0 < 2 = ...错误?

0 < 2 = ...False?

Python 3.7

正在尝试做一个猜数游戏。这是我的代码:

#This is the guess the number game!
import random
secretNumber = random.randint(0,20)

print('I am thinking of a secret number between 0 and 20, can you guess what it is in six tries or less?')

for guessTimes in range(1,7):
    try:
        guessNumber = int(input())
        print(type(guessNumber))
        print('Guess Number: ' +str(guessNumber))
    except ValueError:
        guessNumber = None
        print('Secret Number: ' +str(secretNumber))
        print('You have to give me a valid integer for your guess.', end = ' ')
    if guessNumber and guessNumber < secretNumber:
        print('You have guessed a number that is too low...')
    elif guessNumber and guessNumber > secretNumber:
        print('You have guessed a number that is too high...')
    elif guessNumber and guessNumber == secretNumber:
        print('Great job, you guessed the secret number in only ' +str(guessTimes)+ ' tries!')
        print('You should go PRO!')
        break
    if guessTimes > 6:
        print('Sorry, that was six tries and lots of fail, better luck next time!')
    elif guessTimes == 1:
        print('That is ' +str(guessTimes)+ ' failed attempt thus far, you have ' +str(6-guessTimes)+ ' chances remaining. Please try again.')
    elif guessTimes > 1:
        print('That is ' +str(guessTimes)+ ' failed attempts thus far, you have ' +str(6-guessTimes)+ ' chances remaining. Please try again.')
    guessTimes += 1
    continue

对于介于 1 和 123,412,351 之间的所有 guessNumber 值,这一切似乎都工作得很好。但出于某种原因,每当我输入 0 作为 guessNumber 时,代码都会跳过该行:

if guessNumber and guessNumber < secretNumber:
        print('You have guessed a number that is too low...')

很抱歉,这不是一个超级相关的问题,但我已经为此苦苦思索了一段时间,无法弄清楚为什么当 guessNumber 时该行的计算结果不为 True == 0.

如果在 if 等条件语句中使用的数字将被视为 boolean(如果为 0,则为 false,否则为 true)

if guessNumber and guessNumber < secretNumber:
     print('You have guessed a number that is too low...')

if 语句中有两个条件,第一个条件为假,因为输入 0 的 guessNumber 为假,因此该行被跳过。

从条件中删除 guessNumber 就可以了

if guessNumber < secretNumber:
     print('You have guessed a number that is too low...')

None0在Python中都是"falsy",所以if guessNumber and guessNumber < secretNumber:在测试guessNumber时短路,因为它是[=12] =] 和 0 是假的。

您需要缩小检查范围以仅捕获 None,将 if guessNumber and ...: 形式的测试更改为 if guessNumber is not None and ...:

另一种解决方案是在给出无效值时避免完全检查猜测。您可以通过从 try/except 扩展到 try/except/else:

来相当容易地做到这一点
for guessTimes in range(1,7):
    try:
        guessNumber = int(input())
        print(type(guessNumber))
        print('Guess Number: ' +str(guessNumber))
    except ValueError:
        print('Secret Number: ' +str(secretNumber))
        print('You have to give me a valid integer for your guess.', end = ' ')
    else:
        # Only run when no ValueError occurs
        if guessNumber < secretNumber:
            print('You have guessed a number that is too low...')
        elif guessNumber > secretNumber:
            print('You have guessed a number that is too high...')
        elif guessNumber == secretNumber:
            print('Great job, you guessed the secret number in only ' +str(guessTimes)+ ' tries!')
            print('You should go PRO!')
            break

    if guessTimes == 1:
        print('That is ' +str(guessTimes)+ ' failed attempt thus far, you have ' +str(6-guessTimes)+ ' chances remaining. Please try again.')
    else:
        print('That is ' +str(guessTimes)+ ' failed attempts thus far, you have ' +str(6-guessTimes)+ ' chances remaining. Please try again.')
else:
    # Run when loop exits without break
    print('Sorry, that was six tries and lots of fail, better luck next time!')

这里的优点是你根本不用设置或测试 guessNumber 当它是垃圾时(不使用 None 作为标志值等),所以当它不是垃圾时,您根本不需要检查 None 的标志。

旁注:在新代码中,我删除了 guessTimes += 1continue,因为 for i in range(1, 7): 已经为您完成了增量,并且 continue因为循环中的最后一条语句是荒谬的。我还将 "too many guesses" 输出移动到 for 循环上的 else;您永远不会按编写的方式点击该代码(因为循环以 guessTimes 结束,因为 6guessTimes > 6 始终为假),并且它会保存检查以使其自动发生,如果循环结束时没有 break.