簡體   English   中英

我如何接受用戶的是/否輸入,如果他們選擇否,則繼續通知他們

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM