Python 3.6.5。为什么OR不能像我期望的那样工作?

时间:2018-06-07 12:59:22

标签: python python-3.6

为什么我使用OR !!!即使我在猜测输入中输入数字1 - 9,它是否会中断。为什么我不需要输入'q'和'quit',因为这就是我所假设的并且意味着......'q'和'退出'......

import random

    while True:
        print("\nGuess a number between 1 and 9.")
        guess = input("I guess: ")

        if guess == 'q' !!!or!!! 'quit':
            break

        number = random.randrange(1, 10)
        try:
            if int(guess) < number:
                print(f"You guess was too low. The number was {number}")
            elif int(guess) > number:
                print(f"Your guess was too high. The number was {number}")
            elif int(guess) == number:
                print(f"Your guess was exactly right! The number was {number}")
        except ValueError:
            print("Please only guess numbers!")

所以使用OR它不起作用,而且它确实如此。这对我来说毫无意义。这是为什么?

1 个答案:

答案 0 :(得分:1)

if guess == 'q' or 'quit':

此语句不起作用,因为您尝试将字符串用作布尔值。 OR并不假设你想要像之前一样发生完全相同的事情,你必须再次填补条件。

if guess == 'q' or guess == 'quit':

这样可行,因为您现在从右侧获取布尔值,而不是仅仅尝试使用字符串。