本文会介绍如何将语句组织成函数,还会详细介绍参数和作用域的概念,以及递归的概念及其在程序中的用途。
一. 创建函数
函数是可以调用,它执行某种行为并且返回一个值。用def语句即可定义一个函数:(并非所有的函数都会返回一些东西)
def fibs(num):
result = [0,1]
for i in range(num-2):
result.append(result[-2]+result[-1])
return result
记录函数
如果想给函数写文档以便让人理解的话,可以加入注释(以#开头)。另一个方式就是直接写上字符串,它会作为函数的一部分进行存储,这成为文档字符串。
def square(x):
'计算x的平方'
return x*x
#文档字符串可以按如下方式访问:
>>> square._doc_
'计算x的平方'
二. 参数魔法
函数使用起来很简单,创建起来也不复杂,但是函数参数的用法有时就不可思议了。
2.1 我能改变参数吗
在函数内为参数赋予新值,不会改变外部任何变量的值:
>>> def to_change(n):
n = 's'
>>> name = 'b'
>>> to_change(name)
>>> name
'b'
字符串(以及数字和元组)是不可变的,即无法被修改。但是如果将可变的数据结构如列表用作参数时,参数就会被改变了。
>>> def change(n):
n[0] = 'ss'
>>> names = ['aa','zz']
>>> change(names)
>>> names
['ss', 'zz']
2.2 关键字参数和默认值
目前为止,我们所使用的参数都叫做位置参数。有时候参数顺序是很难记住的,为了让事情简单些,可以提供参数的名字:
>>> def hello(greeting,name):
print '%s,%name!'
>>> hello(greeting = 'hello',name = 'world')
hello,world!
这样一来,参数顺序就完全没影响了,但是参数名和值一定要对应。
这样使用参数名提供的参数叫做关键字参数,主要作用在于可以明确每个参数的作用。
关键字参数最厉害的地方在于可以在函数中给参数提供默认值:
>>> def hello(greeting = 'hello',name = 'world'):
print '%s,%name!'
当参数具有默认值时,调用的时候就不用提供参数了,可以不提供,提供一些或提供所有的参数。
>>> hello()
'hello,world!'
>>> hello('greeting')
'greeting,world!'
>>> hello(name = 'universe')
'hello,universe!'
2.3 收集参数
如果函数中能存储多个名字就好了,用户可以给函数提供任意多的参数,我们需要这样做:定义函数时提供一个参数,在前面加个星号。
>>> def print_para(*paras):
print paras
>>> print_para('ss')
('ss',)
>>> print_para(1,2,3)
(1, 2, 3)
参数前的星号将所有值放置在同一个元组中,可以说是将这些“其余位置的参数”收集起来再使用。如果不提供任何收集元素,参数得到的是一个空元组()。
但是如果需要处理关键字参数的“收集”操作,我们需要2个星号“**”:
>>> def print_params(x,y,z=3,*pospar,**keypar):
print x,y,z
print pospar
print keypar
>>> print_params(1,2,3,5,6,7,foo=1,bar=2)
1 2 3
(5, 6, 7)
{'foo': 1, 'bar': 2}
>>> print_params(1,2)
1 2 3
()
{}
请仔细体味上面的例子,前三个参数是固定的,第四个参数pospar是位置参数,可以收集多个参数,第五个参数是关键字参数,可以收集多个关键字参数。当没有输入时,默认为空元组或者空字典。
2.4 反转过程
刚刚已经讨论过如何将参数收集为元组和字典了,如果使用*和**的话,还可以执行相反的操作。(1)在调用的时候使用
>>> def add(x,y):
return x+y
>>> params =(1,2)
>>> add(*params)
3
(2)在定义的时候使用
>>> def with_stars(**kds):
print kds['name'],'is',kds['age'],'years old'
>>> args = {'name':'Mr.Gumby','age':42}
>>> with_stars(**args)
Mr.Gumby is 42 years old
三. 作用域
在执行x=1赋值语句后,名称x引用到值1。这就像用字典一样,键引用值,当然,变量和所对应的值用的是个‘不可见'的字典。内建vars函数可以返回这个字典:
>>> x=1
>>> scope = vars()
>>> scope['x']
1
>>> scope['x'] += 1
>>> x
2
这个不可见的字典叫做命名空间或者作用域。除了全局作用域外,每个函数调用都会创建一个新的作用域。
一般学过编程的基本都知道什么是作用域了,这里就不细讲了。
四. 递归
递归的定义包括它们自身定义内容的引用。
一个有用的递归函数包含以下几部分:
(1)当函数直接返回值时有基本实例(最小可能性问题)
(2)递归实例,包括一个或者多个问题最小部分的递归调用。
这里的关键是将问题分解为小部分,递归不能永远继续下去,因为它总是以最小可能性问题结束,而这些问题又存储在基本实例中。
下面我们来看3个经典的递归例子:
A.阶乘
>>> def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
[/code]
B.幂
>>> def power(x,n):
if n == 0:
return 1
else:
return x * power(x,n-1)
C.二元查找(假设number必然在序列sequence中)
>>> def search(sequence,number,lower,upper):
if lower == upper:
assert num == sequence[upper]
return upper
else:
middle = (lower+upper) // 2
if number > sequence[middle]:
return search(sequence,number,middle+1,upper)
else:
return search(sequence,number,lower,middle)

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.