流程控制之if判斷


一、語法

if判斷是干什么的呢?if判斷其實是在模擬人做判斷。就是說如果這樣干什么,如果那樣干什么。對於ATM系統而言,則需要判斷你的賬號密碼的正確性。

1.1 if

學什么都是為了讓計算機向人一樣工作,我們無時無刻都在判斷。路邊路過一個生物,你會判斷兩個人是不是會表白?首先會判斷這個生物是不是人類,並且這個人類是個女人,年齡大於18小於20幾歲。你首先需要記錄一堆數據,然后才會用你的大腦去判斷。if表示if成立代碼成立會干什么。

if 條件:
	代碼1
	代碼2
	代碼3
	...
# 代碼塊(同一縮進級別的代碼,例如代碼1、代碼2和代碼3是相同縮進的代碼,這三個代碼組合在一起就是一個代碼塊,相同縮進的代碼會自上而下的運行)
cls = 'human'
gender = 'female'
age = 18

if cls == 'human' and gender == 'female' and age > 16 and age < 22:
    print('開始表白')

print('end...')
開始表白
end...

1.2 if...else

if 條件:
	代碼1
	代碼2
	代碼3
	...
else:
	代碼1
	代碼2
	代碼3
	...

if...else表示if成立代碼成立會干什么,else不成立會干什么。

cls = 'human'
gender = 'female'
age = 38

if cls == 'human' and gender == 'female' and age > 16 and age < 22:
    print('開始表白')
else:
    print('阿姨好')
阿姨好

1.3 if...elif...else

if 條件1:
	代碼1
	代碼2
	代碼3
	...
elif 條件2:
	代碼1
	代碼2
	代碼3
	...
elif 條件3:
	代碼1
	代碼2
	代碼3
	...
...
else:
	代碼1
	代碼2
	代碼3
	...

if...elif...else表示if條件1成立干什么,elif條件2成立干什么,elif條件3成立干什么,elif...否則干什么。

cls = 'human'
gender = 'female'
age = 28

if cls == 'human' and gender == 'female' and age > 16 and age < 22:
    print('開始表白')
elif cls == 'human' and gender == 'female' and age > 22 and age < 30:
    print('考慮下')
else:
    print('阿姨好')
考慮下

二、if的嵌套

如果我們表白的時候,表白成功的時候我們是不是會做什么,表白不成功是不是又會會做什么呢?

# if的嵌套
cls = 'human'
gender = 'female'
age = 18
is_success = False

if cls == 'human' and gender == 'female' and age > 16 and age < 22:
    print('開始表白')
    if is_success:
        print('那我們一起走吧...')
    else:
        print('我逗你玩呢')
else:
    print('阿姨好')
開始表白
我逗你玩呢

三、練習

3.1 練習1:成績評判

  • 如果 成績>=90,打印"優秀"
  • 如果 成績>=80 並且 成績<90,打印"良好"
  • 如果 成績>=70 並且 成績<80,打印"普通"
  • 其他情況:打印"差"
# 成績評判
score = input("your score: ")
score = int(score)


if score >= 90:
    print('優秀')
# elif score >= 80 and score < 90:
elif score >= 80:
    print('良好')
# elif score >= 70 and score < 80:
elif score >= 70:
    print('普通')
else:
    print('差')
your score: 80
良好

3.2 練習2:模擬登錄注冊

# 模擬登錄注冊
user_from_db = 'nick'
pwd_from_db = 123

user_from_inp = input('username: ')
user_from_inp = input('password: ')

if user_from_inp == user_from_db and pwd_from_inp == pwd_from_db:
    print('login successful')
else:
    print('username or password error')
username: nick
password: 123
username or password error


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM