不間斷 Python 挑戰 Day 4 - if 流程控制

2021/12/08閱讀時間約 7 分鐘
當我們的程式需要根據某些狀況做出判斷,例如某些條件成立的話,程式就對應做出某種行為,這時單純從頭執行到尾的程式便無法滿足我們的需求,因此便需引進流程控制的概念,也就是if敘述以及其相關的語法,來讓程式可以完成更複雜的工作。

if 敘述

最基本if敘述語法如下,如果滿足condition1的條件判斷,則執行A程式碼區塊,否則就結束判斷。
if condition1:   
  Do A
if 敘述

if / else 敘述

進一步,如果滿足condition1的條件判斷時執行A程式碼區塊,不滿足時要執行B程式碼區塊,則可以用if/else敘述。
if condition1:
  Do A
else:
  Do B
if / else 敘述

巢狀 if 敘述

若if敘述裡面包含有其它的if敘述,稱為巢狀if敘述。
if condition1:
  if condition2
    Do A
  else:
    Do B
else:
  do C
巢狀 if 敘述

if / elif / else 敘述

當程式有多個條件要做判斷時,可使用if/elif/else敘述。
if condition1:
  do A
elif condition2:
  do B
......
else:
  do C
if / elif / else 敘述
例如,當我們要設計一個BMI (Body Mass Index)的計算程式時,必須判斷[1]:
  • 若BMI小於18.5時,體重過輕。
  • 若BMI大於或等於18.5、且BMI小於24時,體重正常。
  • 若BMI大於或等於24、且BMI小於28時,體重過重。
  • 若BMI大於或等於28時,則達到肥胖的程度。
此時除了必須運用if/elif/else語法外,還需引入關係運算子與邏輯運算子的觀念。

關係運算子

  • a > b:檢查a是否大於b
  • a >= b:檢查a是否大於或等於b
  • a < b:檢查a是否小於b
  • a <= b:檢查a是否小於或等於b
  • a == b:檢查a是否等於b
  • a != b:檢查a是否不等於b
舉例來說:
  • a > b
>>> print(2 > 1)
True
>>> print(1 > 2)
False
  • a >= b
>>> print(2 >= 2)
True
>>> print(1 >= 2)
False
  • a < b
>>> print(1 < 2)
True
>>> print(2 < 1)
False
  • a <= b
>>> print(2 <= 2)
True
>>> print(2 <= 1)
False
  • a == b
>>> print(2 == 2)
True
>>> print(2 == 1)
False
  • a != b
>>> print(2 != 1)
True
>>> print(2 != 2)
False

邏輯運算子

  • and運算子,例如:condition1 and condition2,兩條件必須同時成立為True,反之為False。
  • or運算子,例如:condition1 or condition2,兩條件必須有其中一個成立為True,反之為False。
  • not運算子,例如:not condition1,此條件不成立為True,反之為False。
舉例來說:
  • and
>>> print((1 < 2) and (2 < 3))
True
>>> print((1 < 2) and (3 < 2))
False
  • or
>>> print((1 < 2) or (3 < 2))
True
>>> print((2 < 1) or (3 < 2))
False
  • not
>>> print(not (1 > 2))
True
>>> print(not (1 < 2))
False

實作BMI計算機

綜合以上所學,這個程式會要求使用者輸入身高和體重,接著計算BMI,然後回傳它所計算的數值並判斷體重是否在正常範圍內。
# input your height and weight
height = input("Please input your height in centimeter:\n")
weight = input("Please input your weight in kilogram:\n")

# calculate BMI
bmi = int(weight) / ((int(height) / 100) ** 2)

# BMI interpretation
if bmi < 18.5:
  print(f"Your BMI is {bmi}, and you are underweight.")
elif bmi < 24:
  print(f"Your BMI is {bmi}, and you have a normal weight.")
elif bmi < 28:
  print(f"Your BMI is {bmi}, and you are overweight.")
else:
  print(f"Your BMI is {bmi}, and you are obese.")
以下是執行結果:
Please input your height in centimeter:
180
Please input your weight in kilogram:
75
Your BMI is 23.148148148148145, and you have a normal weight.

程式範例

參考資料

為什麼會看到廣告
Wei-Jie Weng
Wei-Jie Weng
留言0
查看全部
發表第一個留言支持創作者!