python中的函数问题

我观看了bilibili视频 并总结了一些字典的知识,希望能帮到大家。

1.1 定义函数

def hello_world ():
  print ("Hello,world")
hello_world()

1.1.1 向函数传递信息

def hello_world (usename):
  print ("Hello,"+" "+usename.title())
hello_world('mojingqin')

1.2 传递实参

1.2.1 位置实参

def pet (animal_type,pet_name):
    print("l have a "+animal_type+".")
    print("my"+animal_type+"'s name is"+pet_name.title()+".")
pet('haster','harry')

1.2.2 关键字实参

def pet (animal_type,pet_name):
    print("l have a "+animal_type+".")
    print("my"+animal_type+"'s name is"+pet_name.title()+".")
pet(animal_type='haster',pet_name='harry')

1.3 函数返回值- return语句

def get_name(f_name,l_name):
    full_name =f_name+" "+l_name
    return full_name.title()
musician = get_name('mo','fen')
print (musician)

1.3.1 让实参变为可选的

def get_name(f_name,l_name,m_name=""):  
 if m_name:
    full_name=f_name+""+m_name+""+l_name
 else:
    full_name =f_name+" "+l_name 
 return full_name.title()
musician = get_name('mo','fen')
print (musician)
doctor= get_name('mo','miao','jing')
print(doctor)

1.3.2 返回字典

def build_person (f_name,l_name):
     person={'first':f_name,'last':l_name}
     return person
build_person ('mo','di')

1.4 传递列表

def greet_users (names):
    for name in names:
        msg = "Hello,"+name.title()+"!"
        print(msg)
usernames=['modi','mofen','moju']
greet_users(usernames)

1.5 传递任意数量的实参

 # 传递任意数量的实参 
def make_pizza(*toppings):
    """   打印顾客点的所有配料"""
    print(toppings)
make_pizza('Pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')

1.5.1 结合使用位置实参和任意数量实参

def make_pazzle(size,*toppings ):
    print("\nMaking a  "+str(size)+
    "-inch pizza with the following toppings")
    for topping in toppings:
        print("- "+topping)
 
make_pazzle(16,'pepperoni')
make_pazzle(12,'mushrooms','green peppers ','extra cheese')

将函数存储在模块中

pizza.py

def make_pizza(size,*toppings):
    print("\nMaking a " + str(size)+
          "-inch pizza with the following toppings:")
    for topping in toppings:
        print("-" + topping)
import pizza
#python读取这个文件时,代码行import pizza让Python打开文件pizza.py,并将其中的
#所有函数都复制到这个程序中
pizza.make_pizza(16,'pepperoni')
pizza.make_pizza(12,'mushrooms','green peppers','extra cheese'

参考

博客1
博客2

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值