今天學條件判斷 if
1. 注意要寫:號. 若if 判斷為True, 就會把縮進的那段程式執行.
說明:
每個流程的結尾是用:號
屬於該流程底下的執行動作不需要任何括號,而是使用縮排(Tab)
>>> results = 100
>>> if results >= 90:
... print ('Your results is',results)
... print ('Excellent')
...
Your results is 100
Excellent
>>>
2. elif放程式中間, else:放結尾. if是由上向下判斷, 若有符合, 就直接執行. 不再繼續判斷.
>>> results = 70
>>> if results >= 90:
... print ('Your results is',results)
... print ('Excellent')
... elif results >=60:
... print ('Your results is',results)
... print ('Good')
... else:
... print ('Your results is',results)
... print ('Failed')
...
Your results is 70
Good
>>>
3. inupt ()內是字串str(), str () 不能跟整數int ()做比較. 所以要先將str 轉成整數 int
>>> R = input ('results: ')
results: 85
>>> results = int (R)
>>> if results >= 90:
... print ('Your results is',results)
... print ('Excellent')
... elif results >=60:
... print ('Your results is',results)
... print ('Good')
... else:
... print ('Your results is',results)
... print ('Failed')
...
Your results is 85
Good
>>>
Example
# -*- coding: utf-8 -*-
#20170509
#06_01.py
#輸入身高, 體重. 算出BMI(體重除以身高的平方)
#BMI < 18.5: 過輕.
#BMI 18.5 - 25: 正常.
#BMI 25 - 28: 過胖.
#BMI 28 - 32: 肥胖.
#BMI > 32: 嚴重肥胖.
H1 = input ('Height (m) : ')
W1 = input ('Weight (kg): ')
H2 = float (H1)
W2 = float (W1)
bmi = W2/(H2 ** 2)
print ('Your heights:',H1,'(m).','Your weights:',W1,'(kg).')
print ('Your BMI: %.2f' %(bmi))
#因為過輕,正常,過胖, 肥胖, 嚴重肥胖等字. UTF-編碼顯示有問題. 故我先用0-4表示.
if bmi < 18.5:
print ('Your BMI: 0')
elif bmi < 25:
print ('Your BMI: 1')
elif bmi < 28:
print ('Your BMI: 2')
elif bmi < 32:
print ('Your BMI: 3')
else:
print ('Your BMI: 4')
最初發表 / 最後更新: 2017.05.09 / 2018.05.29
0 comments:
張貼留言