Python_函数

1.函数定义:

def get_apple(num,name):
    print('......................................................')
    count=0
    while count<int(num):
        count +=1
        print(name+'拿第'+str(count)+'个苹果')



get_apple(10,'张三')

get_apple(20,'王五')

get_apple(30,'李四')

注:函数定义的关键字:def

  函数名后不要忘了“:”

2.必须参数和关键字参数:

def get_apple(num,name):
    print('......................................................')
    count=0
    while count<int(num):
        count +=1
        print(name+'拿第'+str(count)+'个苹果')



get_apple(num=10,name='张三')

get_apple(name='王五',num=20)

get_apple(name='李四',num=30)

 3.默认参数:

def get_apple(name,num=5):
    print('......................................................')
    count=0
    while count<int(num):
        count +=1
        print(name+'拿第'+str(count)+'个苹果')



get_apple('张三') #张三默认拿5个苹果

get_apple('王五',num=10) #王五特殊,可以拿10个苹果

get_apple(name='李四',num=20) #李四更特殊,可以拿20个苹果

 4.可变参数:

def get_apple(name,*b):
    for num in b:
        print('.....................................')
        count=0
        while(count<num):
            count+=1
            print(name+'拿第'+str(count)+'个苹果')


get_apple('张三',5,10) #张三分两次拿苹果,第一次拿5个,第二次拿10个

get_apple('李四',10,20,30) #李四分三次拿苹果,第一次拿了10个,第二次拿了20个,第三次拿了30个

注:b是可变参数,首先需要在参数名前加“*”

  需要先遍历可变参数b

 5.带返回值的函数:

def get_apple(name,*b):
    totalCount=0
    for num in b:
        print('.....................................')
        count=0
        while(count<num):
            count+=1
            totalCount+=1
            print(name+'拿第'+str(count)+'个苹果')
    return totalCount

totalCount1= get_apple('张三',5,10) #张三分两次拿苹果,第一次拿5个,第二次拿10个
print(totalCount1)

totalCount2= get_apple('李四',10,20,30) #李四分三次拿苹果,第一次拿了10个,第二次拿了20个,第三次拿了30个
print(totalCount2)
原文地址:https://www.cnblogs.com/myfy/p/11459410.html