在python 3中合并while和if else

时间:2018-07-08 07:10:46

标签: python

我是python的新手,我试图在python中制作一个小游戏“ guess number”,如果输入的数字错误,它将告诉您它的错误,太大或太小,直到您找到正确的。但目前它不会显示太大或太小,只是继续显示错误的数字  这是我的代码(顺便说一句,如果我想设置一个特定的重试时间,该怎么办?例如只能重试3次。)

import random
secret = random.randint(1,10)
guess = int(input("guess a number :"))
while guess != secret:
    guess = int(input("wrong, try again:"))

    if guess == secret:
        print("6666")
        print("88")
    else:
        if guess > secret:
            print("too large")
        else:
            print("too small")

1 个答案:

答案 0 :(得分:1)

首先,修复缩进!在python中,这一点很重要。 这是具有重试功能的示例代码(并非最佳,可以肯定地做得更好):

import random
secret = random.randint(1,10)
guess = -1
num_retries = 3
while guess != secret and num_retries > 0:
    guess = int(input(f"Guess the number [retry {num_retries} out of 3]:"))

    if guess == secret:
        print("6666")
        print("88")
    else:
        if guess > secret:
            print("wrong, too large")
        else:
            print("wrong, too small")

    num_retries -= 1