![](/img/trans.png)
[英]Fixing a loop to continue with the program instead asking the same thing again in python
[英]Failed loop: asking the user if they wish to continue (Python)
我為Python 3開發了此代碼,以詢問用戶是否希望繼續:
def dnv():
b = input('Would you like to try again? Type 1 for "yes" and 0 for "no": ')
if b == '1':
return run()
if b == '0':
return print('See you later!')
run()是任何程序的主要功能。 但是現在我正在學習Python 2的課程,並且嘗試將其應用於從那里獲得的算法,但沒有成功。 目的是確定兩個日期之間有多少天。 我相信相關的部分是:
def inputs():
year1 = input('Type the first year: ')
month1 = input('Type the first month: ')
day1 = input('Type the first day: ')
year2 = input('Type the second year: ')
month2 = input('Type the second month: ')
day2 = input('Type the second day: ')
print daysBetweenDates(year1, month1, day1, year2, month2, day2)
def dnv():
answer = input('Would you like to try again? Type "y" for yes and "n" for no: ')
if answer == 'y':
return inputs()
else:
print('See you later!')
我收到一個NameError: name 'y' is not defined
盡管每次我鍵入y或n時, NameError: name 'y' is not defined
(類似於“ n”)。 我還嘗試將if answer == 'y'
修改為:
if answer.lower().startswith('y'):
return inputs()
再次沒有成功。 我想念什么? 謝謝!
使用raw_input()
answer = input('Would you like to try again? Type "y" for yes and "n" for no: ')
如果您使用的是python 2,則需要將輸入更改為:
answer = raw_input("your message here: ")
而且您不需要返回一個函數就可以調用它。
if answer.lower().startswith('y'):
inputs()
如果您使用的是python 3,建議您這樣做:
b = input('Would you like to try again? Type 1 for "yes" and 0 for "no": ')
if b == '1':
return run()
if b == '0':
return print('See you later!')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.