我希望接受用户输入为是/否,如果用户输入是,代码将继续运行可用代码,用户输入否,代码将再次通知用户,代码将不会运行,直到用户输入'是'终于
以下是简要介绍:
# 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)
答案 0 :(得分:2)
您的一些测试是不必要的。如果输入“no”键入“marmalade”,则会得到相同的结果。
# 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'}:
答案 1 :(得分:1)
您正在比较input()
(字符串)的结果与set
字符串的相等性。他们永远不平等。
您可以使用in
检查输入是否在集合中:
链接的欺骗asking-the-user-for-input-until-they-give-a-valid-response适用于您的问题:
# 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