Categories: 攝影或3C

Python判斷式介紹(if, else, elif,巢狀if),==是邏輯判斷式,=是指定

#if…

#if … else…

#if… elif…elif…else…

 

Light = ‘on’

if Light == ‘on’: print(‘open’) #使用雙等號,單等號是指定

if Light == ‘on’:
    print(‘open’) #分兩行的話,第二行的前方要縮排

 

執行結果:

open
open

 

 

account = ‘abc123’
password = ‘abc123’

if account == password :
    print(‘login’)
else                    #else後面加:
    print(‘error’)

if account == password : print(‘login’)
else: print(‘error’)

執行結果:

login
login

 

 

account = ‘abc123’
password = ‘abc123’

if account == ‘ ‘ : print(‘account is null’)

elif password == ‘ ‘ : print(‘password is null’)

#elif account != password : print(“account or password error”)  #這段程式碼不知道為何錯誤
elif account != password : print(“account or password error”) #依照上一行,一模一樣打又正確

elif account == password : print (‘login’)

執行結果

login

 

 

account = ‘abc123’
password = ‘abc123a’

if account == ‘ ‘ : print(‘account is null’)

elif password == ‘ ‘ : print(‘password is null’)

elif account == password : print (‘login’)

#elif account != password : print(‘account or password error) #這段程式碼不知道為何錯誤

#Python invalid non-printable character U+00A0:

#由于习惯了复制现成的代码,导致报错,所以一般先处理下复制的代码,去掉空格,或者再不行用笨办法重新敲一遍

else : print(‘account or password error’)

執行結果:

account or password error

 

account = ‘abc123’
password = ‘abc123A’

if account == ‘ ‘ : print(‘account is null’)

elif password == ‘ ‘ : print(‘password is null’)

#elif account != password : print (“account or password error”)  #這段程式碼不知道為何錯誤

elif account != password : print (‘account or password error’)

elif account == password : print (‘login’)

執行結果:

account or password error

 

 

print(“請輸入帳號”)
acc = input()

print(“請輸入密碼”)
pwd = input()

account = “abc123”
password = “ABC456”

if account == acc and password == pwd : print(“login”)
else : print(“account or password error”)

執行結果:

 

 

print(“請輸入帳號”)
acc = input()

print(“請輸入密碼”)
pwd = input()

account = “abc123”
password = “ABC456”

if account != acc or password != pwd : print(“account or password error”)
else : print(“login”)

執行結果同上

 

print(“請輸入您的體重”)

weight = float(input())

Goal =60 #目標體重

Health = 50 #理想體重

if weight <= Goal:
    if weight <= Health: print(“恭喜您達到理想體重”)
    else: print(“恭喜您達到目標體重”) #跟上面的if同縮排
else: print(“請繼續努力”) #else後面要加:
#槽狀IF

 

print(“恭喜您達到理想體重”) if weight <= Health else print(“恭喜您達到理想體重”) if weight <= Goal else print(“請繼續努力”)

#寫成一行,不可分行,不用:(冒號),一行式邏輯比較容易理解

執行結果同上

儲蓄保險王

儲蓄險是板主最喜愛的儲蓄工具,最喜愛的投資理財工具則是ETF,最喜愛的省錢工具則是信用卡