![](/img/trans.png)
[英]how can i make sure that the user inputs a string containing only numbers, operators, and letter Q?
[英]how to make sure user inputs a given set of numbers in python
我正在嘗試用 python 制作一個程序,其中用戶只能輸入 1、2 或 3。我嘗試過這種方法,但它不起作用。`
x = input("Enter your Choice: ")
while (x!=1 or x!=2 or x!=3):
x = input("Enter your Choice: ")
使用這種方法,即使輸入了 1、2 或 3 或任何其他數字,它也會不斷要求輸入。誰能告訴我為什么這不起作用,並建議輸入這三個數字的正確方法。
這就是我們所說的邏輯錯誤。
該行應該是這樣的:
while (x!=1 and x!=2 and x!=3):
也就是說,將or更改為and 。
要處理任何輸入並在它不是 1,2 或 3 時發出錯誤,請執行以下操作:
x = raw_input("Enter your Choice: ")
while (x!='1' and x!='2' and x!='3'):
x = raw_input("Enter your Choice: ")
嘗試:
def userchoicevalidator():
x = input("Please Enter Your Choice: ")
while x not in list('123'):
x = input("Please Enter Your Choice: ")
raw_input
對您不起作用的原因是它在 python 3 中已被棄用。 input
在 python 3 中。另請注意,這返回一個字符串,而不是一個整數,這就是為什么您的布爾值檢查意外失敗的原因
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.