1. 程式人生 > >三、流程控制

三、流程控制

pri tin gin 愛情 叠代 success ucc 判斷 int

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

三、流程控制