一.python的選擇結構:
python的選擇結構有兩種選擇結構一種是單選擇(if...else)另一種則是多選擇結構(if ...elif...elif)
下面用代碼來實現:
1.if....else
結構:
if boolean :
語句1
語句2
else :
語句3
from datetime import datetime #在datetime標准庫中導入datetime
odd =[1,3,5,7,9,11,13,15,17,19,21,23]
if datetime.today().hour in odd:#in是python的運算符,表是對象是否在后面的列表中
print(datetime.today().hour)
print("now the time is odd")
else:
print(datetime.today().hour)
print("now the time is even")
在上面的簡單代碼中我們可以看到python的格式與其他的高級語言程序不同,它沒有大括號來區分代碼塊,對於python區分代碼塊都是用:和制表符來區分
且需要說明的是python中一旦缺少制表符和:上述代碼就會出錯,同時我們可以看出python不需要我們去定義變量而可以直接使用
2.if...elif...elif
結構
if boolean :
語句1
語句2
elif boolean:
....
score=int(input("請輸入你的成績:"))#python的輸入函數並將輸入轉化為整數 if(score>100 or score <0): print("輸入錯誤") elif 100>=score >=90: print("你的成績是A") elif 90>score>=80: print("你的成績是B") elif 80>=score>=60: print("你的成績是C") elif score<60: print("你的成績是D")
同於其他語言python 並沒有if else if的結構且我們可以看出的是python可以像數學中那樣列不等式所以更方便初學者來學習
二.python的循環結構
python的循環有兩種一種是while 另一種則是for
1.while循環:
while循環一般用於某個條件不成立時使用
結構:while boolean :
語句
#用while循環來計算階乘 while True: i=input("請輸入想要計算的數:") if not i.isdigit(): #判斷用戶輸入的是否是純數字 print("請輸入純數字") continue #不是時終止當前循環,並開啟下一次循環 else: if int(i)<0: print("請輸入正數") continue else : #計算階乘 n=int(i) sum=0 for temp in range(1,n+1):#range函數為內置函數表示在某個范圍相當於 1=<temp<n+1 facto=1 #保存每個中間數的階乘 for temp2 in range(1,temp+1): facto=facto*temp2 sum=sum+facto print("1!+2!+3!.....+n!={0}".format(sum)) #format是字符串匹配的函數{0}是表示format中要配對的位置例如{1} format(1,2,3)則匹配的是2 temp=input("請問要接着計算嗎?(y/n)") ; if temp=='y': continue else: break #break用於終止當前循環
2.for循環
for循環和while循環一樣都時重復的執行某個語句,但不同的是for循環是利用迭代來窮歷序列中的所有元素直到序列中沒有元素為止
結構:
for i(元素) in item(某個序列):
語句
#九九乘法表 for i in range(1,10): for j in range(1,i+1): print("{1}*{0}={2}".format(i,j,i*j),end=" ") print("")
---恢復內容結束---