亞洲大學基礎程式設計教材(AUP110-Fundamentals of Programming)¶
[](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/noteboHealthy weights/colab-github-demo.ipynb)
#Week6-條件式(condition)和資料容器(Container)
Topic 1(主題1)-if條件陳述式/if condition statement¶

Body mass index (BMI) is a person’s weight in kilograms divided by the square of height in meters. BMI is an inexpensive and easy screening method for weight category—underweight, healthy weight, overweight, and obesity. https://www.cdc.gov/healthyweight/assessing/bmi/adult_bmi/index.html
Step 1: 布林值/boolean¶
True / False
print(True)
print(False)
True
False
print(5>3)
print(5<3)
True
False
bmi = 21.0
print(bmi>24.0) #24.0 is Overweight
False
bmi = 18.0
print(bmi<18.5) #18.5 is too skinny
True
bmi = float(input("Input yout bmi"))
print(bmi>24.0)
---------------------------------------------------------------------------
StdinNotImplementedError Traceback (most recent call last)
/tmp/ipykernel_884/2551581868.py in <module>
----> 1 bmi = float(input("Input yout bmi"))
2 print(bmi>24.0)
~/.local/lib/python3.8/site-packages/ipykernel/kernelbase.py in raw_input(self, prompt)
1001 """
1002 if not self._allow_stdin:
-> 1003 raise StdinNotImplementedError(
1004 "raw_input was called, but this frontend does not support input requests."
1005 )
StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.
Step 2: if-condition¶
if 布林一:
# 布林一被評估為 True 時候執行縮排的程式碼
elif 布林二:
# 布林二被評估為 True 時候執行縮排的程式碼
else:
# 布林一與布林二都被評估為 False 時候執行縮排的程式碼
bmi = float(input("Input yout bmi"))
if bmi>30.0:
print("Obesity")
Step 3: if-else-condition¶
bmi = float(input("Input yout bmi"))
if bmi>24.0:
print("Overweight")
else:
print("Healthy weight")
Step 4: if-elif-else-condition¶
bmi = float(input("Input yout bmi"))
if bmi>24.0:
print("Overweight")
elif bmi<18.5:
print("Underweight")
else:
print("Healthy weight")
Topic 2(主題2)-運算子/Operator¶
Step 1: 比較運算子/Comparison Operators: >, >=, < , <=, ==¶
Operators |
Running |
---|---|
> |
greater than |
< |
less than |
>= |
greater than or equal |
<= |
less than or equal |
== |
equal |
!= |
not equall |
#判斷奇數偶數
a = 9
if a % 2 == 0:
print("{} is even".format(a))
else:
print("{} is odd".format(a))
b = 8
if b % 2 == 0:
print("{} is even".format(b))
else:
print("{} is odd".format(b))
#判斷奇數偶數
a = 9
if a % 2 != 1:
print("{} is even".format(a))
else:
print("{} is odd".format(a))
b = 8
if b % 2 < 1:
print("{} is even".format(b))
else:
print("{} is odd".format(b))
Step 2: 布林運算子/Boolean Operators: and, or, not¶
bmi = float(input("Input yout bmi"))
if 18.5<= bmi and bmi<24.0:
print("Healthy weight")
bmi = float(input("Input yout bmi"))
if 18.5<= bmi <24.0:
print("Healthy weight")
bmi = float(input("Input yout bmi"))
if 18.5<= bmi and bmi<24.0:
print("Healthy weight")
else:
if bmi>24.0:
print("Overweight")
else:
print("Underweight")
score1 = int(input("Input yout score1"))
score2 = int(input("Input yout score2"))
if score1 > 60 and score2 > 60:
print("All pass")
else:
print("Have failed grades")
score1 = int(input("Input yout score1"))
score2 = int(input("Input yout score2"))
if score1 < 60 or score2 < 60:
print("Have failed grades")
else:
print("All pass")
score1 = int(input("Input yout score1"))
score2 = int(input("Input yout score2"))
if not(score1 < 60 or score2 < 60):
print("All pass")
else:
print("Have failed grades")
Topic 3(主題3)-for-loop-if-condition¶
Step 7:找出一個數字的所有因數¶
num = int(input())
for i in range(1,num+1):
if num % i ==0:
print("{} ".format(i), end="")
Step 8:決定一個數字是不是質數(prime number), 除了1和本身之外,沒有別的因數¶
num = int(input())
count = 0
for i in range(2,num):
if num % i ==0:
count+=1
print("{} ".format(i), end="")
print()
if count ==0:
print("{} is a prime number".format(num))
else:
print("{} is not a prime number".format(num))
Step 9:break-for-loop¶
num = int(input())
count = 0
for i in range(2,num):
if num % i ==0:
count+=1
break
if count ==0:
print("{} is a prime number".format(num))
else:
print("{} is not a prime number".format(num))
Step 10:continue-for-loop¶
for c in 'Asia University':
if c == 'i':
continue
print ('Current Letter :', c)
Topic 4(主題4)-While迴圈(While Loop)¶
while 條件判斷式:
# 程式碼
Step 1: 用一個數字控制執行次數¶
for i in range(10):
print(i, end=" ")
i = 1
while i < 10:
print(i, end=" ")
i += 1
i = 1
while True:
print(i, end=" ")
i += 1
if i >=10:
break
Step 2: 用一個迴圈控制程式是否結束¶
i = 1
while True:
if input("Q for quit?").lower() == "q":
break
print(i, end=" ")
i += 1
Topic 5(主題5)資料容器(Container)¶
Python語言括號有三種, 小括號()代表元組(tuple)資料型別、中括號[ ]代表串列(List)資料型別、大括號{ }代表字典(dict)或集合(set)資料型別。序列是由一個範圍內的數字當作索引,字典是由鍵 (key) 來當索引,鍵可以是任何不可變的類型;字串和數字都可以當作鍵值。
串列把一堆變數放入[]中,形成一排資料
元組由若干個值藉由逗號區隔而組成
集合(Set) 是一組無序且沒有重複的元素
字典(Dictionary)把一堆鍵和值的對應放入{}中,形成可索引資料集合
Step 1: 資料容器變數的啟始化¶
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
steps = 1, 3, 5, 6, 9
vectors = ((0,0,0), (3, 5, 7), (8, 8, 8))
baskets = {'orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'}
favors = {0:'orange', 7:'apple', 3:'pear', 2:'banana', 6:'kiwi', 4:'apple', 9:'banana'}
tel = {'jack': 4098, 'sape': 4139}
print(type(fruits))
print(type(steps))
print(type(vectors))
print(type(baskets))
print(type(favors))
print(type(tel))
Step 2: 資料容器變數的索引¶
print(fruits[1])
print(steps[1])
print(vectors[1])
print(favors[2])
print(tel['sape'])
Step 3: Set comprehensions¶
a = {x for x in 'abracadabra' if x not in 'abc'}
print(a)
data={x: x**2 for x in (2, 4, 6)}
print(data)
Step 4: Dictionary comprehensions¶
dict_items([('c', 3), ('d', 4), ('a', 1), ('b', 2)])
dict_variable = {key:value for (key,value) in dictonary.items()}
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
# Double each value in the dictionary
double_dict1 = {k:v*2 for (k,v) in dict1.items()}
print(double_dict1)
Topic 6(主題6):使用容器的迴圈¶
Step 1: in 資料容器變數¶
steps = 1, 3, 5, 6, 9
for x in steps:
print (x**2, end=" ")
baskets = {'orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'}
for x in baskets:
print (x, end=" ")
Step 2: 使用 items()¶
tel = {'jack': 4098, 'sape': 4139}
for k, v in tel.items():
print(k, v)
Step 3: 使用 enumerate()¶
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
for i, x in enumerate(fruits):
print (i, x)
vectors = ((0,0,0), (3, 5, 7), (8, 8, 8))
for i, x in enumerate(vectors):
print (i, x)
baskets = {'orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'}
for i, x in enumerate(baskets):
print (i, x)
Step 4: 使用 zip()¶
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print(f'What is your {q}? It is {a}.')
Topic 7(主題7):map()函數的使用¶
map(function, iterable, …)
返回一個將 function 應用於 iterable 中每一項並輸出其結果的迭代器。如果傳入了額外的 iterable 參數,function 必須接受相同個數的實參並被應用於從所有可迭代對像中並行獲取的項。當有多個可迭代對象時,最短的可迭代對象耗盡則整個迭代就將結束。
Step 1: 計算資料容器的變數長度¶
a, b, c = map(len, ('apple', 'banana', 'cherry'))
print(a, b, c)
Step 2: 將輸入字串轉換成整數
a, b, c = map(int, ['3', '5', '6'])
print(a, b, c)