博客
关于我
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/

你可能感兴趣的文章
npm报错fatal: Could not read from remote repository
查看>>
npm报错File to import not found or unreadable: @/assets/styles/global.scss.
查看>>
npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
查看>>
npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
查看>>
npm版本过高问题
查看>>
npm的“--force“和“--legacy-peer-deps“参数
查看>>
npm的安装和更新---npm工作笔记002
查看>>
npm的常用配置项---npm工作笔记004
查看>>
npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
查看>>
npm编译报错You may need an additional loader to handle the result of these loaders
查看>>
npm设置淘宝镜像、升级等
查看>>
npm设置源地址,npm官方地址
查看>>
npm设置镜像如淘宝:http://npm.taobao.org/
查看>>
npm配置安装最新淘宝镜像,旧镜像会errror
查看>>
NPM酷库052:sax,按流解析XML
查看>>
npm错误 gyp错误 vs版本不对 msvs_version不兼容
查看>>
npm错误Error: Cannot find module ‘postcss-loader‘
查看>>
npm,yarn,cnpm 的区别
查看>>
NPOI
查看>>
NPOI之Excel——合并单元格、设置样式、输入公式
查看>>