流程控制
Posted 蜗牛也是妞
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了流程控制相关的知识,希望对你有一定的参考价值。
3.1 判断 if
第一种:
age=28
if age > 18:
print(‘表白‘)
第二种if...else...:
if age > 18 and age < 22:
print(‘表白‘)
else:
print(‘阿姨好‘)
第三种 #if多分支:
score=input(‘>>: ‘)
score=int(score)
if score >= 90:
print(‘优秀‘)
elif score >= 80:
print(‘良好‘)
elif score >= 60:
print(‘合格‘)
else:
print(‘滚犊子‘)
if嵌套:
age=19
is_pretty=True
success=True
if age > 18 and age < 22 and is_pretty:
if success:
print(‘表白成功,在一起‘)
else:
print(‘去他妈的爱情‘)
else:
print(‘阿姨好‘)
3.2 条件循环 while
3.2.1 格式一:while:条件循环
while 条件:
循环体
count=0
while count <= 10:
print(count)
count+=1
嵌套循环
count=1
while True:
if count > 3:
print(‘too many tries‘)
break
name=input(‘name>>: ‘)
password=input(‘password>>: ‘)
if name == ‘egon‘ and password == ‘123‘:
print(‘login successfull‘)
break
else:
print(‘user or password err‘)
count+=1
例2:登陆,只允许登陆三次,使用tag
count = 1
tag=True
while tag:
if count > 3:
print(‘too many tries‘)
break
name = input(‘name>>: ‘)
password = input(‘password>>: ‘)
if name == ‘egon‘ and password == ‘123‘:
print(‘login successfull‘)
while tag:
cmd=input(‘cmd>>: ‘) #q
if cmd == ‘q‘:
tag=False
continue
print(‘run %s‘ %cmd)
else:
print(‘user or password err‘)
count += 1
3.2.2 格式二:while+else
count=0
while count <= 5:
if count == 3:
break
print(count)
count+=1
else:
print(‘当while循环在运行过程中没有被break打断,则执行我‘)
3.3 for迭代式循环
3.3.1 格式一:
for i in range(1,10,2):
print(i)
例1:
l1=[‘a‘,‘b‘,‘c‘,‘d‘,‘e‘]
for i in range(len(l1)):
print(i,l1[i])
3.3.2 格式二:for+else:
for i in range(5):
if i == 3:break
print(i)
else:
print(‘当循环在运行过程中没有被break打断,则执行我‘)
3.4 break和continue关键字
while+break
count=0
while True:
if count == 5:
break #跳出本层循环
print(count)
count+=1
while+continue
#1,2,3,4,5,7
count=1
while count <= 7:
if count == 6:
count += 1
continue #跳出本次循环
print(count)
count+=1
以上是关于流程控制的主要内容,如果未能解决你的问题,请参考以下文章