2017年4月25日,今天瀏覽器崩潰2次,全部白寫...上周都在外面跑,這周應該有幾天有空
1、格式化
習題來自廖老師的blog
小明的成績從去年的72分提升到了今年的85分,請計算小明成績提升的百分點,并用字符串格式化顯示出'xx.x%',只保留小數(shù)點后1位:
s1 = 72
s2 = 85
r = (s2 - s1)/s1 * 100
print('成績提高比第一季度提高:%.1f%%' % r)
另外寫了一個啰嗦一點的:

image.png
2、if條件判斷
age = input('your age:') #輸入一個數(shù)值
if age >= 18: #條件判斷1
print('your age is', age)
print('your is adult.')
elif age >= 6: #條件判斷2
print('your age is', age)
print('your is teenager')
else: #都不是的話
print('oh!kid!')
注意!如果直接輸入一個數(shù)值,會提示錯誤:
your age:20
Traceback (most recent call last):
File "C:/python_study/python01/temp.py", line 52, in
if age >= 18: #條件判斷1
TypeError: '>=' not supported between instances of 'str' and 'int'
輸入的任何數(shù)值,python看來都是‘str’類型的
>>> age = input('your age:')
your age:18
>>> type(age)
因此我們改成:
age = int(input('your age:'))
或者
age = input('your age:')
birth = int(age)
練習
小明身高1.75,體重80.5kg。請根據(jù)BMI公式(體重除以身高的平方)幫小明計算他的BMI指數(shù),并根據(jù)BMI指數(shù):
低于18.5:過輕
18.5-25:正常
25-28:過重
28-32:肥胖
高于32:嚴重肥胖
用if-elif判斷并打印結(jié)果:
height = float(input('Please enter your height:'))
weight = float(input('Please enter your weight:'))
bmi = weight / height**2
if bmi < 18.5:
print('too light')
elif 18.5 <= bmi <= 25:
print('normal')
elif 25 < bmi <= 28:
print('fat')
elif 28 < bmi <= 32:
print('overweight')
else:
print('You are a pig!')
結(jié)果
Please enter your height:1.5
Please enter your weight:200
You are a pig!