码迷,mamicode.com
首页 > 编程语言 > 详细

python函数

时间:2019-07-10 01:18:11      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:nbsp   outer   info   dict   匿名函数   string   comment   oba   com   

1、函数定义

def 函数名():

  函数体

2.input函数和print函数

input()

接受一个标准输入数据,返回字符串类型

print("width =", w, " height =", h, " area =", area(w, h))

3.函数返回值

def 函数名():

  函数体

  return 变量

print(函数名)

4.函数参数

def 函数名(参数1,参数2)

  return 变量

c=函数名(参数1,参数2)

print(c)

 5.不定长参数

一个函数能处理比当初声明时更多的参数,加了*的参数以元组的形式被导入,存放未命名变量参数.加了**的以字典形式被导入。

def printinfo( arg1, *vartuple ):

  "打印任何传入的参数"

  print ("输出: ")

  print (arg1)

  print (vartuple)

# 调用printinfo 函数

printinfo( 70, 60, 50 )

printinfo( 10 )

 

def printinfo( arg1, **vardict ):

  函数体

printinfo(1, a=2,b=3)

 

如果单独出现星号 * 后的参数必须用关键字传入。

def f(a,b,*,c)

f(1,2,3) #错误

f(1,2,c=3)

 

6.匿名函数

  • lambda 只是一个表达式,函数体比 def 简单很多。
  • lambda的主体是一个表达式,而不是一个代码块。仅仅能在lambda表达式中封装有限的逻辑进去。
  • lambda 函数拥有自己的命名空间,且不能访问自己参数列表之外或全局命名空间里的参数。
  • 虽然lambda函数看起来只能写一行,却不等同于C或C++的内联函数,后者的目的是调用小函数时不占用栈内存从而增加运行效率。

a=lambda 变量1,变量2:函数体

a(变量1,变量2)

 

7.作用域

global 变量名 #局部变量变全局变量

nonlocal 变量名 #使局部变量在上一层也能用

def outer():

  num = 10

  def inner():

    nonlocal num # nonlocal关键字声明

    num = 100

    print(num)

  inner()

  print(num)

outer()

输出

100

100

#错误示范,因为 test 函数中的 a 使用的是局部,未定义,无法修改

a = 10

def test():

  a = a + 1

  print(a)

test()

#正确示范

a = 10

def test(a):

  a = a + 1

  print(a)

test(a)

 

python函数

标签:nbsp   outer   info   dict   匿名函数   string   comment   oba   com   

原文地址:https://www.cnblogs.com/rokoko/p/11159039.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!