Python基础-条件语句

if 语句

Python程序语言指定任何非0和非空(null)值为true,0 或者 null为false。
Python 编程中 if 语句用于控制程序的执行,基本形式为:
if 语句的判断条件可以用>(大于)、<(小于)、==(等于)、>=(大于等于)、<=(小于等于)、!= (不等于)来表示其关系
if 判断条件:
执行语句……
else:
执行语句……

条件成立
Python基础-条件语句
条件不成立
Python基础-条件语句

当判断条件为多个值时,可以使用以下形式:
if 判断条件1:
执行语句1……
elif 判断条件2:
执行语句2……
elif 判断条件3:
执行语句3……
else:
执行语句4……
Python基础-条件语句

    嵌套循环

    ![](https://s1.51cto.com/images/blog/201910/10/256eb386133115ee65fe6ce119e836a4.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)

while循环

count=0
while count < 9:
print('The count is ',count)
count = count + 1
print('good bye')
以上代码执行输出结果
The count is 0
The count is 1
The count is 2
The count is 3
The count is 4
The count is 5
The count is 6
The count is 7
The count is 8
good bye

无限循环

while 1==1: #该条件永远为true,循环将无限执行下去
执行语句1……

注意:以上的无限循环你可以使用 CTRL+C 来中断循环。

continue,break

count=0
while count < 9:
count = count + 1
if count % 2 > 0: #非双数时跳过输出
continue
print('The count is ',count) #输出双数2、4、6、8

i=1
while 1: #循环条件为1必定成立
print("i====",i)
i +=1
if i>10: #当大于10时跳出循环
break

while循环使用 else 语句

count=0
while count < 9:
count = count + 1
if count % 2 > 0: #非双数时跳过输出
continue
print('The count is ',count) #输出双数2、4、6、8
else:
print("当前循环结束啦啦啦啦")

猜你喜欢

转载自blog.51cto.com/13729775/2441304