Python之‘’控制流‘’
阿新 • • 發佈:2017-09-09
對象 exe while語句 else ann == dont nbsp 部分
一、if語句
格式:
i1 = 3 if i1 > 4: print(‘yes you are right‘) elif 0 < i1 < 4: print(‘im dont konw‘) else: print(‘no you are wrong‘)
註意if、elif以及else後面的(:)符號,我們通過它告訴Python下面跟著一個語句塊。
二、while語句
number = 23 running = True while running: guess = int(input(‘enter an integer:‘)) if guess == number: print(‘congratulations,you guessed it‘) running = False elif guess < number: print(‘no,it is a little lower than that‘) else: print(‘no,it is a little higher than that ‘) else: print(‘the while loop is over‘) print(‘done‘)
輸出結果:
enter an integer:22
no,it is a little lower than that
enter an integer:24
no,it is a little higher than that
enter an integer:23
congratulations,you guessed it
the while loop is over
done
註意:在Python2.x版本中輸入使用的是raw_input而在Python3.x版本中輸入使用的是input。並且後面都要跟冒號。
三、for循環
格式:for...in
for i in range(1,5): print(i) else: print(‘the loop is over‘) 結果: C:\Python36\python.exe C:/Users/蔡瑞/7.py 1 2 3 4 the loop is over Process finished with exit code 0
註意:range(1,5)只是輸出1-4沒有5。還有,else部分是可選的,如果包含else,它總是在for循環結束後執行一次,除非遇到break語句。
for循環在這個範圍內遞歸,這就相當於把序列中的每個數(或對象)賦值給i,一次一個,然後以每個i的值執行這個程序塊。
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python
Python之‘’控制流‘’