4 回答

TA貢獻1757條經(jīng)驗 獲得超8個贊
如果要稍后將輸入與整數(shù)進行比較,則需要將輸入從字符串轉(zhuǎn)換為整數(shù)。如果你想避免一遍又一遍地重復(fù)邏輯,你可以使用列表。
user_choice = int(input("Please choose from the following: \n" " 1 for scissor \n" " 2 for rock \n" " 3 for paper. \n"))
和
while user_choice not in [1,2,3]

TA貢獻1942條經(jīng)驗 獲得超3個贊
在單個循環(huán)中執(zhí)行整個提示/驗證。在滿足條件之前,用戶無法繼續(xù)
print("This program simulates a 'rock paper scissor' game.")
print("The rules are as follows: rock beats scissor, paper beats rock, and scissor beats paper. \n")
print("This program simulates a 'rock paper scissor' game.")
print("The rules are as follows: rock beats scissor, paper beats rock, and scissor beats paper. \n")
#get user input
while True:
user_choice = input("Please choose from the following: \n"
" 1 for scissor \n"
" 2 for rock \n"
" 3 for paper. \n")
#validate input so user only enters 1, 2, or 3
if user_choice in ["1", "2", "3"]:
int_user_choice = int(user_choice)
break

TA貢獻1851條經(jīng)驗 獲得超5個贊
您的不正確,因為輸入返回字符串類型,并且您正在使用類型int進行檢查,因此請在循環(huán)中更改類型。此外,如果希望它在其中一種情況下終止,則不能使用,在這種情況下,您必須使用 。orand
print("This program simulates a 'rock paper scissor' game.")
print("The rules are as follows: rock beats scissor, paper beats rock, and scissor beats paper. \n")
print("This program simulates a 'rock paper scissor' game.")
print("The rules are as follows: rock beats scissor, paper beats rock, and scissor beats paper. \n")
#get user input
user_choice = input("Please choose from the following: \n"
" 1 for scissor \n"
" 2 for rock \n"
" 3 for paper. \n")
#validate input so user only enters 1, 2, or 3
while user_choice != '1' and user_choice != '2' and user_choice != '3':
user_choice = input("Please enter only '1' for scissor, '2' for rock, or '3' for paper: ")
#convert input to int
int_user_choice = int(user_choice)

TA貢獻1821條經(jīng)驗 獲得超5個贊
獲得輸入后,您可以檢查兩個輸入是否都是有效數(shù)字并且它是否在有效范圍內(nèi),如果兩個條件之一不成立,請再次請求輸入。
valid_choices = {1,2,3}
while not user_choice.isdigit() and not int(user_choice) in valid_choices:
user_choice = input("Please enter only '1' for scissor, '2' for rock, or '3' for paper: ")
或更簡單地說
valid_choices = {'1','2','3'}
while not user_choice in valid_choices:
user_choice = input("Please enter only '1' for scissor, '2' for rock, or '3' for paper: ")
添加回答
舉報