简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM