首页 > 解决方案 > Python缩进不清楚

问题描述

试图了解缩进在 Python 中是如何工作的。

var = 100                
if ( var == 100 ) :                      
    print ("Value of expression is 100")                 
    print ("Good bye!")
print("AM I out?")

输出:

Value of expression is 100
Good bye!
AM I out?

考虑到 if 条件给出的缩进,它不应该只打印下面的输出吗?

Value of expression is 100   
Good bye!

为什么最后一个语句也打印出来,即使它没有像前面的语句那样缩进?

标签: pythonindentation

解决方案


Python 逐行执行你的程序,

var = 100                                 # First assign var = 100
if ( var == 100 ) :                       # Executed your if condition
    print ("Value of expression is 100")                 
    print ("Good bye!")
print("AM I out?")                        # Executed your last line

如果您不想在使用 if 时执行最后一行,请保留print("AM I out?") 在 else 块中。

if ( var == 100 ) :                       
        print ("Value of expression is 100")                 
        print ("Good bye!")
else:
        print("AM I out?")

关于识别:

它用于了解您的程序,特定的块语句属于特定的对象(类、函数、if 条件、循环)


推荐阅读