if语句:
Python的if语句是类似的其他语言。 if语句包含一个逻辑表达式,使用哪些数据进行了比较,比较的结果的基础上作出决定。 if语句的语法是:
if :
statement(s)
这里的if语句,条件是第一次评估。如果条件为真,那就是,如果其值为非零,则执行语句块(S)。否则,下一个语句之后的语句(S)块被执行。
注:在Python中,所有的缩进字符空格后的编程结构相同数量的报表,被认为是一个单一的代码块的一部分。 Python使用缩进作为其语句分组的方法。
例子:
#!/usr/bin/python
var1 = 100
if var1:
print \"1 - Got a true value\"
print var1
var2 = 0
if var2:
print \"2 - Got a true value\"
print var2
print \"Good bye!\"
这将产生以下结果:
1 - Got a true value
100
Good bye!
else 语句:
可以结合一个if语句else语句。 else语句中包含的代码块,执行,如果在条件表达式if语句解析为0或false值。 else语句是一个可选的语句,并有可能最多只有一个else语句后.
if... else语句的语法是:
if :
statement(s)
else:
statement(s)
例子:
#!/usr/bin/python
var1 = 100
if var1:
print \"1 - Got a true value\"
print var1
else:
print \"1 - Got a false value\"
print var1
var2 = 0
if var2:
print \"2 - Got a true value\"
print var2
else:
print \"2 - Got a false value\"
print var2
print \"Good bye!\"
这将产生以下结果:
1 - Got a true value
100
2 - Got a false value
0
Good bye!
elif 语句
elif语句可以让你检查多个表达式为真值,并执行一个代码块,只要条件之一的值为true。 像其他人,elif语句是可选的。然而,不像别的,这有可能是最一个语句ELIF报表,可以有任意数量的if。
if... elif语句的语法是:
if 1:
statement(s)
elif 2:
statement(s)
elif 3:
statement(s)
else:
statement(s)
注:当前Python不支持其他语言的switch或case语句。
例如:
#!/usr/bin/python
var = 100
if var == 200:
print \"1 - Got a true value\"
print var
elif var == 150:
print \"2 - Got a true value\"
print var2
elif var == 100:
print \"3 - Got a true value\"
print var
else:
print \"4 - Got a false value\"
print var
print \"Good bye!\"
这将产生以下结果:
3 - Got a true value
100
Good bye!
嵌套的if... elif...else构造
当您想要检查的另一个条件,后一个条件解析为true时,可能会出现的情况。在这种情况下,你可以使用嵌套if构造。 在嵌套if构造,可以有一个if... elif的... ELSE构造,如果在另一个... ELIF... else结构。 if... ELIF... else结构可能嵌套的语法:
if 1:
statement(s) if 2:
statement(s)
elif 3:
statement(s)
else
statement(s) elif 4:
statement(s)
else:
statement(s)
例如:
#!/usr/bin/python
var = 100
if var < 200: print \" value is less than 200\"
if var == 150:
print \"Which is 150\"
elif var == 100:
print \"Which is 100\"
elif var == 50:
print \"Which is 50\" elif var < 50:
print \" value is less than 50\"
else:
print \"Could not find true \"
print \"Good bye!\"
这将产生以下结果:
value is less than 200
Which is 100
Good bye!
单个语句:
如果如果第一套只包括一个单一的线,它可能会在同一行头语句:
这里是如果第一个一行的一个例子:
if ( == 1 ) : print \"Value of is 1\" 继续阅读与本文标签相同的文章
上一篇 :
关于SwiftUI,看这一篇就够了
下一篇 :
谷歌通过概念向量来影响图像搜索
-
1.98亿滴滴用户添加了紧急联系人 每天百万个订单行程分享给亲友
2026-05-14栏目: 教程
-
工程院院士刘韵洁:5G前景很大,但主要是行业应用
2026-05-14栏目: 教程
-
陆奇:看好5G技术,但应用好5G还需要时间
2026-05-14栏目: 教程
-
在Visual Studio中使用clang-tidy进行代码分析
2026-05-14栏目: 教程
-
甘薇贾跃亭曝出离婚消息,贾跃亭破产前转账51万美元,作为“家庭费用”
2026-05-14栏目: 教程
