编写一个while循环,询问用户为何喜欢编程。每当用户输入一个原因后,都将其添加到一个存储所有原因的文件中
reason2_file ='reason2.txt'
reasons = []
while True:
reason = input('你为什么喜欢编程?\n')
reasons.append(reason)
controll_poll = input('你想让下一个人参与吗?(Y/N)')
if controll_poll != 'Y':
break
else:
with open(reason2_file,'a') as f:
for reason in reasons:
f.write(reason)
运行之后,无法将reasons写入到 txt中是为啥呢?整体逻辑感觉没啥问题啊
因为if else判断语句,在输入不等于Y时循环终止,不会执行else语句,也就不会写入文件。还有代码中也不需要append。参考如下修改代码:
reason2_file ='reason2.txt'
reasons = []
while True:
reason = input('你为什么喜欢编程?\n')
with open(reason2_file,'a') as f:f.write(reason+'\n')
controll_poll = input('你想让下一个人参与吗?(Y/N)')
if controll_poll == 'Y':
continue
else:
break
如对你有帮助,请点采纳按钮。
因为当最后if判断输入的等于Y时退出循环,不会执行else语句,这样最后一个输入不会写到文件中。
并且循环中每次都写入整个列表,这样前面的输入会重复的写入到文件中
with open(reason2_file,'a') as f: 应该放在while外面
reason2_file ='reason2.txt'
reasons = []
while True:
reason = input('你为什么喜欢编程?\n')
reasons.append(reason)
controll_poll = input('你想让下一个人参与吗?(Y/N)')
if controll_poll != 'Y':
break
with open(reason2_file,'a') as f:
for reason in reasons:
f.write(reason+'\n')
或者不用列表:
reason2_file ='reason2.txt'
with open(reason2_file,'a') as f:
while True:
reason = input('你为什么喜欢编程?\n')
f.write(reason+'\n')
controll_poll = input('你想让下一个人参与吗?(Y/N)')
if controll_poll != 'Y':
break
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!