首页 > 编程语言 >python - 函数(一)

python - 函数(一)

时间:2023-07-08 22:46:51浏览次数:40  
标签:函数 python describe pet animal print type name

1. 示例

def greet_user():               # 函数定义
    """显示简单的问候语"""       # 文档字符串,描述了函数的功能。Python基于此生成有关函数的文档
    print("Hello!")
    
greet_user()

1.1 参数

def greet_user(username):
    """显示简单的问候语"""
    print(f"Hello, {username.title()}")
    
greet_user("jesse")

username是形参,"jesse"是实参

2. 传递实参的方式

当函数有多个形参时,函数调用时也会包含多个实参。形参和实参的关联方式有以下方式

2.1 位置实参

实参的顺序与形参顺序一致

def describe_pet(animal_type, pet_name):
    """显示宠物的信息。"""
    print(f"\nI have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name.title()}.")

describe_pet('hamster', 'harry')
describe_pet('dog', 'willie')

2.2 关键字实参

无需考虑实参顺序

def describe_pet(animal_type, pet_name):
    """显示宠物的信息。"""
    print(f"\nI have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name.title()}.")

describe_pet(animal_type = 'hamster', pet_name = 'harry')
describe_pet(pet_name = 'willie', animal_type = 'dog')

2.3 形参指定默认值

函数定义使用默认值时,必须先列出无默认值的形参,再列出有默认值的形参。

def describe_pet(pet_name, animal_type='dog'):
    """显示宠物的信息。"""
    print(f"\nI have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name.title()}.")

describe_pet('xiaohuang')    # 按形参顺序
describe_pet(pet_name = 'willie')   # 按参数名
describe_pet(animal_type = 'hamster', pet_name = 'harry')  # 显式指定pet_name, 将忽略默认值

3. 返回值

3.1 示例

def get_formatted_name(first_name, last_name):
    """返回整洁的姓名。"""
    full_name = f"{first_name} {last_name}"
    return full_name.title()
    
actor = get_formatted_name('tom', 'hanks')
print(actor)

让实参可选

def get_formatted_name(first_name, last_name, middle_name=''):
    """"返回整洁的姓名。"""
    if middle_name:    # middle_name非空,则为True
        full_name = f"{first_name} {middle_name} {last_name}"
    else:
        full_name = f"{first_name} {last_name}"
    return full_name

actor = get_formatted_name('jim', 'hendrix')
print(actor)

actor = get_formatted_name('john', 'hooker', 'lee')
print(actor)

3.2 返回字典

def build_person(first_name, last_name, age=None):   # age设置为可选,None表示变量没有值,占位符
    person = {'first': first_name, 'last':last_name}
    if age:
        person['age'] = age
    return person

actor = build_person('tom', 'hanks', age=33)
print(actor)

标签:函数,python,describe,pet,animal,print,type,name
From: https://www.cnblogs.com/route/p/17538029.html

相关文章

  • reactive函数
    作用:定义一个对象类型的响应式数据(基本类型不要用它,要用ref函数)语法:const代理对象=reactive(源对象)接收一个对象(或数组),返回一个代理对象(Proxy的实例对象,简称proxy对象)reactive定义的响应式数据是“深层次的”。内部基于ES6的Proxy实现,通过代理对象操作源对象......
  • python: generate and decode QrCode
     #encoding:utf-8#-*-coding:UTF-8-*-#版权所有2023©涂聚文有限公司#许可信息查看:#描述:#Author:geovindu,GeovinDu涂聚文.#IDE:PyCharm2023.1python311#Datetime:2023/7/511:08#User:geovindu#Product:UI#Project......
  • python笔记1.2
    基本输入函数input的应用name=input('请输入您的姓名')print('您的姓名为:'+name)num=int(input('请输入您的幸运数字'))#print('您的幸运数字为:'+num)#字符串和整数无法运算print('您的幸运数字为:',num)#正常返回num单行注释#正常返回num多行注释'''版权所有......
  • R语言中 bquote函数
     R语言中bquote函数用于显示变量的值,有点类似与shell中的$符号。001、i=100##定义一个测试变量bquote(i)##不能直接输出变量的值bquote(.(i))##需要借助.()的形式输出变量的值 002、应用于绘图中i=100plot(1:10,mai......
  • python笔记:第四章使用字典
    1.1概述说白了就是键值对的映射关系不会丢失数据本身关联的结构,但不关注数据的顺序是一种可变类型格式:dic={键:值,键:值}键的类型:字典的键可以是任何不可变的类型,如浮点数,字符串,元组1.2函数dict可以从其他映射或键值对创建字典items=[('name','Gumby'),('ag......
  • python笔记1.1
    ASCII码使用print输出中文Unicode编码:print(ord("天"))#使用ord()查询“天”的Unicode编码为22825print("\u5929")#22825的十六进制为5929返回值为“天” 使用print()将内容输出到文件fp=open("note.txt","w")#打开文件,w——writeprint("北京欢迎你",file=fp)#输出......
  • Python潮流周刊#10:Twitter 的强敌 Threads 是用 Python 开发的!
    你好,我是猫哥。这里每周分享优质的Python及通用技术内容,大部分为英文,已在小标题注明。(标题取自其中一则分享,不代表全部内容都是该主题,特此声明。)首发于我的博客:https://pythoncat.top/posts/2023-07-08-weekly周刊已开通Telegram频道,欢迎关注:https://t.me/pythontrendingwee......
  • ref函数
    作用:定义一个响应式的数据语法:constxxx=ref(initValue)创建一个包含响应式数据的引用对象(reference对象,简称ref对象)。JS中操作数据:xxx.value模板中读取数据:不需要.value,直接:<div>{{xxx}}</div>备注:接收的数据可以是:基本类型、也可以是对象类型。......
  • python - while循环(二)
    使用while处理列表和字典1.在列表之间移动元素在for循环遍历列表时,若修改列表元素会导致Python难以跟踪元素。unconfirmed_users=['alice','brian','candace']confirmed_users=[]forunconfirmed_userinunconfirmed_users:unconfirmed_users.remove(unconfirm......
  • Python | 使用try-except导包
    导包的时候我们可能会遇到这样的代码:try:from.hugmodelimportHugModelexceptException:pass这段代码的作用是尝试导入名为HugModel的模块,如果导入失败则不做任何操作,而是直接跳过异常。其中.表示当前包,也就是相对导入方式。这种写法通常用于可选的依赖项或......