为什么我的 python if 语句不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21790669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:37:27  来源:igfitidea点击:

Why is my python if statement not working?

pythonpython-3.x

提问by user3311991

I hope someone can help me. when I run the below function, no matter what the input, the rules are printed. I can't see what I've done wrong.

我希望有一个人可以帮助我。当我运行下面的函数时,无论输入是什么,都会打印规则。我看不出我做错了什么。

def check_rules():
    while True:
       request = input("\nWould you like to know the rules? (y/n) ")
       if request == "y" or "Y":
           print("""
1. Each player takes it in turn to roll a dice.
2. The player then turns over a card with the same
   number as the number rolled to see how many ladybirds
   there are (0-3).
3. The player keeps the card.
4. If a player rolls a number that is not on an unclaimed
   card, play continues to the next player.
5. Play continues until there are no more cards.
6. The player with the most number of ladybirds wins.""")
           break
        elif request == "n" or "N":
           break
        else:
           print("\nI'm sorry, I didn't understand that.")

采纳答案by pseudocubic

Your if statement is not formed correctly:

您的 if 语句格式不正确:

def check_rules():
    while True:
       request = input("\nWould you like to know the rules? (y/n) ")
       if request in ["y","Y"]:
           print("""
1. Each player takes it in turn to roll a dice.
2. The player then turns over a card with the same
   number as the number rolled to see how many ladybirds
   there are (0-3).
3. The player keeps the card.
4. If a player rolls a number that is not on an unclaimed
   card, play continues to the next player.
5. Play continues until there are no more cards.
6. The player with the most number of ladybirds wins.""")
           break
        elif request in ["n","N"]:
           break
        else:
           print("\nI'm sorry, I didn't understand that.")

Boolean expressions cannot be like if something == x or y, you must state them like if something == x or something == y

布尔表达式不能像if something == x or y,你必须像if something == x or something == y

回答by HahaHortness

The ifstatement doesn't determine whether request equals yor Y. If determines the boolean value of request == "y"which may be false. If it's false it then determines the boolean value of "Y". Since a non empty string evaluates to True request == "y"or "Y"is always true.

if语句不确定 request 是等于y还是Y。如果确定其布尔值request == "y"可能为假。如果为假,则确定 的布尔值"Y"。由于非空字符串的计算结果为 Truerequest == "y""Y"始终为真。