Python 3.x 使用有限的用户提示输入写入文件
我需要一个代码,提示用户输入名称和数字,但最大值为3。然后,它将代码写入一个空文本文件,即使名称只有2或3Python 3.x 使用有限的用户提示输入写入文件,python-3.x,Python 3.x,我需要一个代码,提示用户输入名称和数字,但最大值为3。然后,它将代码写入一个空文本文件,即使名称只有2或3 name = True while name: if name == "done entering": name = False break else: name = True firstName1 = input("Enter your first Name: ") lastName1 = i
name = True
while name:
if name == "done entering":
name = False
break
else:
name = True
firstName1 = input("Enter your first Name: ")
lastName1 = input("Enter your last Name here: ")
studentID1 = input("Enter your id number: ")
firstName2 = input("Enter your first Name: ")
lastName2 = input("Enter your last Name here: ")
studentID2 = input("Enter your id number: ")
firstName3 = input("Enter your first Name: ")
lastName3 = input("Enter your last Name here: ")
studentID3 = input("Enter your id number: ")
break
inFile = open("studentInfo.txt", 'a')
inFile.write("Name: " + firstName1 + " " + lastName1)
inFile.write("\nStudentID: " + studentID1)
inFile.write("Name: " + firstName2 + " " + lastName2)
inFile.write("\nStudentID: " + studentID2)
inFile.write("Name: " + firstName3 + " " + lastName3)
inFile.write("\nStudentID: " + studentID3)
inFile.close()
print("\nDone! Data is saved in file: studentInfo.txt")
我复制粘贴了我的第一个代码,它可以正常工作,但每当我在Python解释器中运行它时,“输入名字”之前都有一个“y”,我不能只输入2个名字,它需要3个。我怎样才能把它也缩短。。。TY我无法在“输入名字”行为之前复制“y”。也许是
在您的环境中复制并粘贴问题
若要输入少于3个条目,则需要限制为3个条目,并且可以
允许少于3个。这可能需要不同的数据处理,如使用列表
创建一个列表以存储3组条目。列表有长度,所以使用
作为while语句的列表长度。循环将在3组后结束
参赛作品的数量
如果first name条目为空,则从循环中中断,因为这意味着没有更多
输入。如果其他项为空,则继续循环,以便用户可以重做组。
在每个循环结束时将条目组追加到列表中。
如果愿意,这些中断或继续的条件可以改变
循环结束时,如果列表为空,则将脚本结束为“无事可做”
可以使用for循环编写文件。使用格式化字符串,以便
组可以写成一个组。格式化允许进一步对齐等
studentInfo = []
while len(studentInfo) < 3:
firstName = input("Enter your first Name: ")
if firstName == '':
break
lastName = input("Enter your last Name here: ")
if firstName == '':
continue
studentID = input("Enter your id number: ")
if studentID == '':
continue
studentInfo.append([firstName, lastName, studentID])
print()
if not studentInfo:
exit()
fileName = "studentInfo.txt"
inFile = open(fileName, 'a')
for firstName, lastName, studentID in studentInfo:
inFile.write("Name: {} {}\n"
"StudentID: {}\n"
.format(firstName, lastName, studentID)
)
inFile.close()
print("Done! Data is saved in file: " + fileName)
studentInfo=[]
而len(studentInfo)<3:
firstName=输入(“输入您的名字:”)
如果firstName='':
打破
lastName=input(“在此处输入您的姓氏:”)
如果firstName='':
持续
studentID=输入(“输入您的id号:”)
如果studentID='':
持续
append([firstName,lastName,studentID])
打印()
如果不是学生信息:
退出()
fileName=“studentInfo.txt”
infle=open(文件名“a”)
对于studentInfo中的firstName、lastName和studentID:
write(“名称:{}{}\n”
“StudentID:{}\n”
.格式(名字、姓氏、studentID)
)
infle.close()
打印(“完成!数据保存在文件:”+文件名中)