亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python:確保字符串是用戶的有效輸入,并拒絕任何其他輸入

Python:確保字符串是用戶的有效輸入,并拒絕任何其他輸入

慕俠2389804 2024-01-15 21:09:49
嘗試配置我的程序,使其僅在整個程序中接受“是”和“否”的答案,并且任何其他輸入(例如整數和其他字符串)都會產生錯誤消息。使用 .isalpha() 也不適合我,任何有關如何幫助編寫代碼的提示將不勝感激。text = True    if text:        textHelp = input('Are you sleeping? '.isalpha())        if textHelp == 'yes':            print('Cannot take phone call b/c im sleeping')        else:            print('Can take phone call)
查看完整描述

3 回答

?
慕工程0101907

TA貢獻1887條經驗 獲得超5個贊

根據您的描述,您要尋找的是這樣的:


input_text = input('Are you sleeping? ').lower()


if input_text == 'yes':

  print('Cannot take phone call b/c im sleeping')

elif input_text == 'no':

  print('Can take phone call')

else:

  print('Expected a yes or a no for an answer')

Thr.lower()方法確保“Yes”、“yes”、“yEs”等得到相同的處理。您不需要.isalpha()此場景的方法。


查看完整回答
反對 回復 2024-01-15
?
楊魅力

TA貢獻1811條經驗 獲得超6個贊

我想這就是您正在尋找的。


while true:

? ? textHelp = input('Are you sleeping? ')

? ? if textHelp.isalpha():

? ? ? ? # your expected output ...

? ? ? ? break

? ? else:

? ? ? ? print("try again!")


查看完整回答
反對 回復 2024-01-15
?
慕無忌1623718

TA貢獻1744條經驗 獲得超4個贊

您可以嘗試使用 if..elif..else:


if textHelp == 'yes':

    print('Cannot take phone call b/c im sleeping')

elif textHelp == 'no':

    print('Can take phone call')

else:

   print("Faulty message")

如果您想在無效輸入時保持提示繼續:


while True:

  if textHelp == 'yes':

    print('Cannot take phone call b/c im sleeping')

    break

  elif textHelp == 'no':

    print('Can take phone call')

    break

  else:

   print("Faulty message")


查看完整回答
反對 回復 2024-01-15
  • 3 回答
  • 0 關注
  • 187 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號