## wk03_0921_ch02_變數與運算式 ## 【inclass practice】 ### {上週使用函數} 1. print() - 輸出 2. input() - 輸入 3. type() - 顯示資料類型 4. int() - 轉換成數字 5. float() - 轉換成浮點數 6. str() - 轉換成字串 ### {綜合演練} #### 實作題3 <pre> 矩形的面積是長*寬、周邊長是(長+寬)*2 請設計程式讓使用者輸入矩形的長和寬,然後計算矩形面積和周邊長。 </pre> 1. input : 矩形的長、寬 2. process : 先將輸入都轉換成浮點數(可計算)後代入公式 3. output : 矩形的面積、周長 ```python length=float(input("輸入矩形的長")) width=float(input("輸入矩形的寬")) area=length*width perimeter=(length+width)*2 print("矩形的面積為",area) print("矩形的周長為",perimeter) ``` 輸入矩形的長2.8 輸入矩形的寬5 矩形的面積為 14.0 矩形的周長為 15.6 #### 實作題4. <pre> 許多人出國時會有公制轉英制的困擾,以長度為例,英制和公制的長度轉換公式為: 1 inch (英吋) = 2.54 cm (公分) 請設計程式讓使用者輸入公制的身高(cm),然後計算出英制的高度是幾英呎、幾英吋 1 英呎 = 12 英吋 </pre> 1. input : 使用者輸入公制的身高(cm) 2. process : 先換算成英吋後用商跟餘數得出答案 3. output : 計算出英制的高度是幾英呎、幾英吋 ```python height=int(input("輸入您的身高(cm)")) height=height/2.54 foot=height//12 inch=height%12 print("您的身高是%d英尺又%4.1f英吋"%(foot,inch)) ``` 輸入您的身高(cm)180 您的身高是5英尺又10.9英吋 ## {概念練習} 1. 變數命名 - 合法的 - height、weight - 不合法的 - 100_year_ago、range 2. 變數資料型態 - 數值型資料類型有哪些 - int、float、bool - 5 + 5.16 + True = 11.16 - 字串行資料類型有哪些 - str 3. 數值型資料類型有哪些 4. " + " 運篹子 5. 輸出: " %d %s " % (參數列) 6. 輸出: " {0} {1} ".format(參數列) 7. 輸入命令 8. 運算子優先順序 ```python print(5 + 5.16 + True) ``` 11.16 ## 【afterclass practice】 ### 綜合演練 實作題1 1. 一年一班只有2位同學,程式設計讓老師分別輸入2位同學的姓名和成績,然後分別計算成績總分,最後以下圖格式列印。 ```python a=input("請輸入第一位學生的姓名 : ") b=int(input("請輸入第一位學生的成績 : ")) c=input("請輸入第二位學生的姓名 : ") d=int(input("請輸入第二位學生的成績 : ")) print("姓名 成績") print(a,b) print(c,d) print("成績總分為 : ",b+d) ``` 請輸入第一位學生的姓名 : 林建豪 請輸入第一位學生的成績 : 100 請輸入第二位學生的姓名 : 張家誠 請輸入第二位學生的成績 : 78 姓名 成績 林建豪 100 張家誠 78 成績總分為 : 178 ### 綜合演練 實作題2 2. 計程車計費方式第1公里為70元,多1公里加收30元。設計程式讓運將輸入乘客的搭乘公里數,然後計算乘車費用。 ```python a=int(input("請輸入路程公里數(整數):")) b=70+(a-1)*30 print("你的車程資費為:",b) ``` 請輸入路程公里數(整數):5 你的車程資費為: 190 ## 【Self practice】 ```python # 1. print(5+3*2/(7-4)) ``` 7.0 ```python # 2. print((10%3)**2+4//2) ``` 3 ```python # 3. print((8+2)*(5-3)/2) ``` 10.0 ```python # 4. print(2**3+4**(1/2)-1) ``` 9.0 ```python # 5. True or False = True , True and True = True print((10>5)or(3!=3)and(8//2<=4)) ``` True ```python # 6. print("Hello"+" "+"world"*2) ``` Hello worldworld ```python #7. 1 !=0 = True , True and not True = Flase print((15/3)%2 != 0 and not (10>7)) ``` False ```python # 8. print((3+2)**2/4*5%6) ``` 1.25 ```python # 9. print(2*(4+6)-(5%3)**2) ``` 16 ```python # 10. print(len("Python")+int("3")+(5>2)) ``` 10
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up