Home > Backend Development > Python Tutorial > Python中条件判断语句的简单使用方法

Python中条件判断语句的简单使用方法

WBOY
Release: 2016-06-10 15:07:59
Original
1069 people have browsed it

最简单的条件语句:

if expression:
   expr_true_suite
Copy after login

如上,if是关键字,expression是条件表达式,条件表达式支持多重条件判断,可以用布尔操作符and、or和not连接,expr_true_suite是代码块,expression为true时执行,代码块如果只有一行,上面的整个条件语句便可全部写到一行,但可读性差。
带elif和else的条件语句:

if expression1:
   expr1_true_suite
elif expression2:
   expr2_true_suite
elif expressionN:
   exprN_true_suite
else:
   none_of_the_above_suite
Copy after login

如上,语法同其它语言的条件语句类似,elif和else是可选的。
条件表达式实现三元操作符:
在C/C++中,三元操作符如下(E成立时执行X,否则执行Y)——

E ? X : Y
Copy after login

python模拟的三元操作符——

(E and [X] or [Y])[0]
Copy after login

python三元操作符的实现——

X if E else Y
Copy after login

来看几个判断实例:

>>> if 1 < x < 2: 
  print('True') 
 
   
True 
Copy after login

and 表示且

or 表示 或
>>> x 
2 
>>> if x == 2 or x == 3: 
  print(x) 
 
  2 

Copy after login

如果 b 为真则返回a,否则返回 c

a if b else c
>>> 'True' if 1 < x <2 els
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