python3之if语句介绍

x33g5p2x  于2021-03-13 发布在 其他  
字(3.0k)|赞(0)|评价(0)|浏览(277)

语句快介绍

语句快并非一种语句,是通过缩进形成的语句集合;
可以使用的缩进符:TAb建(相当于四个空格),4个空格,8个空格,可以成倍增加形成嵌套语句快;
一般来说使用四个空格是最规范的。
功能:语句快是在条件为真时执行(if)或执行多次(循环)的一组语句;

#伪代码
this is a line
this is a condition:
    this is a block
    .....
there wo escaped the inner block

条件和条件语句

布尔型介绍

假(false):会被看做假的值:
FALSE ,None ,0 ,‘ ’ (没有空格) ,“ ” (没有空格) ,() ,[] ,{}
真(true):其他的都会被判定为真:
测试如下:

#假
>>> bool(False)
False
>>> bool(None)
False
>>> bool('')
False
>>> bool("")
False
>>> bool()
False
>>> bool([])
False
>>> bool(())
False
>>> bool({})
False
>>> 
#真
>>> bool(True)
True
>>> bool('ddd')
True
>>> bool(1)
True
>>> bool([1])
True
>>> bool((1))
True
>>> bool({1})
True
>>> 

条件执行和if语句

if语句

if语句可以实现条件执行,如果条件判定为真,则后面的语句块执行,如果条件为假,语句块就不会被执行。

#如果用户输入:0-9 就打印True
>>> x=int(input("Please enter an integer in 0-9 "))
Please enter an integer in 0-9 6
if 0<x<9:
    print(True)

True

else语句

else子句(之所以叫子句,是因为它不是独立的语句,而只能作为if语句的一部分)当条件不满足时执行;

#如果用户输入:0-9 就打印True,不在之类输出 False
>>> x=int(input("Please enter an integer in 0-9 "))
Please enter an integer in 0-9 11
>>> if 0<x<9:
...     print(True)
... else:
...     print(False)
... 
False

elif语句

如果需要检查多个条件,就可以使用elif,它是“else if”的简写,也是if和else子句的联合使用——也就是具有条件的else子句。

#如果用户输入在0-9:就打印in 0-9 ,否则如果输出大于9:就打印 >9,否则打印:<0
>>> x=int(input("Please enter an integer in 0-9 "))
Please enter an integer in 0-9 -1
>>> if 0<x<9:
...     print("in 0-9")
... elif x>9:
...     print(">9")
... else:
...     print("<0")
... 
<0
>>> 

嵌套if语句

if语句里可以嵌套使用if语句:

x=int(input("Please enter an integer in 0-9 "))
if x>=0:
    if x>9:
        print("x>9")
    elif x==0:
        print("x==0")
else:
    print('x<0')

Please enter an integer in 0-9 0
x==0

更复杂的条件:

条件运算符一览:

#比较运算符
x==y x等于y
x<y x小于y
x>y x大于y
x>=y x大于等于y
x<=y x小于等于y
x!=y x不等于y
a<x<b  x大于a小于b
#同一性运算符
x is y x和y是同一个对象
x is not y x和y是不同的对象
#成员资格运算符
x in y x是y容器的成员
x not in y x不是y容器的成员

同一性运算符说明:
看以来和==一样实际是时不同的,只有两个绑定在相同的对象时才是真(当然当为数值变量时是和==相同的):

#a与b不时指向同一对象
>>> a=[1,2]
>>> b=[1,2]
>>> a is b
False
#a与b指向同一对象
>>> a=b=[1,2]
>>> a is b
True

in成员资格运算符说明

#成员在序列中返回真
>>> a=[1,2,3]
>>> b=1
>>> c=4
>>> b in a
True
>>> c in a
False
>>> 

逻辑运算符:

and :x and y 返回的结果是决定表达式结果的值。如果 x 为真,则 y 决定结果,返回 y ;如果 x 为假,x 决定了结果为假,返回 x。
or :x or y 跟 and 一样都是返回决定表达式结果的值。
not : 返回表达式结果的“相反的值”。如果表达式结果为真,则返回false;如果表达式结果为假,则返回true。

>>> a=1
>>> b=2
>>> a and b
2
>>> a=1
>>> b=0
>>> a and b
0
>>> a or b
1
>>> not b
True
>>> 

断言简介

if语句有个非常有用的近亲,其工作方式多少有点像下面这样(伪代码):
if not condition:
crash program
这样做是因为与其让程序在晚些时候崩溃,不如在错误条件出现时直接让它崩溃。一般来说,你可以要求某些条件必须为真。语句中使用的关键字为assert。
如果需要确保程序中的某个条件一定为真才能让程序正常工作的话,assert语句就有用了,可以在程序中置入检查点:
条件后可以添加字符串(用逗号把条件和字符串隔开),用来解释断言:

>>> age=-1
>>> assert 0<age<150,"The age must be realistic"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: The age must be realistic
>>> 
>>> age=10
>>> assert 0<age<150,"The age must be realistic"
>>> 

相关文章