首页 > 编程 > Python > 正文

Python 函数用法简单示例【定义、参数、返回值、函数嵌套】

2019-11-25 11:41:21
字体:
来源:转载
供稿:网友

本文实例讲述了Python 函数用法。分享给大家供大家参考,具体如下:

demo.py(函数定义):

# say_hello() # 不能在定义函数之前调用函数# Python 解释器知道下方定义了一个函数def say_hello():  """函数的说明文档"""  print("hello 1")  print("hello 2")  print("hello 3")print("调用函数之前")# 只有在程序中,主动调用函数,才会让函数执行say_hello()print("调用函数之后")

运行结果:

调用函数之前
hello 1
hello 2
hello 3
调用函数之后

demo.py(函数的参数、返回值):

def sum_2_num(num1, num2):  """对两个数字的求和"""  result = num1 + num2  return result # 通过return返回结果# 可以使用变量,来接收函数执行的返回结果sum_result = sum_2_num(10, 20)print("计算结果:%d" % sum_result)

运行结果:

计算结果:30

demo.py(函数的嵌套):

def test1():  print("*" * 50)def test2():  print("-" * 50)  # 函数的嵌套调用  test1()  print("+" * 50)test2()

运行结果:

--------------------------------------------------
**************************************************
++++++++++++++++++++++++++++++++++++++++++++++++++

关于Python相关内容感兴趣的读者可查看本站专题:《Python函数使用技巧总结》、《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表