Python基础之函数的定义与使用示例

yipeiwu_com7年前Python基础

本文实例讲述了Python基础之函数的定义与使用。分享给大家供大家参考,具体如下:

Python 定义函数使用 def 关键字,一般格式如下:

def 函数名(参数列表):
    函数体

让我们使用函数来输出"Hello World!":

>>> def hello() :
  print("Hello World!")
>>> hello()
Hello World!
>>>

更复杂点的应用,函数中带上参数变量:

def area(width, height):
  return width * height
def print_welcome(name):
  print("Welcome", name)
print_welcome("Fred")
w = 4
h = 5
print("width =", w, " height =", h, " area =", area(w, h))

以上实例输出结果:

Welcome Fred
width = 4 height = 5 area = 20

函数变量作用域

定义在函数内部的变量拥有一个局部作用域,定义在函数外的拥有全局作用域。通过以下实例,你可以清楚了解Python函数变量的作用域:

#!/usr/bin/env python3
a = 4 # 全局变量
def print_func1():
  a = 17 # 局部变量
  print("in print_func a = ", a)
def print_func2():
  print("in print_func a = ", a)
print_func1()
print_func2()
print("a = ", a)

以上实例运行结果如下:

in print_func a = 17
in print_func a = 4
a = 4

关键字参数

函数也可以使用 kwarg=value 的关键字参数形式被调用.例如,以下函数:

def parrot(voltage, state='a stiff', action='voom',
type='Norwegian Blue'):
  print("-- This parrot wouldn't", action, end=' ')
  print("if you put", voltage, "volts through it.")
  print("-- Lovely plumage, the", type)
  print("-- It's", state, "!")

可以以下几种方式被调用:

parrot(1000) # 1 positional argument
parrot(voltage=1000) # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump') # 3 positional arguments
parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword

以下为错误调用方法:

parrot() # required argument missing
parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument
parrot(110, voltage=220) # duplicate value for the same argument
parrot(actor='John Cleese') # unknown keyword argument

返回值

Python的函数的返回值使用return语句,可以将函数作为一个值赋值给指定变量:

def return_sum(x,y):
  c = x + y
  return c
res = return_sum(4,5)
print(res)

你也可以让函数返回空值:

def empty_return(x,y):
  c = x + y
  return res = empty_return(4,5)
print(res)

可变参数列表

最后,一个最不常用的选择是可以让函数调用可变个数的参数.这些参数被包装进一个元组(查看元组和序列).在这些可变个数的参数之前,可以有零到多个普通的参数:

def arithmetic_mean(*args):
  sum = 0
  for x in args:
    sum += x
  return sum
print(arithmetic_mean(45,32,89,78))
print(arithmetic_mean(8989.8,78787.78,3453,78778.73))
print(arithmetic_mean(45,32))
print(arithmetic_mean(45))
print(arithmetic_mean())

以上实例输出结果为:

244
170009.31
77
45
0

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

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

相关文章

numpy库与pandas库axis=0,axis= 1轴的用法详解

numpy库与pandas库axis=0,axis= 1轴的用法详解

对数据进行操作时,经常需要在横轴方向或者数轴方向对数据进行操作,这时需要设定参数axis的值: axis = 0 代表对横轴操作,也就是第0轴; axis = 1 代表对纵轴操...

基于python-opencv3的图像显示和保存操作

基于python-opencv3的图像显示和保存操作,具体代码如下所示: import cv2 as cv import numpy as np #导入库 pr...

浅谈python中str字符串和unicode对象字符串的拼接问题

str字符串 s = '中文' # s: <type 'str'> s是个str对象,中文字符串。存储方式是字节码。字节码是怎么存的: 如果这行代码在python解释...

python requests更换代理适用于IP频率限制的方法

python requests更换代理适用于IP频率限制的方法

有些网址具有IP限制,比如同一个IP一天只能点赞一次。 解决方法就是更换代理IP。 从哪里获得成千上万的IP呢? 百度“http代理” 可获得一大堆网站。 比如某代理网站,1天...

python用线性回归预测股票价格的实现代码

python用线性回归预测股票价格的实现代码

线性回归在整个财务中广泛应用于众多应用程序中。在之前的教程中,我们使用普通最小二乘法(OLS)计算了公司的beta与相对索引的比较。现在,我们将使用线性回归来估计股票价格。 线性回归是一...