標籤:流程式控制制 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