Python语句的特点
Python没有花括号来构造代码块
Python通过缩进来设置层次结构
如果在条件语句中同时执行多条语句,保持相同缩进即可
即连续代码又保持相同缩进,它们就是同一代码块,是一个执行整体
Flat is better than nested.尽量减少嵌套
分支结构语句
if … :
…
elif … :
…
…
else:
…
练习
练习1:英制单位英寸与公制单位厘米互换
"""
The British unit inch is interchanged with the metric unit centimeter
Powered by RainGiving
"""
length = float(input('Please enter the length\n '))
unit = input('Please enter the unit\n')
if unit=='in':
print('%fin = %fcm' % (length,length*2.54))
elif unit == 'cm':
print('%fcm = %fin' % (length,length/2.54))
else:
print('Please enter a valid unit')
练习2:百分制成绩转换为等级制成绩
"""
The hundred-mark system is converted to a hierarchical system
Powered by RainGiving
"""
score = float(input('Please enter the score\n'))
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
grade = 'E'
print('The corresponding level is',grade)
练习3:输入三条边长,如果能构成三角形就计算周长和面积
"""
Judge whether the input side length can form a triangle,
if so, calculate the circumference and area of the triangle
Powered by RainGiving
"""
a = float(input('a = '))
b = float(input('b = '))
c = float(input('c = '))
if a + b > c and a + c > b and b + c > a:
C = (a + b + c ) / 2
S = (C*(C-a)*(C-b)*(C-c))**0.5
print('the circumference and area of the triangle is %f and %f' % (C,S))
else:
print('You cannot make a triangle')