Skip to main content
 首页 » 编程设计

python之基本的 if 语句在 Python 中如何工作

2025年05月04日19davidwang456

我从 python 开始,遇到这个嵌套练习的基本问题:

bird_names="eagle", "pigeon", "colibri", "seagull" 
 
bird_guess=input("Guess the bird: ") 
 
if bird_guess in bird_names == False: 
    print("Try again") 
    bird_guess2=input("Guess the Bird: ")    
 
    if bird_guess2 in birds == False: 
        print("Try again") 
        bird_guess3=input("Guess the Bird: ")  
 
        if bird_guess3 in birds == False: 
            print("Sorry out of tries")      
        else: 
            print("Yes 3rd try") 
    else: 
        print("Yes 2rd try") 
else: 
    print("Great, 1st try") 

例如,当我运行它并向 bird_guess 赋值 d 时,代码直接输出 Great, 1st try 而不是通过所有其他 if 语句。

知道我的错误在哪里吗?

请您参考如下方法:

这个:

if bird_guess in bird_names == False: 

等同于:

if bird_guess in bird_names and bird_names == False: 

你应该这样做:

if bird_guess not in bird_names: 

检查一个项目是否不在列表中。

您的原始表达式不起作用的原因是 comparison chaining .在 Python 中,可以将任意数量的比较链接在一起,例如 x < y <= z相当于x < y and y <= z .因此 a in b == False将变为 a in b and b == False .