1. 程式人生 > >python --003--流程控制while,for

python --003--流程控制while,for

流程控制 while for

流程控制
順序流程:每一行代碼都會執行,並且只會執行一次
···
if -- else 結構語句:
1、if 布爾表達式:
代碼對齊,tab與空格不能夠同時出現

2、if 布爾表達式:
代碼
else:

money = input (‘please input your money:‘)
if money > 100:
print ‘you are vip!‘
print ‘you are gold VIP‘
else :
print(‘you are not vip!‘)

3、if--else 嵌套:
if 布爾表達式:
代碼
else:
if 布爾表達式:
代碼
else:
代碼
....

money = input (‘please input your money:‘)

if money > 100:
print ‘you are vip!‘
if money >= 200:
print ‘you are golden VIP‘
if 200>money>100:
print‘you are silver vip‘
else :
if money<0:
print‘error!‘
else:
print(‘you are not vip!‘)

4、if 布爾表達式:
代碼
elif 布爾表達式:
代碼

money = input (‘please input your money:‘)
if money > 100:
print ‘you are vip!‘
if money >= 200:

print ‘you are golden VIP‘
if 200>money>100:
print‘you are silver vip‘
elif money<0:
print‘error!‘
else:
print(‘you are not vip!‘)

EG:
第一種:
#coding:UTF-8
score = int(input(‘please input a score:‘))

if 100>=score>=90:
print(‘很好‘)
if 90>=score>=70:
print(‘well done!‘)
if 70>=score>=60:
print(‘pass!‘)

if 60>score:
print(‘failed!‘)
if score>100 or score<0:
print (‘error!‘)

第二種:

-- coding: cp936 --

score = int(input(‘please input a score:‘))

if 100>=score>=90:
print(‘很好‘)
else:
if 90>=score>=70:
print(‘良好‘)
else:
if 70>=score>=60:
print(‘及格‘)
else:
if 60>score>=0:
print(‘不及格‘)
else:
print (‘error!‘)
第三種:
score = int(input(‘your number:‘))
if 100>=score>=90:
print(‘excellent‘)
elif 90>=score>=70:
print(‘good‘)
elif 70>=score>=60:
print(‘pass‘)
elif 60>score>=0:
print(‘flunk‘)
else:
print (‘error!‘)

循環流程
··while 循環

重復運行某些代碼
1、語法:
while 布爾表達式:
代碼:(循環體)
註意:要避免死循環(註意循環跳出條件)
服務器就是死循環724365
num = 0
while num<10:
print ‘hello world!‘
num+=1

·····for循環
1、語法:
for 目標 in 表達式:
循環體

                            目標:變量
                            表達式:字符串、列表、元祖----可叠代對象

a = ‘baizhi‘
for i in a:
print i

teacher = [‘fei‘,‘xige‘,‘kuai‘]
for i in teacher:
print i

number = [123,466,969]
for i in number:
print i

·range()
語法:
range([start],stop[,step=1])
1、這個函數有三個參數,其中方括號表示可選擇參數()
2、第一個參數默認就是0,第二個參數停止,第三默認1
3、作用生成一個值,從start開始,到stop結束的數字序列
取值範圍從[start,stop)左閉右開

a = range(0,3,1)

>> a
[0, 1, 2]
>>
>> a=range(0,10,2)
>> a
[0, 2, 4, 6, 8]
>> a = range(0,10,3)
>> a
[0, 3, 6, 9]
>> range(3)
[0, 1, 2]

for i in range(5):
print i

01
2
3
4

>> for i in range(2,5):
print i

2
3
4

>> for i in range(1,5,2):
print i

1
3

··break
跳出當前循環,後面所有循環都不執行

while True:
num = input(‘please input your number:‘)
if num ==1:
break
print(‘error,try again!‘)

please input your number:3
error,try again!
please input your number:1

·continue
跳過本次循環,不影響下次循環

for i in range(10):
if i%2!=0:
continue
print i

02
4
6
8

>> for i in range(10):
if i%2!=0:
break
print i

python --003--流程控制while,for