[英]Python - Creating generic functions for unspecified input
如果用戶鍵入的不是1-5,我希望該程序可以打印出一個答案,說“對不起,我無法識別該輸入”。
import time
rating=input()
if rating == '1':
time.sleep(.5)
print('Well, you mustve just had a bad day.')
if rating =='2':
time.sleep(.5)
print('Second to last means I wasnt even the best at losing...')
if rating =='3':
time.sleep(.5)
print('Atleast thats almost passing.')
if rating =='4':
time.sleep(.5)
print('Im offended.')
if rating =='5':
time.sleep(.5)
print('Well yeah, obviously.')
使用if
, elif
以及else
,如果輸入的內容不是1,2,3,4,5,則代碼中的else
將打印您要顯示的消息。 下面的代碼也將由於elif
阻止檢查所有其他數字。 在您的代碼中,您正在檢查5 if語句中的所有數字。
import time
rating=input()
if rating == '1':
time.sleep(.5)
print('Well, you mustve just had a bad day.')
elif rating =='2':
time.sleep(.5)
print('Second to last means I wasnt even the best at losing...')
elif rating =='3':
time.sleep(.5)
print('Atleast thats almost passing.')
elif rating =='4':
time.sleep(.5)
print('Im offended.')
elif rating =='5':
time.sleep(.5)
print('Well yeah, obviously.')
else:
print ('Sorry I dont recognize that input')
再次詢問用戶,直到輸入正確的號碼為止 (根據下面的評論)
while rating:
if rating == '1':
time.sleep(.5)
print('Well, you mustve just had a bad day.')
break
elif rating =='2':
time.sleep(.5)
print('Second to last means I wasnt even the best at losing...')
break
elif rating =='3':
time.sleep(.5)
print('Atleast thats almost passing.')
break
elif rating =='4':
time.sleep(.5)
print('Im offended.')
break
elif rating =='5':
time.sleep(.5)
print('Well yeah, obviously.')
break
else:
print ('Sorry I dont recognize that input. Enter the rating again.')
rating=input()
continue
輸出(第二種情況)
6
Sorry I dont recognize that input. Enter the rating again.
6
Sorry I dont recognize that input. Enter the rating again.
5
Well yeah, obviously.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.