卡在错误之间

时间:2019-05-13 15:51:52

标签: python python-3.x

我是一个绝对的初学者,正在练习“猜数字”这个项目,我写了下面的代码,想知道我犯了什么样的错误。

import random
guess_count = 3
number = random.randint(1, 9)

while guess_count > 0:
    guess = int(input("Guess: "))
    guess_count -= 1


    if guess == number:
        print("Congrats You Won!")
        guess_count = 0
    else:
        print("You Lose, Better luck next time.")
        print('')
        print(f"The correct number was {number}.")

输出结果就是这样,

Guess: 2
You Lose, Better luck next time.

The correct number was 6.
Guess:  6
Congrats You Won!

预期的失败输出:

  Guess: 3
  Guess: 4
  Guess: 5
You Lose, Better luck next time.

3 个答案:

答案 0 :(得分:1)

随机导入 guess_count = 3 数字= random.randint(1,9)

while guess_count > 0:
    guess = int(input("Guess: "))
    guess_count -= 1


    if guess == number:
        print("Congrats You Won!")
        guess_count = 0
    else:
        print("You Lose, Better luck next time.")
        print('')
        print("The correct number was ", number , " .")

答案 1 :(得分:1)

在猜测正确时,使用break结束循环。

else:块放在while循环中。如果循环在没有break的情况下结束,则将执行该循环,当它们用尽了所有猜测时就会发生。

import random
guess_count = 3
number = random.randint(1, 9)

while guess_count > 0:
    guess = int(input("Guess: "))
    guess_count -= 1

    if guess == number:
        print("Congrats You Won!")
        break
else:
    print("You Lose, Better luck next time.")
    print('')
    print(f"The correct number was {number}.")

答案 2 :(得分:1)

格式化问题的另一种方法,而是使用for循环:

import random

guess_count = 3
number = random.randint(1, 9)

for x in range(0, guess_count):
    guess = int(input("Guess: "))

    if guess == number:
        print("Congrats You Won!")
        break # exit loop
    else:
        print("You Lose, Better luck next time.")
        print('')

        if x == guess_count - 1:
            print(f"The correct number was {number}.")