一.if语句
单分支,单重条件判断
if expression:
expr_true_suite
单分支,多重条件判断
if not active or over_time >= 10:
print(‘Warning:service is dead‘)
warn_tag+=1
if+else
if expression:
expr_true_suite
else:
expr_false_suite
多分支if+elif+else
if expession1:
expr1_true_suite
elif expression2:
expr2_true_suite
elif expession3:
expr3_true_suite
else:
none_of_the_above_suite
三元表达式
语法:
expr_true_suite if expession else expr_false_suite
案例一:
>>> active=1 >>> print(‘service is active‘) if active else print(‘service is inactive‘) service is active
案例二:
>>> x=1 >>> y=2 >>> smaller=x if x < y else y >>> smaller 1
二.while语句
2.2.1:基本语法
while expression:
suite_to_repeat
注解:重复执行suite_to_repeat,直到expression不再为真
2.2.2:计数循环
count=0 while (count < 9): print(‘the loop is %s‘ %count) count+=1
2.2.3:无限循环
count=0 while True: print(‘the loop is %s‘ %count) count+=1
tag=True count=0 while tag: if count == 9: tag=False print(‘the loop is %s‘ %count) count+=1
跳出无限循环
2.2.4:while与break,continue,else连用
count=0 while (count < 9): count+=1 if count == 3: print(‘跳出本层循环,即彻底终结这一个/层while循环‘) break print(‘the loop is %s‘ %count)
break跳出本层循环
count=0 while (count < 9): count+=1 if count == 3: print(‘跳出本次循环,即这一次循环continue之后的代码不再执行,进入下一次循环‘) continue print(‘the loop is %s‘ %count)
continue跳出本次循环
count=0 while (count < 9): count+=1 if count == 3: print(‘跳出本次循环,即这一次循环continue之后的代码不再执行,进入下一次循环‘) continue print(‘the loop is %s‘ %count) else: print(‘循环不被break打断,即正常结束,就会执行else后代码块‘) count=0 while (count < 9): count+=1 if count == 3: print(‘跳出本次循环,即这一次循环continue之后的代码不再执行,进入下一次循环‘) break print(‘the loop is %s‘ %count) else: print(‘循环被break打断,即非正常结束,就不会执行else后代码块‘)
循环被break打断,即非正常结束,就不会执行else后代码块
2.2.5:while语句小结
- 条件为真就重复执行代码,直到条件不再为真,而if是条件为真,只执行一次代码就结束了
- while有计数循环和无限循环两种,无限循环可以用于某一服务的主程序一直处于等待被连接的状态
- break代表跳出本层循环,continue代表跳出本次循环
- while循环在没有被break打断的情况下结束,会执行else后代码
时间: 2024-12-24 16:22:35