目录
分支结构
就像是一大群结伴同行的人,每遇到岔路口总是会根据各自的选择走上不同的道路,其中遇到的岔路可能不止一条,暗指可能有多种情况。
if语句
在python中是使用 if elif else 表明分支的产生,现在上面三个单词是关键字,无法成为变量名,(变量命名规则(硬性规则))
当然如果要构造出更多的分支,
- if...elif...else...
- if...else...
缩进
Python中没有用花括号({})来构造代码块而是使用了缩进的方式来表示代码的层次结构也就是说,某段连续的代码如果保持相同的缩进,那它们就是属于同一个代码块,一个整体,也就是别的语言中花括号括住的部分。
缩进可以使用任意数量的空格,但通常使用4个空格
the Zen of Python
其中“Flat is better than nested.”的理解
实现这个函数,两者写法,个人认为第一种要比第二种更具有可读性。
x = float(input('x = '))
if x > 1:
y = 3 * x - 5
elif x >= -1:
y = x + 2
else:
y = 5 * x + 3
print('f(%.2f) = %.2f' % (x, y))
x = float(input('x = '))
if x > 1:
y = 3 * x - 5
else:
if x >= -1:
y = x + 2
else:
y = 5 * x + 3
print('f(%.2f) = %.2f' % (x, y))
练习
- 英寸和厘米之间的转换,加上其他英制单位,如mile,foot,inch ,英里,英尺,英寸
- 百分制成绩转换为等级制成绩
- 输入三边长,判断能否构成三角形,并计算周长和面积,并判断是否是直角三角形
1.
# 1 mile = 1.61 km 英里
# 1 foot = 30.48 cm 英尺
# 1 inch = 2.54 cm 英寸
value = float(input('input value please:'))
unit = input('input nuit please:')
#in and cm
if unit == 'in' or unit == '英寸':
print('%.2fin = %.2fcm' % (value, value*2.54))
elif unit == 'cm' or unit == '厘米':
print('%.2fcm = %.2fin' % (value, value/2.54))
#foot and cm
if unit == 'foot' or unit == '英尺':
print('%.2ffoot = %.2fcm' % (value, value*30.48))
elif unit == 'cm' or unit == '厘米':
print('%.2fcm = %.2ffoot' % (value, value/30.48))
#mile and km
if unit == 'mile' or unit == '英里':
print('%.2fmile = %.2fkm' % (value, value*1.61))
elif unit == 'km' or unit == '千米':
print('%.2fkm = %.2fmile' % (value, value/1.61))
2.
#百分制成绩转换为等级制成绩
grade = int(input('please input your grade:'))
a = grade // 10
if a >= 9:
print('A')
elif a == 8:
print('B')
elif a == 7:
print('C')
elif a == 6:
print('D')
else:
print('E')
3.
#输入三边长,判断能否构成三角形,并计算周长和面积,判断直角三角形
import math
a = float(input())
b = float(input())
c = float(input())
if a+b>c and b+c>a and a+c>b:
cc = a+b+c
#使用海伦公式,计算面积,p = (a+b+c)/2
p = cc/2
s = (p*(p-a)*(p-b)*(p-c))**0.5
print('周长为{0}\n面积为{1}'.format(cc,s))
#排列之后判断是否为直角三角形
if a**2+b**2 == c**2:
print('该为直角三角形')
else:
print('无法构成三角形')