详解Python中的条件判断语句

WBOY
Release: 2016-06-06 11:16:14
Original
905 people have browsed it

 一个else语句可以使用if语句结合起来。如果在if语句中的条件表达式解析为0或false值,那么else语句包含代码执行。

else语句是可选的声明,并if语句下面最多只有一个else语句。
语法:

if ... else语句的语法是:

if expression:
  statement(s)
else:
  statement(s)
Copy after login

2015514110654164.jpg (264×368)

例子:

#!/usr/bin/python

var1 = 100
if var1:
  print "1 - Got a true expression value"
  print var1
else:
  print "1 - Got a false expression value"
  print var1

var2 = 0
if var2:
  print "2 - Got a true expression value"
  print var2
else:
  print "2 - Got a false expression value"
  print var2

print "Good bye!"

Copy after login

当执行上面的代码,产生以下结果:

1 - Got a true expression value
100
2 - Got a false expression value
0
Good bye!

Copy after login

elif 语句

elif语句可以检查多个表达式的真值,并执行一个代码块的条件之一计算结果为true。

if...elif 语句是可选的。然而不像else,对此可以有最多一个语句,if语句下边可以有任意数量elif语句。

if...elif 语句的语法是:

if expression1:
  statement(s)
elif expression2:
  statement(s)
elif expression3:
  statement(s)
else:
  statement(s)

Copy after login

Python核心不提供switch或case语句在其他语言,但我们可以用if..elif...语句来模拟switch case如下:
例子

#!/usr/bin/python

var = 100
if var == 200:
  print "1 - Got a true expression value"
  print var
elif var == 150:
  print "2 - Got a true expression value"
  print var
elif var == 100:
  print "3 - Got a true expression value"
  print var
else:
  print "4 - Got a false expression value"
  print var

print "Good bye!"

Copy after login

当执行上面的代码,产生以下结果:

3 - Got a true expression value
100
Good bye!

Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!