函数定义
# 为什么需要函数
# 对重复的代码进行封装
# def 函数名(参数...):
# 函数体
# 函数名(实参)
def sayHello():
print("哈哈")
print("哈哈")
# 调用函数
sayHello()
# 1~任意数的累加和
def caculateNum(number):
sum = 0
for i in range(1, number+1):
sum += i
print(sum)
caculateNum(2)
caculateNum(50)
caculateNum(100)
caculateNum(500)
# 任意两个数的相加
def sum_two(x, y):
print("x =", x)
print("y =", y)
print(x + y)
sum_two(10, 20)
sum_two(-10, 20)
demo2
# + - x /
def jia(a, b):
print(a + b)
def jian(a, b):
print(a - b)
def mul(a, b):
print(a*b)
def div(x, y):
print(x/y)
num1 = input("请输入第一个数") # "1"
num1 = int(num1)
# print(type(num1))
fuhao = input("请输入运算符(+ - * /)")
num2 = int(input("请输入第二个数"))
if fuhao=="+":
print("+")
jia(num1, num2)
elif fuhao=="-":
print("-")
jian(num1, num2)
elif fuhao=="*":
print("*")
mul(num1, num2)
elif fuhao=="/":
print("/")
div(num1, num2)
else:
print("输入有误")
demo2
# 函数的类型
# 无参无返回
def haha():
print("哈哈")
# 有参无返回
haha()
def add(x, y):
print(x+y)
# 有参有返回
print(add(10, 20))
def add2(x, y):
return x + y
# res = add2(11, 22)
# print(res)
print(add2(30, 70))
# 无参有返回
def haha2():
return "呵呵呵"
print(haha2())
网友评论