[英]How do I accept yes/no input from user and continue notifying them if they select no
我希望接受用户输入的是/否,如果用户输入是,则代码将继续运行可用的代码,如果用户输入否,则代码将再次通知用户,并且直到用户最终输入“是”后代码才会运行
这是简短的介绍:
# Here is part1 of code
a = input('Have you finished operation?(Y/N)')
if a.lower() == {'yes','y' }
# user input 'y', run part2 code
if a.lower() == {'no', 'n'}
# user input no
# code should notifying user again "'Have you finished operation?(Y/N)'"
# part2 code will run until user finally input 'y'
if a.lower() !={'yes','y', 'no', 'n'}:
# user input other words
# code should notifying user again "'Have you finished operation?(Y/N)'"
# here is part2 of code
您对如何解决此问题有任何想法,如果您能提供一些建议,我将不胜感激
更新资料
这是我正在练习的代码
yes = {'yes','y',}
no = {'no','n'}
print(1)
print(2)
while True:
a = input('Have you create ''manually_selected_stopwords.txt'' ???(Y/N)''')
if a.lower().split() == yes:
break
if a.lower().split() == no:
continue
print(3)
print(4)
当我运行它时,它显示如下,当我第一次尝试输入“ n”然后输入“ y”时,即使我键入“ y”,它也将始终通知我,并且不会打印3和4
1
2
Have you create manually_selected_stopwords.txt ???(Y/N)>? n
Have you create manually_selected_stopwords.txt ???(Y/N)>? y
Have you create manually_selected_stopwords.txt ???(Y/N)>? y
Have you create manually_selected_stopwords.txt ???(Y/N)>? y
Have you create manually_selected_stopwords.txt ???(Y/N)
您的某些测试是不必要的。 如果您输入“ no”与输入“果酱”,您将得到相同的结果。
# Here is part1 of code
while True:
# Calling `.lower()` here so we don't keep calling it
a = input('Have you finished operation?(Y/N)').lower()
if a == 'yes' or a == 'y':
# user input 'y', run part2 code
break
# here is part2 of code
print('part 2')
编辑:
如果要使用set
而不是or
则可以执行以下操作:
if a in {'yes', 'y'}:
您正在将input()
(一个字符串)的结果与一set
相等的字符串进行比较。 他们从不平等。
您可以使用in
检查输入是否在集合中:
链接骗局要求用户输入直到他们给出有效响应后才可解决您的问题:
# do part one
yes = {"y","yes"}
no = {"n","no"}
print("Doing part 1")
while True:
try:
done = input("Done yet? [yes/no]")
except EOFError:
print("Sorry, I didn't understand that.")
continue
if done.strip().lower() in yes:
break # leave while
elif done.strip().lower() in no:
# do part one again
print("Doing part 1")
pass
else:
# neither yes nor no, back to question
print("Sorry, I didn't understand that.")
print("Doing part 2")
输出:
Doing part 1
Done yet? [yes/no] # adsgfsa
Sorry, I did not understand that.
Done yet? [yes/no] # sdgsdfg
Sorry, I did not understand that.
Done yet? [yes/no] # 23452345
Sorry, I did not understand that.
Done yet? [yes/no] # sdfgdsfg
Sorry, I did not understand that.
Done yet? [yes/no] # no
Doing part 1
Done yet? [yes/no] # yes
Doing part 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.