while True:
def student_info(name,age,gender):
print("The student name is:",name)
print("The student age is:",age)
print("The student gender is:",gender)
print("*"*70)
Student_name=input("Enter Student name:")
Student_age=input("Enter Student age:")
Student_gender=input("Enter Student gender:")
print("*"*70)
with open('Try1.txt', 'w') as f:
f.write(Student_name+" "+Student_age+" "+Student_gender)
student_info(Student_name,Student_age,Student_gender)
print("if you want add more students press 1 ")
user_input=input("Enter:")
if user_input=="1":
with open('Try1.txt', 'a') as f:
f.write(Student_name+" "+Student_age+" "+Student_gender)
student_info(Student_name,Student_age,Student_gender)
我想在课文中增加更多的学生,但是当我再添加一个学生时,前一个会被删除。.在此方面,我需要帮助。
答案 0 :(得分:1)
首先,在用户未输入1的情况下,您有时需要break
,否则您想进行continue
循环。还有您在代码末尾复制数据插入的地方。
尝试以下方法:
while True:
def student_info(name,age,gender):
print("The student name is:",name)
print("The student age is:",age)
print("The student gender is:",gender)
print("*"*70)
Student_name=input("Enter Student name:")
Student_age=input("Enter Student age:")
Student_gender=input("Enter Student gender:")
print("*"*70)
with open('Try1.txt', 'a') as f:
f.write('\n'+Student_name+" "+Student_age+" "+Student_gender)
student_info(Student_name,Student_age,Student_gender)
print("if you want add more students press 1 ")
user_input=input("Enter:")
if user_input=="1": continue
else: break
答案 1 :(得分:1)
问题在于第一个open
在while
循环内,只是将其带到外面。我在重新格式化您的代码:
def student_info(name,age,gender):
print("The student name is:",name)
print("The student age is:",age)
print("The student gender is:",gender)
while True:
print("*"*70)
Student_name=input("Enter Student name:")
Student_age=input("Enter Student age:")
Student_gender=input("Enter Student gender:")
print("*"*70)
with open('Try1.txt', 'a') as f:
f.write(f"{Student_name} {Student_age} {Student_gender}")
student_info(Student_name, Student_age, Student_gender)
print("if you want add more students press 1 ")
user_input=input("Enter:")
if user_input != "1":
break