python从入门到实践8-python从入门到实践-8章函数

#!/user/bin/env python

# -*- coding:utf-8 -*-

# 给形参指定默认值时,等号两边不要有空格 def function_name("parameter_0",parameter_1="default value")

# 函数形参的位置很重要 传递参数使用关键字实参(一一对应的传递,可以不用理会顺序)

# 默认值传递时候要指定传递(可以对应位置传递)

# 返回值return 默认函数已经结束了

def get_formatted_name(frist_name,last_name,middle_name=""):

if middle_name:

full_name = frist_name + " " + middle_name + " " + last_name

else:

full_name = frist_name + " " + last_name

return full_name.title()

musician = get_formatted_name("jimi","hendrix")

print(musician)

musician = get_formatted_name("jimi","li","men")

print(musician)

# 返回字典

def build_person(frist_name, last_name):

person = {"frist": frist_name, "last": last_name}

return person

musician = build_person("jimi","hendrix")

print(musician)

# 结合while写函数

# 向函数传递列表 for循环提取

def greet_user(names):

for name in names:

msg = "hello " + name.title()

print(msg)

user_names = ["hannah","ty","margot"]

greet_user(user_names)

# 函数中修改列表就是调用列表方法修改

"""【遇到禁止修改源文件的列表,就要用[:]创建一个副本进行修改】"""

# 传递任意数量的实参用: *

def make_pizza(size, *topings):

print(" Making a " + str(size) + "-inch pizza with following toppings")

for toping in topings:

print("- " + toping)

make_pizza(16, "pepperoni")

make_pizza(12,"mushrooms", "green peppers")

# 传递任意数量的关键字参数

def build_proflie(frist, last, **user_info):

profile = {}

profile["frist_name"] = frist

profile["last_name"] = last

for key,value in user_info.items():

profile[key] = value

return profile

user_profile = build_proflie("albert","einstein",

location="princeton",

field="physics")

print(user_profile)

# 导入模块 每个py文件都可以是模块

# import 模块

# from 模块 import 函数

# from 模块 import 函数 as 另一个名字

# import 模块 as 另一个名字

# from 模块 import * 导入模块中所有函数

# 所有import都要放在开头,除非在文件开头使用了注释性语言来描述整个程序

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值