本文以实例形式较为详细的讲述了Python函数的用法,对于初学Python的朋友有不错的借鉴价值。分享给大家供大家参考之用。具体分析如下:
通常来说,Python的函数是由一个新的语句编写,即def,def是可执行的语句--函数并不存在,直到Python运行了def后才存在。
函数是通过赋值传递的,参数通过赋值传递给函数
def语句将创建一个函数对象并将其赋值给一个变量名,def语句的一般格式如下:
def <name>(arg1,arg2,arg3,……,argN): <statements>
def语句是实时执行的,当它运行的时候,它创建并将一个新的函数对象赋值给一个变量名,Python所有的语句都是实时执行的,没有像独立的编译时间这样的流程
由于是语句,def可以出现在任一语句可以出现的地方--甚至是嵌套在其他语句中:
if test: def fun(): ... else: def func(): ... ... func()
可以将函数赋值给一个不同的变量名,并通过新的变量名进行调用:
othername=func() othername()
创建函数
内建的callable函数可以用来判断函数是否可调用:
>>> import math >>> x=1 >>> y=math.sqrt >>> callable(x) False >>> callable(y) True
使用del语句定义函数:
>>> def hello(name): return 'Hello, '+name+'!' >>> print hello('world') Hello, world! >>> print hello('Gumby') Hello, Gumby!
编写一个fibnacci数列函数:
>>> def fibs(num): result=[0,1] for i in range(num-2): result.append(result[-2]+result[-1]) return result >>> fibs(10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] >>> fibs(15) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
在函数内为参数赋值不会改变外部任何变量的值:
>>> def try_to_change(n): n='Mr.Gumby' >>> name='Mrs.Entity' >>> try_to_change(name) >>> name 'Mrs.Entity'
由于字符串(以及元组和数字)是不可改变的,故做参数的时候也就不会改变,但是如果将可变的数据结构如列表用作参数的时候会发生什么:
>>> name='Mrs.Entity' >>> try_to_change(name) >>> name 'Mrs.Entity' >>> def change(n): n[0]='Mr.Gumby' >>> name=['Mrs.Entity','Mrs.Thing'] >>> change(name) >>> name ['Mr.Gumby', 'Mrs.Thing']
参数发生了改变,这就是和前面例子的重要区别
以下不用函数再做一次:
>>> name=['Mrs.Entity','Mrs.Thing'] >>> n=name #再来一次,模拟传参行为 >>> n[0]='Mr.Gumby' #改变列表 >>> name ['Mr.Gumby', 'Mrs.Thing']
当2个变量同时引用一个列表的时候,它们的确是同时引用一个列表,想避免这种情况,可以复制一个列表的副本,当在序列中做切片的时候,返回的切片总是一个副本,所以复制了整个列表的切片,将会得到一个副本:
>>> names=['Mrs.Entity','Mrs.Thing'] >>> n=names[:] >>> n is names False >>> n==names True
此时改变n不会影响到names:
>>> n[0]='Mr.Gumby' >>> n ['Mr.Gumby', 'Mrs.Thing'] >>> names ['Mrs.Entity', 'Mrs.Thing'] >>> change(names[:]) >>> names ['Mrs.Entity', 'Mrs.Thing']
关键字参数和默认值
参数的顺序可以通过给参数提供参数的名字(但是参数名和值一定要对应):
>>> def hello(greeting, name): print '%s,%s!'%(greeting, name) >>> hello(greeting='hello',name='world!') hello,world!!
关键字参数最厉害的地方在于可以在参数中给参数提供默认值:
>>> def hello_1(greeting='hello',name='world!'): print '%s,%s!'%(greeting,name) >>> hello_1() hello,world!! >>> hello_1('Greetings') Greetings,world!! >>> hello_1('Greeting','universe') Greeting,universe!
若想让greeting使用默认值:
>>> hello_1(name='Gumby') hello,Gumby!
可以给函数提供任意多的参数,实现起来也不难:
>>> def print_params(*params): print params >>> print_params('Testing') ('Testing',) >>> print_params(1,2,3) (1, 2, 3)
混合普通参数:
>>> def print_params_2(title,*params): print title print params >>> print_params_2('params:',1,2,3) params: (1, 2, 3) >>> print_params_2('Nothing:') Nothing: ()
星号的意思就是“收集其余的位置参数”,如果不提供任何供收集的元素,params就是个空元组
但是不能处理关键字参数:
>>> print_params_2('Hmm...',something=42) Traceback (most recent call last): File "<pyshell#112>", line 1, in <module> print_params_2('Hmm...',something=42) TypeError: print_params_2() got an unexpected keyword argument 'something'
试试使用“**”:
>>> def print_params(**params): print params >>> print_params(x=1,y=2,z=3) {'y': 2, 'x': 1, 'z': 3} >>> def parames(x,y,z=3,*pospar,**keypar): print x,y,z print pospar print keypar >>> parames(1,2,3,5,6,7,foo=1,bar=2) 1 2 3 (5, 6, 7) {'foo': 1, 'bar': 2} >>> parames(1,2) 1 2 3 () {} >>> def print_params_3(**params): print params >>> print_params_3(x=1,y=2,z=3) {'y': 2, 'x': 1, 'z': 3} >>> #返回的是字典而不是元组 >>> #组合‘#'与'##' >>> def print_params_4(x,y,z=3,*pospar,**keypar): print x,y,z print pospar print keypar >>> print_params_4(1,2,3,5,6,7,foo=1,bar=2) 1 2 3 (5, 6, 7) {'foo': 1, 'bar': 2} >>> print_params_4(1,2) 1 2 3 () {}
相信本文所述对大家Python程序设计的学习有一定的借鉴价值。

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

Python is suitable for rapid development and data processing, while C is suitable for high performance and underlying control. 1) Python is easy to use, with concise syntax, and is suitable for data science and web development. 2) C has high performance and accurate control, and is often used in gaming and system programming.

The time required to learn Python varies from person to person, mainly influenced by previous programming experience, learning motivation, learning resources and methods, and learning rhythm. Set realistic learning goals and learn best through practical projects.

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.

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.


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

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.

Zend Studio 13.0.1
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools