3 回答
TA贡献1155条经验 获得超0个赞
以下是您的代码的一些问题:
您没有在 while 循环中增加 j 。你应该
j+=1在循环中的某个地方。您的最后一个打印语句有一个错位的括号。应该是
print(sum(list_trial) / len(list_trial))。最后,假设您正在增加 j,您的 while 循环逻辑 (
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 循环中的检查,那么您根本不需要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...
添加回答
举报
