3.4函数function

def say_hi():
    print("hi")
    
say_hi()
say_hi()

def print_sum_two(a,b):
    c=a+b
    print(c)
#没有return关键字,所以这是没有返回值的函数
print_sum_two(3,6)

def hello_some(str):
    print("hello "+str+"!")
    
hello_some("china")
hello_some("china")
#有返回值的函数如下:
def repeat_str(str,times):
    repeated_strs=str*times
    return repeated_strs

repeated_strings=repeat_str("happy birthday", 4)
print((repeated_strings))
###################################

x=60
def foo(x):
    print("x is"+str(x))
    x=3
    print("change lacal x to"+str(x))
    
foo(x)
print("x is still",str(x))
##############全局变量是60
x=60
def foo():
    global x
    print("x is"+str(x))
    x=3
    print("change lacal x to"+str(x))
    
foo()
print("vlaue of x is",str(x))
###############函数内部也定义了全局变量所以变成了3

 

 

 

 

 

 

#默认参数


def repeat_str(s,times=1):
    repeated_strs=s*times
    return repeated_strs
##没有传入参数时使用默认值
repeated_strings=repeat_str("happy")
print(repeated_strings)
##传入参数时使用该参数
repeated_strings=repeat_str("happy", 4)
print(repeated_strings)

#===============================================================================
#f(a,b=2)这个是可以的,默认参数必须放在最尾才是合法的
# f(a=2,b)这是不合法的,python中某个参数使用了默认参数,之后的所有参数都必须是由默认参数的,否则不合法
#===============================================================================

#关键字参数

def func(a,b=4,c=8):
    print(a,b,c)

func(13, 17)
func(125, c=24)
func(c=40, a=80)

#VarArgs参数

def print_paras(fpara,*nums,**words):
    print("f:"+str(fpara))
    print("n:"+str(nums))
    print("w:"+str(words))
    
print_paras("hello",1,3,5,7,word="python",another_word="java")

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值