[英]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. 我是python的新手,在学习OOP时,我尝试制作一个脚本,该脚本可以接受用户输入指定数量的条目(或者直到输入诸如“ exit”之类的特殊关键字)并将其写入名为“ entries”的文件中。 txt”,但代码无法按预期运行。 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 我期望输出类似Name的名称:Andrew年龄:20分数: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.
避免使用变量名,例如'a','x'...等,应使用有意义的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.