Home Backend Development Python Tutorial 讲解python参数和作用域的使用

讲解python参数和作用域的使用

Jun 16, 2016 am 08:46 AM
python

本文会介绍如何将语句组织成函数,还会详细介绍参数和作用域的概念,以及递归的概念及其在程序中的用途。
一. 创建函数
函数是可以调用,它执行某种行为并且返回一个值。用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)
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

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.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

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.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

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.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

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.

See all articles