函数定义
def 函数名(形参列表用逗号隔开):
函数体
return 返回值
# 有参数 无返回值
def my_length(data):count = 0for i in data:count += 1print(f"data count={count}")my_length(str1)
my_length(str2)#无参数无返回值
def say_hello():print("hello python")say_hello()有参数 有返回值
def sum(x,y):result = x + yreturn result
a = 2
b = 5
result = sum(a,b)
print(f"{a} sum {b} = {sum(a,b)}")def smile():print("give me a hug")return Noneresult = smile()
print(f"result = {result}")result = sum(a,b)
print(f"{a} sum {b} = {a + b}")#None
name = Noneif name:print("name = 不为空")
else:print(f"name = {name}")#函数说明文档
def mulity(x,y):"""两个数字相乘:param x: 乘数:param y: 被乘数:return result: 积"""result = x * yreturn result
result = mulity(10,20)
print(f"{10} * {20} = {10 * 20}")
变量作用域
、
num = 20def test_a():print("test_a",{num})def test_b():global numnum = 500print("test_b",{num})test_a()
test_b()
print("num=%d" % num)
money = 5000000000
name = Nonename = input("请输入你的名字")def query(show_header):if show_header:print("===========查询余额========")print(f"{name}, 您好 您的余额为:{money}")def saving(num):global moneymoney += numprint("===========存款=======")print(f"{name}, 您好 您存款:{num}元成功")query(False)def get_money(num):global moneymoney -= numprint("===========取款=======")print(f"{name}, 您好 您存款:{num}元成功")query(False)def main():print("==========主菜单=======")print(f"{name}, 您好 xxx银行为您服务 请选择你需要的服务")print("余额查询\t【请输入1】")print("存款\t\t【请输入2】")print("取款\t\t【请输入3】")print("退出\t\t【请输入4】")return input("请输入您的选择:")while True:keyboard_input = main()if keyboard_input == "1":query(True)continueelif keyboard_input == "2":num = int(input("请存放xx币"))saving(num)continueelif keyboard_input == "3":num = int(input("请输入取款金额"))get_money(num)continueelse:print("很高兴为你服务 欢迎下次光临")break