代码跳过print()函数,直接中断

时间:2019-05-19 23:24:13

标签: python python-3.x python-requests

我正在编写一个游戏代码,其中计算机从1到100中选择一个随机数,然后玩家必须弄清楚数字是多少。当您猜数字时,系统会告诉您数字是高还是低。

当您猜到数字时,应该打印一条消息,说您猜对了,此后它应该中断。当您猜到数字时,它会完全跳过打印功能并中断。

我什么都没尝试过,因为我不知道该怎么做。我在编程方面还很陌生。

代码如下:

import random
num = random.randint(1, 100)
guess = int(input("Guess which number I chose from 1 to 100: "))

while guess != num:
    if guess > num:
        print ("That number is too high")
        guess = int(input("Guess which number I chose from 1 to 100: "))
    elif guess < num:
        print ("That number is too low")
        guess = int(input("Guess which number I chose from 1 to 100: "))
    elif guess == num:
        print ("You guessed it! Want to play again?")
        option = input("Press Y for yes or N for no: ")
        if option.lower() == "y":
            guess = int(input("Guess which number I chose from 1 to 100: "))
        elif option.lower() == "n":
            break
        else:
            print ("Not valid")
            break

没有错误消息。找到号码后,代码就会中断。

2 个答案:

答案 0 :(得分:1)

看看while循环中的情况

while guess != num:

因为您在循环结束时读取了猜测,所以在得到猜测之后,代码将立即检查while条件。因此,当您猜测正确时,while条件将失败,并退出循环。由于您已经休息了,可以通过将其更改为

来解决此问题
while True:

答案 1 :(得分:0)

尝试此代码。可行,我改变了条件。

import random
num = random.randint(1, 100)
guess = int(input("Guess which number I chose from 1 to 100: "))
option = 'y'
while (option.lower() == 'y'):
    if guess > num:
        print ("That number is too high")
        guess = int(input("Guess which number I chose from 1 to 100: "))
    elif guess < num:
        print ("That number is too low")
        guess = int(input("Guess which number I chose from 1 to 100: "))
    else:
        print ("You guessed it! Want to play again?")
        option = input("Press Y for yes or N for no: ")
        if option.lower() == 'y':
            guess = int(input("Guess which number I chose from 1 to 100: "))
        elif option.lower() == 'n':
            break
        else:
            print ("Not valid")
            break
相关问题