博客
关于我
python函数的参数和返回值
阅读量:385 次
发布时间:2019-03-05

本文共 909 字,大约阅读时间需要 3 分钟。

Python 函数的参数与返回值

一、有参函数

在 Python 中,函数的参数是在小括号中定义和传递的。函数接受多种数据类型的参数,可以是数字、字符串、列表、字典等。

参数的定义与传递

def foo(x, y):    print("x 的值是:", x)    print("y 的值是:", y)
foo(2, 3)  # 调用函数,传递参数 x=2,y=3

默认参数

在定义参数时,可以为某些参数设定默认值。默认参数在调用函数时可以省略,使用时会取默认值。

def conn_mysql(user, port=3306):    print(user, port)
conn_mysql("root")  # 未传递 port,使用默认值 3306conn_mysql("root", 3307)  # 传递了 port,使用 3307

注意:所有默认参数必须排在所有位置参数之后。

关键点

  • 位置参数:用户必须传递的参数,例如 user
  • 默认参数:可以省略传递的参数,例如 port
  • 混合调用:可以选择传递默认参数,例如 conn_mysql("root", 3307)

调用方式

conn_mysql(port=3308, user="sahrk")

二、函数的返回值

函数处理的数据只有通过 return 关键字才能返回给调用者。

返回单个值

def foo():    n = 3 + 7    return n
n = foo()  # n 的值为 10

返回多个值和多种数据类型

def func():    return 1, "hello", [1, 2], {"a": 1}
t = func()  # 返回值为 (1, 'hello', [1, 2], {'a': 1})

接收返回值

n, s, li, dic = func()  # 解包获取各个返回值print(n, s, li, dic)  # 输出 1 hello [1, 2] {'a': 1}

返回多种数据类型

函数可以返回任意数量的任意 Python 数据对象。例如,可以返回数字、字符串、列表、字典等多种类型的数据。

转载地址:http://dhjg.baihongyu.com/

你可能感兴趣的文章
PAT (Basic Level) Practise - 写出这个数
查看>>
PAT 1027 Colors in Mars
查看>>
PAT 1127 ZigZagging on a Tree[难]
查看>>
PAT 2-07. 素因子分解(20)
查看>>
PAT A1033 重点题
查看>>
SparkSQL学习03-数据读取与存储
查看>>
PAT L2-012. 关于堆的判断
查看>>
PAT Spell It Right [非常简单]
查看>>
PAT-1044. Shopping in Mars (25)
查看>>
PAT-乙级-1040 有几个PAT
查看>>
pat1011. World Cup Betting (20)
查看>>
Spring组件扫描配置
查看>>
PAT1093 Count PAT's (25)(逻辑题)
查看>>
PATA1038题解(需复习)
查看>>
Patching Array
查看>>
Spring源码学习(二):Spring容器之prepareContext和BeanFactoryPostProcessor的介绍
查看>>
PatchMatchStereo可能会需要的Rectification
查看>>
Path does not chain with any of the trust anchors
查看>>
Path形状获取字符串型变量数据
查看>>
PAT甲级——1001 A+B Format (20分)
查看>>