3 回答

TA貢獻1155條經驗 獲得超0個贊
以下是您的代碼的一些問題:
您沒有在 while 循環(huán)中增加 j 。你應該
j+=1
在循環(huán)中的某個地方。您的最后一個打印語句有一個錯位的括號。應該是
print(sum(list_trial) / len(list_trial))
。最后,假設您正在增加 j,您的 while 循環(huán)邏輯 (
while my_guess != num and j < num_times
) 在第一個有效猜測時退出。
將所有這些放在一起:
num_times = 3
j = 0
list_trial = []
while j < num_times:
my_guess = 0
counter = 0
num = random.randint(1, 3)
while my_guess != num:
my_guess = int(input('Make a guess --> '))
counter += 1
if my_guess < num:
print('Too low!')
elif my_guess > num:
print('Too high!')
else:
print('Finally, you got it !')
print('It took you ' + str(counter) + ' tries...')
list_trial.append(counter)
j += 1
print(list_trial) # prints the number of trials...
print(sum(list_trial) / len(list_trial)) # prints the average of the trials...

TA貢獻1845條經驗 獲得超8個贊
您可以將您拆分while為兩個分開的whiles。一個用于檢查游戲本身num_times的內部和內部while,如下所示:
list_trial = []
num_times = 3
j = 0
while j < num_times:
num = random.randint(1, 1000)
my_guess = 0
counter = 0
while my_guess != num:
my_guess = int(input('Make a guess --> '))
counter += 1
if my_guess < num:
print('Too low!')
elif my_guess > num:
print('Too high!')
else:
print('Finally, you got it !')
print('It took you ' + str(counter) + ' tries...')
list_trial.append(counter)
j += 1
print(list_trial) #prints the number of trials...
print(sum(list_trial) / len(list_trial))

TA貢獻1890條經驗 獲得超9個贊
您可以只使用列表的長度作為 while 循環(huán)中的檢查,那么您根本不需要j變量:
import random
list_trial = []
num_times = 3
while len(list_trial) < num_times:
num = random.randint(1, 1000)
my_guess = 0
counter = 0
while my_guess != num:
my_guess = int(input('Make a guess --> '))
counter += 1
if my_guess < num:
print('Too low!')
elif my_guess > num:
print('Too high!')
else:
print('Finally, you got it !')
print('It took you ' + str(counter) + ' tries...')
list_trial.append(counter)
print(list_trial) #prints the number of trials...
print(sum(list_trial / len(list_trial))) # prints the average of the trials...
添加回答
舉報