def find_num():
list = [5, 8, 4, 6, 9, 2]
limit = len(list)
tries = 0
for tries in range(limit):
tries = 1
answer = input("Type a guess: ")
if tries > limit:
break
elif answer == int in list:
print("Correct guess!")
else:
print("Wrong!")
find_num()
該腳本只是要求用戶輸入猜測,而不是檢查該數字是否在串列中并做出相應的回應。限制和嘗試變數是為了讓用戶不能無限地猜測。它作業正常,除了串列中的 elif answer == int 行,它不起作用,因為我無法在串列中指定未知數字。我試過 list[int], x int 和 list[i]。它在 6 次嘗試后中斷回圈,但每次都列印出“錯誤”。
uj5u.com熱心網友回復:
代碼:
def find_num():
lst = [5, 8, 4, 6, 9, 2]
limit = len(lst)
for tries in range(limit):
answer = int(input("Type a guess: "))
if answer in lst:
print("Correct guess!")
else:
print("Wrong!")
tries = 0并且tries = 1在 中沒有必要for loop。- 型別轉換是由
int(answer)not byanswer == int
if tries > limit:
break
- 以上條件
for loop自行測驗。
uj5u.com熱心網友回復:
我已經將它重構為類似的東西。
def find_num():
numbers_to_guess = [5, 8, 4, 6, 9, 2]
limit = len(numbers_to_guess)
tries = 0
while True:
tries = 1
answer = input("Type a guess: ")
if tries > limit:
break
elif int(answer) in numbers_to_guess:
print("Correct guess!")
else:
print("Wrong!")
find_num()
筆記:
- 您可以使用串列作為變數名。這是一個保留關鍵字。
- 您應該使用 while 回圈而不是 for 回圈。
- 您還應該記住在轉換之前檢查輸入的猜測是一個有效的整數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/412106.html
標籤:
