[英]Checking 2 different user inputs in for loop in Python
我對此很陌生,並試圖循環遍歷一系列數字,直到 2 個不同的用戶對特定數字說“是”。
如果兩個用戶都對一個數字說是,我希望程序打印“你們都選擇了 [X]!” X 是數字,循環在此時停止。
但是,如果任一用戶拒絕,我希望循環簡單地繼續到下一個數字。 為什么下面的代碼不能實現這一目標?
for i in range(100):
user1_response = input("User One: Would you like to pick " + str(i) + "? ")
user2_response = input("User Two: Would you like to pick " + str(i) + "? ")
if (user1_response == "N" or "No" or "Reject") or (user2_response == "No" or "N" or "Reject"):
continue
else:
print("")
print("Both users picked" + str(i) + "!")
break
if (user1_response == "N" or "No" or "Reject")
被解讀為
if ([[user1_response == "N"]] or [["No"]] or [["Reject"]])
所以user1_response == "N"
可能會返回True
或False
。 No
和Reject
本質上都將返回True
。
你可能想要的是
if (user1_response in {"N","No","Reject"})
所以我們創建了一個文字集{"N","No","Reject"}
,我們正在查看user1_response
是否在該集合中。
代碼"No" or "Reject"
被轉換為布爾值True
。 您將需要檢查輸入是否分別等於每個。
在這里,試試這個:
#list of strings that are classified as 'rejections'
rejections = ["no", "N", "n", "Reject"]
#starts our while loops
for i in range(100):
user1_response = input("User One: Would you like to pick " + str(i) + "? ")
user2_response = input("User Two: Would you like to pick " + str(i) + "? ")
if user1_response in rejections or user2_response in rejections:
continue
else:
print("")
print("Both users picked " + str(i) + "!")
break
我對此也很陌生,但希望我可以通過添加接近您的技能水平的視角來提供幫助
neg= ["n", "no", "reject"]
pos= ["y", "yes", "accept"]
##positive and negative lists to easily check for a cass unsensitive response
for i in range(100):
user1= input("User 1 : Would you like to pick "+ str(i)+ "?")
user2= input("User 2 : Would you like to pick "+ str(i)+ "?")
## I suggest making your variable names a little shorter
##Adding .lower() allows users to enter "n' or "N" etc.
if user1.lower() in neg or user2.lower() in neg:
continue
elif user1.lower() in pos and user2.lower() in pos:
break
print"Both users guessed number "+str(i)
在我看來,這個解決方案相當容易理解,並且如果您要與他人分享您所做的事情,其他新開發人員也很容易使用。
條件是有問題的。
(user1_response == "N" 或 "No" 或 "Reject") 僅當 user1_response == "N" 評估為 True
但是,如果 user1 和 user2 都鍵入“Y”(user1_response ==“N”或“No”或“Reject”)計算結果為“No”並且(user2_response ==“No”或“N”或“Reject”)計算結果對“N”
組合語句 (user1_response == "N" or "No" or "Reject") or (user2_response == "No" or "N" or "Reject") 評估為 "No"
並且“No”將觸發代碼的“if”部分,因為“No”不等同於布爾值 False。 因此,不會到達代碼的“其他”部分。
這是一種可能的解決方案:
if user1_response in ("N","No","Reject") or user2_response in ("No","N","Reject"):
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.