初学Python函数的笔记整理
定义
返回单值
def my_abs(x): if x >= 0: return x else: return -x
返回多值
返回多值就是返回一个tuple
import math def move(x, y, step, angle=0): nx = x + step * math.cos(angle) ny = y - step * math.sin(angle) return nx, ny
空函数
def nop(): pass
指定默认参数
必选参数在前,默认参数在后。默认参数需指向不可变对象(默认参数值在函数定义时被计算)
def power(x, n=2): s = 1 while n > 0: n = n - 1 s = s * x return s
可变参数
def calc(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum
调用可变参数的函数方法
>>> calc(1, 2) 5 >>> calc() 0 >>> nums = [1, 2, 3] >>> calc(*nums) 14
关键字参数
def person(name, age, **kw): print 'name:', name, 'age:', age, 'other:', kw
调用关键字参数的方法
>>> person('Michael', 30) name: Michael age: 30 other: {} >>> person('Bob', 35, city='Beijing') name: Bob age: 35 other: {'city': 'Beijing'} >>> person('Adam', 45, gender='M', job='Engineer') name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'} >>> kw = {'city': 'Beijing', 'job': 'Engineer'} >>> person('Jack', 24, **kw) name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}
注:
参数定义的顺序必须是:必选参数、默认参数、可变参数和关键字参数。
对于任意函数,都可以通过类似func(*args, **kw)的形式调用它,无论它的参数是如何定义的。
递归
如果一个函数在内部调用自身本身,这个函数就是递归函数。
尾递归
在函数返回的时候,调用自身本身,并且,return语句不能包含表达式。
高阶函数
- 变量可以指向函数(函数可以赋值给一个变量)
- 函数名也是变量(函数名可以赋值其他值)
- 函数可以做为函数的参数(高阶函数)
map(func, list)
map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回。
>>> def f(x): ... return x * x ... >>> map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) [1, 4, 9, 16, 25, 36, 49, 64, 81]
reduce把一个函数作用在一个序列[x1, x2, x3…]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算。
reduce(f, [x1, x2, x3, x4]) #相当于: f(f(f(x1, x2), x3), x4) >>> def add(x, y): ... return x + y ... >>> reduce(add, [1, 3, 5, 7, 9]) 25
filter(func_return_bool, list)
把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
def is_odd(n): return n % 2 == 1 filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]) # 结果: [1, 5, 9, 15]
sorted
对于两个元素x和y,如果认为x < y,则返回-1,如果认为x == y,则返回0,如果认为x > y,则返回1,
>>> sorted([36, 5, 12, 9, 21]) [5, 9, 12, 21, 36]
高阶函数用法
def reversed_cmp(x, y): if x > y: return -1 if x < y: return 1 return 0 >>> sorted([36, 5, 12, 9, 21], reversed_cmp) [36, 21, 12, 9, 5]
函数做为返回值
def lazy_sum(*args): def sum(): ax = 0 for n in args: ax = ax + n return ax return sum >>> f = lazy_sum(1, 3, 5, 7, 9) >>> f <function sum at 0x10452f668> >>> f() 25
注:每次调用lazy_sum()都会返回一个新的函数,即使传入相同的参数。
闭包
def count(): fs = [] for i in range(1, 4): def f(): return i*i fs.append(f) return fs f1, f2, f3 = count() >>> f1() 9 >>> f2() 9 >>> f3() 9
原因是调用count的时候循环已经执行,但是f()还没有执行,直到调用其时才执行。所以返回函数不要引用任何循环变量,或者后续会发生变化的变量。
匿名函数(lambda表达式)
等价于:
def f(x): return x * x
关键字lambda表示匿名函数,冒号前面的x表示函数参数。
匿名函数做为返回值
def build(x, y): return lambda: x * x + y * y
装饰器(@func)
在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator),本质上,decorator就是一个返回函数的高阶函数。
def log(func): def wrapper(*args, **kw): print 'call %s():' % func.__name__ return func(*args, **kw) return wrapper @log def now(): print '2013-12-25' >>> now() call now(): 2013-12-25 #相当于执行: now = log(now) 回到顶部 带参数的装饰器 def log(text): def decorator(func): def wrapper(*args, **kw): print '%s %s():' % (text, func.__name__) return func(*args, **kw) return wrapper return decorator @log('execute') def now(): print '2013-12-25' #执行结果 >>> now() execute now(): 2013-12-25 #相当于执行: >>> now = log('execute')(now)
剖析:首先执行log('execute'),返回的是decorator函数,再调用返回的函数,参数是now函数,返回值最终是wrapper函数。
import functools def log(func): @functools.wraps(func) def wrapper(*args, **kw): print 'call %s():' % func.__name__ return func(*args, **kw) return wrapper #对于带参函数 import functools def log(text): def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): print '%s %s():' % (text, func.__name__) return func(*args, **kw) return wrapper return decorator
>>> import functools >>> int2 = functools.partial(int, base=2) >>> int2('1000000') 64 >>> int2('1010101') 85 #相当于: def int2(x, base=2): return int(x, base) max2 = functools.partial(max, 10)
相当于为max函数指定了第一个参数
max2(5, 6, 7) #相当于: max(10, 5, 6, 7)

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

Yes, VS Code can run Python code. To run Python efficiently in VS Code, complete the following steps: Install the Python interpreter and configure environment variables. Install the Python extension in VS Code. Run Python code in VS Code's terminal via the command line. Use VS Code's debugging capabilities and code formatting to improve development efficiency. Adopt good programming habits and use performance analysis tools to optimize code performance.
