【问题标题】:High/low game in pythonpython中的高/低游戏
【发布时间】:2021-08-03 04:07:45
【问题描述】:

'''

import random

correct_num = random.randint(0,10)

guess = int(input('What is your guess?'))
while guess != correct_num:
    if guess > correct_num:
        print('Your guess is to big')
    if guess < correct_num:
        print('Your guess is to small')
    else:
        if guess == correct_num:
            print('Yes! You are correct')

'''

这是我目前所拥有的,当我运行代码时,它会无限打印输出。我怎样才能让它给出一个输出并返回另一个猜测?

【问题讨论】:

  • guess = -1开头,这样while循环总是至少运行一次,把guess = int(input(...))放在while循环里面

标签: python loops if-statement while-loop


【解决方案1】:

您可以这样做:

import random

correct_num = random.randint(0,10)


while True:
    guess = int(input('What is your guess?'))
    if guess == correct_num:
        print('Yes! You are correct')
        break
    elif guess > correct_num:
        print('Your guess is to big')
    elif guess < correct_num:
        print('Your guess is to small')


【讨论】:

  • if...elif...elif而不是if的3个独立块
【解决方案2】:

您需要在循环内接受输入。另外,您可以设置guess=-1,因为随机数永远不会是-1,因为它不在范围内。

import random
guess=-1
correct_num = random.randint(0,10)
while guess != correct_num:
    guess = int(input('What is your guess?'))
    if guess > correct_num:
        print('Your guess is to big')
    if guess < correct_num:
        print('Your guess is to small')
    else:
        if guess == correct_num:
            print('Yes! You are correct')

【讨论】:

    【解决方案3】:

    您可以在 if 语句的末尾添加关键字 break,您的问题就解决了。顺便说一句,您也可以尝试让用户说 3 次尝试。在我们的例子中,它只有 1 次尝试。

    
    import random
    
    correct_num = random.randint(0,10)
    
    guess = int(input('What is your guess?'))
    
    while guess != correct_num:
    
        if guess > correct_num:
            print('Your guess is to big')
            break
        elif guess < correct_num:
            print('Your guess is to small')
            break
        else:
            if guess == correct_num:
                print('Yes! You are correct')
                break
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-18
      • 2020-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-11
      • 1970-01-01
      相关资源
      最近更新 更多