【Python自學】條件語句if/else,以及elif多條件語句的用法

 本篇簡單筆記python中的if/else用法,並且寫一些簡單的案例。

 

1、用途

if / else 用來「判斷條件」,根據條件是否成立,決定程式要走哪一段。

「其實滿直觀的,if/else但凡你對英文有一點理解,就是你想像中的那個意思。」

 

2. 基本語法

if (條件,其結果是布林值bool

    # 條件成立(True)時會執行這裡

else:

    # 條件不成立(False)時會執行這裡

 

if/else的判斷語句往往是搭配布林值來做判斷的,或者更廣泛地說,所有判斷語句都離不開布林值。」

 

3. 基本例子(成年人可以進入視窗)

age = 20

if age >= 18:

    print("你已成年,可以進入。")

else:

    print("未成年,禁止進入。")

 

判斷邏輯:

age >= 18 → True → 印出「你已成年,可以進入。」

age < 18 → false → 印出「未成年,禁止進入。」

 

「這個(未成年不得進入視窗),應該是大家從小到大,說謊最多次的地方吧!」

 

4. 加上 elif(多條件)

score = 75

 

if score >= 90:

    print("A 等級")

elif score >= 80:

    print("B 等級")

elif score >= 70:

    print("C 等級")

else:

    print("需要加油喔")

 

「用elif 會讓整個有多重判斷語句的時候,讓程式碼看得更簡潔有力。elifelse以及if的縮寫,實際上並沒有這個英文單字。」

 

5. 判斷字串例子

name = "阿元"

 

if name == "阿元":

    print("歡迎回來!")

else:

    print("你是新朋友嗎?")

 

「字串跟數字的邏輯也是一樣的。」

 

6. 判斷是否有輸入

item = input("輸入一些內容吧!")

 

if item:  # 字串不為空 → True

    print("你輸入的是:", item)

else:

    print("你沒有輸入內容喔")

 

(1)假如使用者輸入:Hello,I am Yuan.

程式執行的結果:你輸入的是: yuan

 

(2)假如使用者輸入:【沒有填入任何訊息,直接按Enter

程式執行的結果:你沒有輸入內容喔

 

簡易計算機程式

接下來,我們來撰寫一個"簡易計算機程式",讓使用者輸入三個資料,分別是

1)運算符號(加減乘除:+ - * /

2)數字1

3)數字2

並根據運算符號,將數字1與數字2做運算

 

目的:練習if/else/elif的條件判斷句

 

 

#簡易計算機程式

operator = input("please input operator")

number1 = float(input("please input number1"))

number2 = float(input("please input number2"))

 

if operator == "+":

    print(number1 + number2)

elif operator == "-":

    print(number1 - number2)

elif operator == "*":

    print(number1 * number2)

elif operator == "/":

    print(number1 / number2)

 

程式執行結果:

please input operator +

please input number1 3

please input number2 4

7.0

 

please input operator -

please input number1 5

please input number2 6

-1.0

 

please input operator *

please input number1 3

please input number2 4

12.0

 

please input operator /

please input number1 8

please input number2 4

2.0

 

 

留言

這個網誌中的熱門文章

常見的化痰粉愛克痰(小鳥粉)怎麼吃?|化痰粉成人及小孩的使用劑量|紅色與藍色比較

麻將教學懶人包|從規則到牌理的完整觀念整理(附實戰心得)

麻將新手必看!不知道聽什麼牌怎麼辦?超多種實戰聽牌範例,教你怎麼判斷胡牌機會