程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python Basics - defining functions

編輯:Python

Catalog

1. Defined function :

1.1 Passing information to a function

1.2 Arguments and formal arguments

2. Transfer argument :

2.1 Location parameter

2.1 Keyword arguments

2.2 The default value is :

2.3 Equivalent function call

2.4 Avoid argument errors

3. Return value

3.1 Returns a simple value

3.2 Make arguments optional

3.3 Return dictionary

4. Delivery list

4.1 Disable function modification list

5. Pass any number of arguments :

5.1 Use a combination of positional arguments and any number of arguments

6. Store functions in modules :

6.1 Import the entire module import 

6.2 Import specific functions

6.3 Use as Give the function an alias

6.4 Use as Assign an alias to a module

6.5 Import all functions in the module , Use *


1. Defined function :

Use keywords def To define a function

def introduction():
print("Hello world!")
greet_user()

1.1 Passing information to a function

def introduction(username):
print("Hello world!")
introduction('Xixi')

1.2 Arguments and formal arguments

With 1.1 As an example , In function introduction() The definition of :

Variable username It's a Shape parameter --- A piece of information required by a function to complete its work .

In the code introduction('Xixi') in , value 'Xixi' It's a Actual parameters , An argument is the information passed to the function when it is called .

2. Transfer argument :

2.1 Location parameter

def person(username,old):
print("I am" + username + ".")
print("I am" + old + "years old.")
person('Xixi','3')

The output result is :

I am Xixi.

I am 2 years old.

The order of positional arguments is important ! If you need to call this function multiple times , Just call... Again person() that will do .

2.1 Keyword arguments

The order of keyword arguments is not required , because Python Know which formal parameter the values should be stored in . The following two function calls are equivalent :

def person(username,old):
person(username='aa', old='two')
person(old='one',username='aa')

Be careful : When using keyword arguments , Be sure to specify the parameter name in the function definition exactly .

2.2 The default value is :

When an argument is provided to a formal parameter in the calling function ,Python The specified argument value will be used ; otherwise , The default value of the formal parameter will be used . therefore , After a parameter is assigned a default value , You can omit the corresponding arguments in the function call . Use default values to simplify function calls , The typical usage of functions can also be clearly pointed out .

# Set formal parameter old The default value of is set to '3'
def person(username,old='3'):

Be careful : When using default values , In the formal parameter list, the formal parameter without default value must be listed first , Then list the arguments with default values . This makes Python Still able to correctly interpret location arguments .

2.3 Equivalent function call

def pet(petname, anmal_type = 'cat'):
print("hhhhh")
# The following function calls are equivalent
pet('xxx')
pet(petname = 'xxx')
pet('aaa','dog')
pet(petname = 'aaa', anmal_type = 'dog')
pet(anmal_type = 'dog', petname = 'aaa')

2.4 Avoid argument errors

If argument mismatch occurs , You're going to report a mistake . appear traceback

3. Return value

3.1 Returns a simple value

In the function , You can use return sentence Return the value to the code line of the calling function . Functions do not always display output directly , contrary , It can process some data , And return one or a set of values . The value returned by a function is called the return value .

def get_name(first_name, last_name):
""" Return clean name """
full_name = first_name + ' ' + last_name
return full_name.title()
singer = get_name('jimi', 'hendrix')
print(singer)

3.2 Make arguments optional

def get_name(first_name, last_name, middle_name=''):
if middle_name:
full_name = first_name + ' ' + middle_name + ' ' + last_name
else:
full_name = first_name + ' ' + last_name
return full_name.title()
singer = get_name('kiki', 'hix')
print(singer)
musician = get_name('jon', 'lua', 'joe')
print(singer)

3.3 Return dictionary

def build_pet(name, age):
""" Return a dictionary , It contains information about a pet """
pet = {'first': name, 'last': age}
pet person
cat = build_person('kiki', '12')
print(cat)

4. Delivery list

def build_pet(name):
for name in names:
greeting = "Hello, " + name.title() + "!"
print(greeting)
petnames = ['cat', 'dog', 'tiger']
build_pet(petnames) 

4.1 Disable function modification list

build_pet(list_name[:])

 

5. Pass any number of arguments :

You can add a before the formal parameter in the first line *, for example :def build_pet(*age):

5.1 Use a combination of positional arguments and any number of arguments

  If you want a function to accept different types of arguments , Formal parameters of any number of arguments must be placed last in the function definition .Python First match location arguments and keyword arguments , Then collect the remaining arguments into the last parameter .

def build_pet(name ,*age):

6. Store functions in modules :

6.1 Import the entire module import 

Create a a.py file , Creating a b.py file , You can import the first file into the second file

6.2 Import specific functions

from xxx import xxx

By separating function names with commas , You can import any number of functions from the module as needed :

from xxx import function1,function2,function3

6.3 Use as Give the function an alias

from B import A as mp

6.4 Use as Assign an alias to a module

import A as mp

6.5 Import all functions in the module , Use *

from A import *

The learning content of this article refers to 《Python Programming : From introduction to practice 》


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved