#3.1调用函数
# 请利用Python内置的hex()函数把一个整数转换成十六进制表示的字符串:
n1 = 255
n2 = 1000
print(hex(n1))
print(hex(n2))
#3.2定义函数
# 请定义一个函数quadratic(a, b, c),接收3个参数,返回一元二次方程:
# ax2 + bx + c = 0的两个解。
# 提示:计算平方根可以调用math.sqrt()函数:
import math
def quadratic(a, b, c):
delta = b * b - 4 * a * c
if delta < 0:
raise EOFError('error')
else:
b = -b
a = 2 * a
x1 = (b + math.sqrt(delta)) / a
x2 = (b - math.sqrt(delta)) / a
return x1, x2
if __name__ == "__main__":
in1 = input('a:')
a = int(in1)
in2 = input('b:')
b = int(in2)
in3 = input('c:')
c = int(in3)
x1, x2 = quadratic(a, b, c)
print('x1 = %.2f x2 = % .2f' % (x1, x2))
#4.3函数的参数
# 以下函数允许计算两个数的乘积,请稍加改造,变成可接收一个或多个数并计算乘积:
def product(x,*nums):
result = x
for num in nums:
result *= num
return result
print(product(2))
#4.4递归函数
def move(n, a, b, c):
if n == 1:
print(a, '-->', c)
else:
move(n-1, a, c, b) # 子目标1
move(1, a, b, c) # 子目标2
move(n-1, b, a, c) # 子目标3
move(3,'A','B','C')
【廖雪峰python3.0】-课后习题:第4章:函数
最新推荐文章于 2021-01-29 11:42:01 发布