9 月 232020
 
#位置参数和关键词参数
#自定义函数,求梯形面积,上底,下底,高。
def trapezoid_area(base_up, base_down, height):
    return 1/2 * (base_up + base_down) * height

#先给变量赋值,再调用函数
base_up = 1
base_down = 2
height = 3

#比较
print(trapezoid_area(1, 2, 3))

#函数中的参数在传入之前已经有了具体值,因此这是位置参数传入而不是关键词参数传入
print(trapezoid_area(height, base_down, base_up))
#print(trapezoid_area(3, 2, 1))
# 1/2 * (3 + 2) * 1 即 2.5,而不是4.5 
PS C:\Users\harveymei> & C:/Users/harveymei/AppData/Local/Programs/Python/Python38/python.exe c:/Users/harveymei/hello.py
4.5
2.5
PS C:\Users\harveymei> 
9 月 232020
 
#位置参数和关键词参数
#自定义函数,求梯形面积,上底,下底,高。
def trapezoid_area(base_up, base_down, height):
    return 1/2 * (base_up + base_down) * height

#位置参数
print('在函数调用中依次传入参数值的方式称为位置参数')
print('print(trapezoid_area(1,2,3))')
print(trapezoid_area(1,2,3))

#关键词参数
print('在函数调用中传输参数和赋予参数的值的方式称为关键词参数')
print('print(trapezoid_area(base_up=2, base_down=3, height=3))')
print(trapezoid_area(base_up=2, base_down=3, height=3))

#函数中引用参数时可以混合使用位置参数和关键词参数
#仅使用关键词参数时,参数顺序可以打乱
#混合使用参数时,位置参数必须在关键词参数之前

trapezoid_area(height=3, base_down=2, base_up=1) #正确
#trapezoid_area(height=3, base_down=2, 1) #错误
#SyntaxError: positional argument follows keyword argument
#trapezoid_area(base_up=1, base_down=2, 3) #错误
#SyntaxError: positional argument follows keyword argument
trapezoid_area(1, 2, height=3) #正确
trapezoid_area(1, height=3, base_down=2) #正确
PS C:\Users\harveymei> & C:/Users/harveymei/AppData/Local/Programs/Python/Python38/python.exe c:/Users/harveymei/hello.py
在函数调用中依次传入参数值的方式称为位置参数
print(trapezoid_area(1,2,3))
4.5
在函数调用中传输参数和赋予参数的值的方式称为关键词参数
print(trapezoid_area(base_up=2, base_down=3, height=3))
7.5
PS C:\Users\harveymei>
9 月 232020
 
#自定义函数,a*a+b*b=c*c,开平方求c值
def Pythagorean_theorem(a,b):
    return 'The right triangle third side\'s length is {}'.format((a**2 + b**2)**(1/2))
#引号内的字符串出现符号时需要使用\转义
#使用.format()将格式化的运算值填入字符串中

#调用函数,传入参数并打印函数返回
print(Pythagorean_theorem(3,4))
PS C:\Users\harveymei> & C:/Users/harveymei/AppData/Local/Programs/Python/Python38/python.exe c:/Users/harveymei/hello.py
The right triangle third side's length is 5.0
PS C:\Users\harveymei> 
9 月 232020
 
#6的2次方
print(6**2)
#6的4次方
print(6**4)
#36的2次方
print(36**2)
#开平方
#1296的1/2次方
print((6**4)**(1/2))
#1296的1/4次方
print((6**4)**(1/4))
PS C:\Users\harveymei> & C:/Users/harveymei/AppData/Local/Programs/Python/Python38/python.exe c:/Users/harveymei/hello.py
36
1296
1296
36.0
6.0
PS C:\Users\harveymei>