[英]ask for user input again if input is wrong without getting the wrong value in the list
為什么elif b:= 0 and b!= 1: print (b)
不起作用? 用戶必須輸入 1 或 0 才能確定 b。 如果用戶不寫 1 或 0,我希望程序再次詢問他“玩家是計算機 (0) 還是人類 (1)?” 沒有 list_2 附加初始錯誤數字。
list_2 = []
players = int(input("number of players: "))
for i in range (players):
a = input("name of player: ")
b = int(input ("is player a Computer (0) or a human (1)?"))
if b == 0:
list_2.append([a] + [True])
elif b == 1:
list_2.append([a] + [False])
elif b!= 0 and b!= 1:
print (b)
print (list_2)
將該部分輸入包裝在一個while True
循環中。 當輸入正確時打破循環,否則繼續循環以獲得更多輸入。
while True:
b = int(input ("is player a Computer (0) or a human (1)?"))
if b == 0:
# player is a computer ...
# do computer stuff
break
elif b == 1:
# player is a human ...
# do human stuff
break
else:
print("That was not 1 or 0. Please try again")
因為 elif 不是循環,編譯器只是檢查條件,然后繼續執行語句。
您可以通過在第一個 if 條件之前添加一個 ***while 循環 *** 來解決這個問題,如下所示:
for i in range (players): a = input("玩家名稱:") b = int(input ("玩家是計算機 (0) 還是人類 (1)?"))
while (b!=0 and b!=1): # Checking if b is not equal to both '0' and '1'
b = int(input ("is player a Computer (0) or a human (1)?"))
if b == 0:
list_2.append([a] + [True])
elif b == 1:
list_2.append([a] + [False])
elif b!= 0 and b!= 1:
print (b)
您還可以嘗試拆分代碼並創建一個新的checkInput
function,如下所示。
list_2 = [] players = int(input("number of players: ")) def checkInput(value): if value == 0: list_2.append([a] + [True]) return True elif value == 1: list_2.append([a] + [False]) return True else: return False for i in range (players): check = False; a = input("name of player: ") while check == False: b = int(input ("is player a Computer (0) or a human (1)?")) check = checkInput(b) print('Please enter correct input') print (list_2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.