函数

来源:互联网 发布:淘宝产品打折功能收费 编辑:程序博客网 时间:2024/06/14 08:19


# coding:utf-8
#创建函数
def say_hi():
    print("hi")
say_hi()

#带参数的函数
def print_sum(a,b):
    c=a+b
    print(c)
print_sum(3,6)

def hello_som(str):
    print("hello "+str+"!")
hello_som("China")

#有返回值的
def repeat_str(str,times):
    repeated_strs=str*times
    return repeated_strs
print(repeat_str("Happy Birthday ",4))
#参数有默认值的
def repeat(str,times=1):  #参数值按位置对应,有默认的参数必须放在最后,即其后不能有没有默认值的参数
    strs=str*times
    return strs
repeat("china")
repeat("time",4)

#变量
x=60 #全局变量
def foo():
    x=3  #局部变量,如果要使其依旧为全局变量可以为:x=3 global
    print(x)
#指明参数值的函数
def func(a,b=4,c=8):
    print("a is",a,"and b is",b,"and c is",c)
func(2,c=5)