天天看點

Python基礎學習-3.程式的組織結構

3.程式的組織結構

計算機的基本流程控制由順序結構、選擇結構、循環結構組成

3.1順序結構

print('---開始程式-----')
print('1.開始程式')
print('2.執行代碼')
print('3.編譯過程')
print('---結束程式')
           

3.2選擇結構

對象的布爾值:一切皆對象,所有對象都有布爾值,用内置函數boo()擷取對象的布爾值

以下對象的布爾值為False

False
數值0
None
空字元串
空清單
空元組
空字典
空集合
           
#print("------以下對象布爾值為Flase-----")
print(bool(False))
print(bool(0))
print(bool(0.0))
print(bool(None))
print(bool(''))
print(bool(""))
print(bool([]))       #空清單
print(bool(list()))   #空清單
print(bool(()))       #空元組
print(bool(tuple()))  #空元組
print(bool(dict()))   #空字典
print(bool(set()))    #空集合
           
3.2.1單分支結構

文法:

if 條件表達式:
    條件執行體
           
money=100
s =int(input(('請輸入取款金額')))
if money >=s :
    money = money - s
    print('取款成功,餘額為:', money)   
           

輸出:

請輸入取款金額20
取款成功,餘額為: 80
           
3.2.2雙分支結構
num=int(input('請輸入一個整數'))
#條件判斷
if num%2==0:
    print(num,'是偶數')
else:
    print(num,'是奇數')
           
3.2.3多分支結構

文法:

if 條件表達式1:
   條件執行體1
elif 條件表達式2:
     條件執行體2
elif 條件表達式3:
     條件執行體3
[else:]
     條件執行體N+1
           
"""
多分支結構
從鍵盤錄入一個整數
90-100 A
80-90 B
70-80 C
60-69 D
0-59 E
"""
score=int(input('請輸入一個成績:'))
#判斷
if score>=90 and score <=100:
    print('A級')
elif score>=80 and score <=89:
    print('B級')
elif score>=70 and score <=79:
    print('C級')
elif score>=60 and score <=69:
    print('D級')
elif score >=0 and score <=59:
    print('E級')
else:
    print('成績輸入有誤,請重新輸入')
    
或者這種寫法:
score=int(input('請輸入一個成績:'))
if 90<=score <=100:
    print('A級')
elif 80<=score <=89:
    print('B級')
elif 70<=score <=79:
    print('C級')
elif 60<=score <=69:
    print('D級')
elif 50<=score <=59:
    print('E級')
else:
    print('成績輸入有誤,請重新輸入')

           
3.2.4 嵌套結構

文法:

if 條件表達式1:
   if 内層條件表達式:
        記憶體條件執行體1
   else:
        記憶體條件執行體2
else:
    條件執行體
           
'''
會員 >=200 8折
     >=100 9折
非會員  >=200 9.5折
        不打折
'''
answer=input('您是會員嗎?y/n')
money=float(input('請輸入您的購物金額:'))
if answer=='y':
    if money >=200:
        print('打8折,付款金額為:',money*0.80)
    elif money >=100:
        print('打9折,付款金額為:',money*0.9)
    else:
        print('不打折,付款金額為:',money)
else:
    if money >=200:
        print('打9.5折,付款金額為:',money*0.95)
    else:
        print('不打折,付款金額為:',money)
           
3.2.3條件表達式

文法:

x if 判斷條件 else y
           

如果判斷條件的布爾值為True,條件表達式傳回值為x,否則條件表達式傳回False

'''輸入兩整數,比較兩個整數大小'''
a=int(input('輸入第一個整數'))
b=int(input('輸入第二個整數'))
'''
if a>=b:
    print(a,'大于等于',b)
else:
    print(a,'小于',b)
'''
print('使用條件表達式比較')
print( str(a)+'大于等于'+str(b) if a>=b else str(a)+'小于'+str(b))
           
#pass語句,什麼都不做
ans=input('您是會員嗎?y/n')
if ans=='y':
    pass
else:
    pass
           

3.3循環結構

繼續閱讀