如何使有条件的while循环重复该过程n次?

时间:2019-04-05 04:04:03

标签: python iteration

我有一个简单的猜数字游戏,我想做的是,一旦用户猜对了正确的随机数,我想将试验的计数数存储在列表中。假设用户在9个试验中找到了数字,则9个将存储在列表中,但我想运行3次游戏,并将这3个试验存储在列表中,然后取平均值。我遇到的问题是用户一次找到n次,将其放在列表中,但不会继续。 1场比赛后停止。如何使其运行3次?任何帮助,将不胜感激。谢谢!

import random
def main():

    num = random.randint(1, 1000)

    my_guess = 0
    counter = 0
    list_trial = []
    num_times = 3
    j = 0

    while my_guess != num and j < num_times:
        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...

main()

3 个答案:

答案 0 :(得分:1)

您的代码有一些问题:

  • 您不会在while循环中递增j。您应该在循环中的某处放置一个<input type="button" class="btn btn-primary btn-lg float-right" value="Edit Assessment" onclick="location.href='@Url.Action("EditAssessment", "Assessments", new { id = ViewData["ProfileId"] })'" />

  • 您的最后一个打印语句的括号位置错误。应该是j+=1

  • 最后,假设您要递增j,则您的while循环逻辑(print(sum(list_trial) / len(list_trial)))将在第一个有效猜测时退出。

将所有这些放在一起:

while my_guess != num and j < num_times

答案 1 :(得分:0)

您可以将while分成两个分开的while。用于检查游戏本身的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))

答案 2 :(得分:0)

您可以将列表的长度用作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...