###### tags: `python` # 變數 & 常數 ## 變數命名不可使用以下文字/符號 * python內建關鍵字 * 特殊符號: @, !, * * 數字開頭的變數名稱 * 變數名稱中間不能有空格(可以用底線) ## 變數內容指派 ```python= 1. name = "amos" 2. x=y=z=1 # x, y, z 內容都是1 3. x, y, z = 1, 2.5, "good" # x=1, y=2.5, z="good" ``` ## 常數 python沒有常數的設定,但習慣上代表常數的變數會以「全大寫」表示 ```python= PI = 3.1415 ``` ## 運算子、運算符號 ### 算術運算子: | 符號 | 意義 | |--|--| | \+ | 加 | | \- | 減 | | \* | 乘 | | / | 除 | | // | 整除 | | % | 餘數 | | ** | 指數 | ```python= print(10+5) # 15 print(10-5) # 5 print(10*5) # 50 print(11/5) # 2.2 print(11//5) # 2 print(11%5) # 1 print(2**10) # 1024 ``` ### 位移運算子 (跟系統及硬體比較有關) ### 位元運算子 (跟系統及硬體比較有關) ### 比較運算子 | 符號 | 意義 | |--|--| | \> | 大於 | | \>= | 大於等於 | | \< | 小於 | | \<= | 小於等於 | | == | 等於 | | != | 不等於 | ```python= print(100>50) # True print(100>=100) # True print(50<100) # True print(100<=100) # True print(100==100) # True print(50!=100) # True print(True == 1) # True print(False == 0) # True ``` ### 指派運算子(簡化版) ```python= a = 100 a = a + 50 print(a) # 100 + 50 = 150 a += 50 print(a) # 150 + 50 = 200 ``` ### 邏輯運算子 | 符號 | 意思 | 意義 | |--|--|--| | and | 而且 | 所有條件都成立結果才成立 | | or | 或者 | 任一條件成立結果就成立 | | not | 相反 | 反向原有結果 | ```python= print(5>3 and 3>2) # True print(5>3 or 3<2)# True print(not 5>3) # False ``` ## 輸入、輸出 input(): 取得的資料都是**字串型態**! ```python= # coding=UTF-8 name = input("請輸入您的名字: ") birthday = input("請輸入您的生日: ") print("hello, " + name + " 您的生日是 " + birthday) ``` ```python= num1 = float(input("first: ")) num2 = float(input("second: ")) print(num1+num2) ``` ## 型態轉換 可將原有型態內容轉成另外一種型態 * int() * float() * bool() * complex() * bool() * str() * list() * tuple() * range() * set() ```python= a = "3" print(type(a)) # str float(a * 3) # 333.0 float(a)*3 # 9.0 ``` ## 練習 1. 讓使用者輸入3個數字,然後顯示加總結果 2. 華氏攝氏溫度轉換 3. 計算BMI 4. 輸入生日及算年齡 5. 公司獎金發放規則: a. 公司營收大於1000 b. 個人績效大於等於400 c. 求每個人是否能領到獎金 | 姓名 | 績效 | 獎金 | | ----- | ------ | ---- | | 慧君 | 300 | | | 文彥 | 450 | | | 宗坤 | 400 | | ## 答案 4. 輸入生日及算年齡 ```python= from datetime import datetime, date birthday = input("your birthday: ") birthday = datetime.strptime(birthday, '%Y/%m/%d').date() today = date.today() age = today.year - birthday.year - ((today.month, today.day) < (birthday.month, birthday.day)) print('your age is : ' + str(age)) ```