天天看點

python判斷循環語句_Python條件判斷和循環語句

一、條件判斷語句

通過一條或多條語句的判斷來決定是否執行代碼塊

1、if語句基本形式:

if 判斷條件:

語句塊

例如:

score=75

if score>=60:

print "passed"

2、if-else語句基本形式:

if 判斷條件1:

代碼塊1

else:

代碼塊2

例如:

score=55

if score>=60:

print "passed"

else

print "failed"

3、if-elif-else語句基本形式

if 判斷條件1:

代碼塊1

elif 判斷條件2:

代碼塊2

elif 判斷條件3:

代碼塊3

else:

代碼塊4

例如:

score=85

if score>=90:

print "very good"

elif score>=80:

print "good"

elif score>=60:

print "passed"

else:

print "failed"

注意:Python不支援switch語句,多個條件判斷,隻能用elif語句實作

二、循環語句

循環語句允許執行一個語句或者語句組多次

1、for循環語句基本形式

for 循環條件:

代碼塊

例如:

L=['Adam','Lisa','Bart']

for name in L:

print name

2、while循環語句基本形式

while 循環條件:

代碼塊

例如:

sum=0

x=1

while x<100:

sum=sum+x

x=x+2

print x

print sum

3、break退出循環

break可以在循環語句内直接退出循環

例如:計算1+2+4+8+16+...的前10項的和

sum=0

x=1

n=1

while True:

sum=sum+x

x=x*2

n=n+1

if n>10:

break

print sum

4、continue退出本次循環,進入下一次循環

例如:計算0-100以内的奇數的和

sum=0

x=0

while True:

x=x+1

if x>10:

break

if x%2==0:

continue

sum=sum+x

print sum