Python syntax: task 05 (functions and Lambda expressions)

function

A function is a named block of code used to do specific work. To perform a special task defined by a function, call the function. When you need to execute the same task multiple times in a program, you don't need to write the code to complete the task repeatedly, but just call the function to execute the task and let python run the code.

Defined function

# -*- coding: GBK -*-
def greet_user():             (1)
	"""Show simple greetings"""     (2)
	print('hello!')           (3)
greet_user()                  (4)

This is a simple function for printing greetings. The code line at (1) uses the keyword def to define a function named green_user, which can complete the work without any information, so the brackets are empty and the definition ends with a colon. The contraction immediately after the definition forms the function body: (2) the text at is a comment called the document string, describing what the function does, and the document string is surrounded by three quotation marks. Line (3) is the only line of code in the function body. (4) to call the function, you can specify the function name and the necessary information caused by brackets in turn. Because this function does not need any information, just enter greet_user().

Passing information to a function

# -*- coding: GBK -*-
def greet_user(username):
	"""Show simple greetings"""
	print('hello,'+username.title())
greet_user("jesse")       #hello,Jesse

Modify the above program slightly. You can let the function not only print hello, but also specify the user's name. To do this, you can add username in parentheses and pass it to username by specifying a value when you call the function. Similarly, when you specify a value with a different name, you get the same result.

# -*- coding: GBK -*-
def greet_user(username):
	"""Show simple greetings"""
	print('hello,'+username.title())
greet_user("sarah")       #hello,Sarah

In these two examples, user name is a parameter (a piece of information required for the function to complete its work) in the definition of the function greet Uuser. In the code greet Uuser ("jesse"), the value "jesse" is an argument, and the argument is the information passed to the function when calling the function. Above, we pass the argument "jesse" to the function greet Uuser (), which is stored in the parameter username.

Transfer argument
Since a function definition may contain multiple parameters, a function call may also contain multiple arguments. There are many ways to pass arguments to functions. You can use positional arguments, which requires that the order of arguments is the same as that of formal arguments. You can also use keyword arguments, where each variable consists of variable name and value. You can also use lists and dictionaries.

Location parameter
When you call a function, python must associate each argument in the function call with a parameter in the function definition. For this reason, the simplest way to associate is based on the order of arguments. This association is called a positional argument.

# -*- coding: GBK -*-
def describe_pet(animal_type,pet_name):
	"""Display pet information"""
	print("\nI have a "+animal_type+".")
	print("My "+animal_type+"'s name is "+pet_name.title()+'.')
describe_pet("hamster","harry")          
#I have a hamster.
#My hamster's name is Harry.

Function can also be called multiple times

# -*- coding: GBK -*-
def describe_pet(animal_type,pet_name):
	"""Display pet information"""
	print("\nI have a "+animal_type+".")
	print("My "+animal_type+"'s name is "+pet_name.title()+'.')
describe_pet("hamster","harry") 
describe_pet("dog","willie")         
#I have a hamster.
#My hamster's name is Harry.

#I have a dog.
#My dog's name is Willie.

When using positional arguments to call functions, the order of arguments is very important. If the order of arguments is not correct, this may happen:

# -*- coding: GBK -*-
def describe_pet(animal_type,pet_name):
	"""Display pet information"""
	print("\nI have a "+animal_type+".")
	print("My "+animal_type+"'s name is "+pet_name.title()+'.')
describe_pet("harry","hamster") 
       
#I have a harry.
#My harry's name is Hamster.

This is not what we want.

Keyword arguments
The key argument is the name value pair passed to the function. You associate names and values directly in arguments, so you don't get confused passing arguments to functions (you don't get harry named hammer).

# -*- coding: GBK -*-
def describe_pet(animal_type,pet_name):
	"""Display pet information"""
	print("\nI have a "+animal_type+".")
	print("My "+animal_type+"'s name is "+pet_name.title()+'.')
describe_pet(animal_type="hamster",pet_name="harry") 
       
#I have a hamaster.
#My hamaster's name is Harry.

Default value
When you write a function, you can specify a default value for each parameter. When an argument is provided to a parameter in a calling function, python uses the specified argument value; otherwise, the default value of the parameter is used.

# -*- coding: GBK -*-
def describe_pet(pet_name,animal_type='dog'):
	"""Display pet information"""
	print("\nI have a "+animal_type+".")
	print("My "+animal_type+"'s name is "+pet_name.title()+'.')
describe_pet(animal_type="hamster",pet_name="harry") 
describe_pet(pet_name="willie")        
#I have a hamaster.
#My hamaster's name is Harry.

#I have a dog.
#My dog's name is Willie.

Notice that in this function definition, the order of the parameters is changed. Since the default value is specified for animal_type, there is no need to specify the animal type through arguments, so the function call only contains one argument -- the pet's name. However, python still treats this argument as a positional argument, so if the function call contains only the pet's name, the argument will be associated with the first parameter in the function definition. That's why you need to put pet? Name at the beginning of the parameter list.

Return value

# -*- coding: GBK -*-
def describe_pet(pet_name):
	"""Display pet information"""
	return pet_name.title()
print(describe_pet("harry"))  #Harry

Pass any number of arguments

# -*- coding: GBK -*-
def make_pizza(*toppings):
	"""Print all ingredients ordered by customers"""
	print(toppings)
make_pizza('pepperoni')                               #('pepperoni')
make_pizza('pepperoni','mushroom','green peppers')    #('pepperoni','mushroom','green peppers')

Keywords: Python

Added by benjy on Sat, 26 Oct 2019 16:47:22 +0300