我正在尝试创建一个程序,计算机在其中选择1到100之间的随机数,然后尝试猜测它选择的数字

时间:2017-10-31 02:58:24

标签: python python-3.x random while-loop conditional-statements

我是Python的新手,我只是编写一些随机的东西以获得乐趣。我想写一个程序,其中计算机生成1到100之间的随机数,然后尝试猜测它。我不希望用户以任何方式干扰它。我还想知道计算机有多少猜测。我也试图让它每次运行多次,使用不同的数字,并计算在这些时间后的平均猜测量。我知道我需要合并一个while循环,但我不知道如何让计算机继续猜测随机数而不是只列出范围内的每个数字,我该如何告诉它停止?我需要一个for循环吗?有人可以帮忙吗?

import random

the_num = random.randint(1, 100)
print('The number to guess is',the_num)
comp_guess = random.randint(1, 100)
print('The computer guesses ', comp_guess)
tries = 1

while comp_guess != the_num:
    print('The computer guesses ', comp_guess)
    tries = tries+1
    if comp_guess > the_num:
        comp_guess = comp_guess-1
    elif comp_guess < the_num:
        comp_guess = comp_guess+1
    elif comp_guess == the_num:
        break

print(tries)
print('The computer guessed it right!')

1 个答案:

答案 0 :(得分:0)

轻微改变:一旦计算机无法猜测它需要继续猜测,因为以下行不在(while)循环中,它不会发生:

comp_guess = random.randint(1, 100)

修复很简单(参见下面的代码注释):

import random

the_num = random.randint(1, 100)
print('The number to guess is',the_num)
comp_guess = random.randint(1, 100)
print('The computer guesses ', comp_guess)
tries = 1

while comp_guess != the_num:
    print('The computer guesses ', comp_guess)
    tries += 1
    if comp_guess == the_num:
        break
    else:     # if the computer didn't guess it, guess again!
        comp_guess = random.randint(1, 100)

print(tries)
print('The computer guessed it right!')

现在,如果你想重复几遍整个逻辑,把它放在一个函数中并在一个循环中调用它:

import random


def guess():
    the_num = random.randint(1, 100)
    print('The number to guess is',the_num)
    comp_guess = random.randint(1, 100)
    print('The computer guesses ', comp_guess)
    tries = 1

    while comp_guess != the_num:
        print('The computer guesses ', comp_guess)
        tries += 1
        if comp_guess == the_num:
            break
        else:
            comp_guess = random.randint(1, 100)

    print(tries)
    print('The computer guessed it right!')


for i in range(5):
    guess()