• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Lucky
博客园    首页    新随笔    联系   管理    订阅  订阅

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)

 

posted @ 2019-09-04 15:27  半仙儿~~~  阅读(182)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3