azoth
azoth

Reputation: 3

How can I make this script to take loop input?

I am new to python and while learning OOP I tried to make a script which can take user input for a specified number of entries(or maybe until a special keyword is entered like "exit") and write it to a file named "entries.txt" but the code is not working as expected. Can someone guide me or modify my code? Thanks!!

num = int(input("number of students: "))

n = input("Name : ")
a = input("Age : ")
m = input("Marks : ")


class Students:
def __init__(self, n, a, m):
    self.name = n
    self.age = a
    self.marks = m


def file(self):
    for i in range(1,num):
        with open("entries.txt","a+") as f:
            f.write("Name : %s \n" %self.name)
            f.write("Age : %s \n" %self.age)
            f.write("Marks : %s \n" %self.marks)
            f.write("----------------------------------------- \n")


s1 = Students(n, a, m)

s1.file() 

i am expecting an output something like Name : Andrew Age : 20 Marks: 55

then program should not exit just ask for another entry.

Upvotes: 0

Views: 29

Answers (1)

adnanmuttaleb
adnanmuttaleb

Reputation: 3624

num = int(input("number of students: "))

class Student:
    def __init__(self, n, a, m):
        self.name = n
        self.age = a
        self.marks = m

    def file(self):
        with open("entries.txt","a+") as f:
            f.write("Name : %s \n" %self.name)
            f.write("Age : %s \n" %self.age)
            f.write("Marks : %s \n" %self.marks)
            f.write("----------------------------------------- \n")

for i in range(num):
    n = input("Name : ")
    a = input("Age : ")
    m = input("Marks : ")

    s1 = Student(n, a, m)
    s1.file() 

A few notes on naming: Name class as singular not plural. Avoid variable name like 'a', 'x'...etc, you should use meaningful name.

Upvotes: 1

Related Questions