Python基础-条件判断

来源:互联网 发布:淘宝导航条设计 编辑:程序博客网 时间:2024/06/03 13:53

Python基础-条件判断

Python 有 if, if else 和 if elif 等判断语句

if 基本使用

if condition:    expressions

condition 的值为 True,将会执行 expressions 语句的内容,否则将跳过该语句往下执行。

实例

x = 1
y = 2
z = 3
if x < y:
…. print(‘x is less than y’)

x is less than y

当我们将代码修改为一下

 if x < y < z:    print('x is less than y, and y is less than z')"""x is less than y, and y is less than z"""

注意

python 语言中等号的判断使用 ==

if x == y:    print('x is equal to y')

if else 基本使用

if condition:    true_expressionselse:    false_expressions

当 condition为 True,执行 true_expressions 语句; 如果为 False,将执行 else 的内部的 false_expressions。

实例

x = 1y = 2z = 3if x > y:    print('x is greater than y')else:       print('x is less or equal to y')

输出 x is less or equal to y

if x > y:    print('x is greater than y')else:    print('x is less or equal y')

输出 x is greater than y

三元运算符

很遗憾的是 python 中并没有类似 condition ? value1 : value2 三目操作符。但是python 可以通过 if-else 的行内表达式完成类似的功能。

var = var1 if condition else var2

实例

worked = Trueresult = 'done' if worked else 'not yet'print(result)

输出 done

if elif else 判断

基本使用

if condition1:    true1_expressionselif condition2:    true2_expressionselif condtion3:    true3_expressionselse:    else_expressions

如果有多个判断条件,那可以通过 elif 语句添加多个判断条件,一旦某个条件为 True,那么将执行对应的 expression。 并在之代码执行完毕后跳出该 if-elif-else 语句块,往下执行。

实例

x = 4y = 2z = 3if x > 1:    print ('x > 1')elif x < 1:    print('x < 1')else:    print('x = 1')print('finish')

输出

x > 1finish