The 8th chapter mainly exercises various functions, the contents are as follows
To define a simple function
Passing information to a function
What is a formal parameter
What is an argument
Position parameters
Calling functions multiple times
Keyword arguments
Default value parameter
Returned value return
Let the parameters be programmed with optional
Back to Dictionary
Using functions and while loops together
Delivery List
To modify a list in a function
Pass any number of arguments
Pass any number of parameters and cycle through the print
Use positional parameters together with any number of arguments
Use any number of keyword arguments
Import the entire module
Import a specific function
Assigning an alias to a function using as
Assigning an alias to a module using as
Import all functions in a module
To define a simple function
Directly call the function, you can print
--------------------------
Def greet_user ():
Print ("hello!")
Greet_user ()
---------------------------
Hello!
Passing information to a function
Username is just a formal parameter
------------------------------------------------------
def greet_user (username):
Print ("Hello," + username.title () + "!")
Greet_user (' Zhao ')
------------------------------------------------------
Hello, zhao!.
What is a formal parameter?
Take the code above as an example. Username is the formal parameter, it only represents greet_user this function needs to pass a parameter
It doesn't matter if it's called username or Nameuser.
What arguments?
Take the code above as an example. ' Zhao ' is an argument, and a summary is a real parameter to get the code to execute.
bit Place Arguments
The order of positional arguments is specified in the function brackets
Input parameters must be operated according to formal parameter hints
In short, the order of positional arguments is important.
-------------------------------------------------------------------------------------------
def describe_pet (Animal_type, Pet_name):
Print ("\ni has 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.
Calling functions multiple times
------------------------------------------------------------------------------------------
def describe_pet (Animal_type, Pet_name):
Print ("\ni has 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.
Keyword arguments
When a function is called, an argument is specified with the formal parameter, even if the position is wrong, it can be called normally.
------------------------------------------------------------------------------------------
def describe_pet (animal_type, Pet_name):
Print ("\ni has 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 ', Animal_type= ' dog ')
------------------------------------------------------------------------------------------
I have a hamster.
My Hamster ' s name is Harry.
I have a dog.
My Dog ' s name is Willie.
Default value
Specify an argument in the Describe_pet parameter of the SET function, when called
You can call it by default without specifying it.
------------------------------------------------------------------------------------------
def describe_pet (pet_name, animal_type= ' dog '):
Print ("\ni has a" + Animal_type + ".")
Print ("My" + Animal_type + "s name is" + pet_name.title () + ".")
Describe_pet (pet_name= ' Willie ')
------------------------------------------------------------------------------------------
I have a dog.
My Dog ' s name is Willie.
You can also make it easier to call
------------------------------------------------------------------------------------------
def describe_pet (pet_name, animal_type= ' dog '):
Print ("\ni has a" + Animal_type + ".")
Print ("My" + Animal_type + "s name is" + pet_name.title () + ".")
Describe_pet (' Willie ')
------------------------------------------------------------------------------------------
I have a dog.
My Dog ' s name is Willie.
return value
Return Full_name.title () converts the value of full_name to the letter capitalization format
and returns the result to the function call line
Variable Full_name a space between two + middle single quotes in the row
If there are no spaces, the printed effect is also two
-----------------------------------------------------------------
def get_formatted_name (first_name, last_name):
Full_name = first_name + "+ last_name
return Full_name.title ()
Musician = Get_formatted_name (' Jimi ', ' Hendrix ')
Print (musician)
-----------------------------------------------------------------
Jimi Hendrix
Let the parameter become optional
Python interprets a non-empty string as True if there is no middle_name parameter, execute else code
You must ensure that the Middle_name parameter is the last argument
-----------------------------------------------------------------------------------------
def get_formatted_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 ()
Musician = Get_formatted_name (' Jimi ', ' Hendrix ')
Print (musician)
Musician = Get_formatted_name (' John ', ' Hooker ', ' Lee ')
Print (musician)
-----------------------------------------------------------------------------------------
Jimi Hendrix
John Lee Hooker
Back to Dictionary
----------------------------------------------------------------
def build_person (first_name, last_name):
person = {' First ': first_name, ' last ': last_name}
return person
Musician = Build_person (' Jimi ', ' Hendrix ')
Print (musician)
----------------------------------------------------------------
{' First ': ' Jimi ', ' Last ': ' Hendrix '}
As an example of the above code, add a formal parameter age and set it to an empty string
If the user enters a name, it is added to the dictionary
-----------------------------------------------------------------
def build_person (first_name, last_name, age= "):
person = {' First ': first_name, ' last ': last_name}
If Age:
person[' age ') = Age
return person
Musician = Build_person (' Jimi ', ' Hendrix ', age=18)
Print (musician)
-----------------------------------------------------------------
{' First ': ' Jimi ', ' Last ': ' Hendrix ', ' Age ': 18}
Using functions and while loops together
If the user enters Q, you can exit at any time
----------------------------------------------------------------------------------
def get_formatted_name (first_name, last_name):
Full_name = first_name + "+ last_name
Return Full_name.title ()
While True:
Print ("\nplease tell Me Your name:")
Print ("(Enter ' Q ' at any time to quit)")
F_name = input ("First Name:")
if f_name = = ' Q ':
Break
L_name = input ("Last Name:")
if l_name = = ' Q ':
Break
Formatted_name = Get_formatted_name (f_name, L_name)
Print ("\nhello," + Formatted_name + "!")
----------------------------------------------------------------------------------
Please tell me your name:
(Enter ' Q ' at any time to quit)
First Name:zhao
Last Name:lulu
Hello, Zhao lulu!
Please tell me your name:
(Enter ' Q ' at any time to quit)
First Name:q
Delivery List
The greet_users () names parameter in the function is just a formal parameter,
And the argument is the list to be passed in
----------------------------------------------------
def greet_users (names):
For name in Names:
msg = "Hello," + name.title () + "!"
Print (msg)
usernames = [' Hannah ', ' Ty ', ' Margot ']
Greet_users (usernames)
----------------------------------------------------
Hello, hannah!.
Hello, ty!.
Hello, margot!.
To modify a list in a function
-------------------------------------------------------------------------------------------
Unprinted_models = [' iphone case ', ' Robot pendant ', ' dodecahedron ']
Completed_models = []
While Unprinted_models:
Current_design = Unprinted_models.pop ()
Print ("Printing model:" + current_design)
Completed_models.append (current_design)
Print ("\nthe following models has been printed:")
For Completed_model in Completed_models:
Print (Completed_model)
-------------------------------------------------------------------------------------------
Printing Model:dodecahedron
Printing Model:robot Pendant
Printing Model:iphone Case
The following models has been printed:
Dodecahedron
Robot Pendant
iphone case
Reorganize the above code and call it in a function
-------------------------------------------------------------------------------------------
def print_models (Unprinted_designs, completed_models):
While unprinted_designs:
Current_design = Unprinted_designs.pop ()
Print ("Printing model:" + current_design)
Completed_models.append (current_design)
def show_completed_models (completed_models):
Print ("\nthe following models has been printed:")
For Completed_model in Completed_models:
Print (Completed_model)
unprinted_designs = [' iphone case ', ' Robot pendant ', ' dodecahedron ']
Completed_models = []
Print_models (unprinted_designs, Completed_models)
Show_completed_models (Completed_models)
-------------------------------------------------------------------------------------------
Printing Model:dodecahedron
Printing Model:robot Pendant
Printing Model:iphone Case
The following models has been printed:
Dodecahedron
Robot Pendant
iphone case
Pass any number of arguments
-----------------------------------------------------------------------------
def make_pizza (*toppings):
Print (toppings)
Make_pizza (' pepperoni ')
Make_pizza (' mushrooms ', ' green peppers ', ' extra cheese ')
-----------------------------------------------------------------------------
(' Pepperoni ',)
(' mushrooms ', ' green peppers ', ' extra cheese ')
Pass any number of parameters and cycle through the print
----------------------------------------------------------------------------
def Make_pizza (*toppings):
Print ("\nmaking a pizza with the following toppings:")
For topping in toppings:
Print ("-" + topping)
Make_pizza (' pepperoni ')
Make_pizza (' mushrooms ', ' green peppers ', ' extra cheese ')
----------------------------------------------------------------------------
Making a pizza with the following toppings:
-Pepperoni
Making a pizza with the following toppings:
-Mushrooms
-Green Peppers
-Extra cheese
Use positional parameters together with any number of arguments
-----------------------------------------------------------------------------------------------------
def make_pizza (Size, *toppings):
Print ("\nmaking a" + str (size) + "-inch pizza with the following toppings:")
For topping in toppings:
Print ("-" + topping)
Make_pizza (+, ' pepperoni ')
Make_pizza (mushrooms ', ' green peppers ', ' extra cheese ')
-----------------------------------------------------------------------------------------------------
Making a 17-inch pizza with the following toppings:
-Pepperoni
Making a 19-inch pizza with the following toppings:
-Mushrooms
-Green Peppers
-Extra cheese
Use any number of keyword arguments
Define an empty list first
The For loop adds the parameters to the profile dictionary and returns
---------------------------------------------------------------
Def build_profile (First, Last, **user_info):
profile = {}
profile[' first_name ' = First
profile[' last_name '] = Last
for key, value in user_ Info.items () :
Profile[key] = value
return profile
User_profile = Build_profile (' Albert ', ' Einstein ',
Location= ' Princeton ',
Field= ' physics ')
Print (User_profile)
---------------------------------------------------------------
{' first_name ': ' Albert ', ' last_name ': ' Einstein ', ' Location ': ' Princeton ', ' field ': ' Physics '}
Import the entire module
pizza.py file contents are as follows
------------------------------------------------------------------------------------------------------
def make_pizza (Size, *toppings):
Print ("\nmaking a" + str (size) + "-inch pizza with the following toppings:")
For topping in toppings:
Print ("-" + topping)
making_pizzas.py file contents are as follows
----------------------------------------------------------------------------------------
Import Pizza
Pizza.make_pizza (+, ' pepperoni ')
Pizza.make_pizza (' mushrooms ', ' green peppers ', ' extra cheese ')
----------------------------------------------------------------------------------------
Making a 16-inch pizza with the following toppings:
-Pepperoni
Making a 12-inch pizza with the following toppings:
-Mushrooms
-Green Peppers
-Extra cheese
Import a specific function
---------------------------------------------------------------------------------
From pizza Import Make_pizza
Make_pizza (+, ' pepperoni ')
Make_pizza (' mushrooms ', ' green peppers ', ' extra cheese ')
---------------------------------------------------------------------------------
Making a 16-inch pizza with the following toppings:
-Pepperoni
Making a 12-inch pizza with the following toppings:
-Mushrooms
-Green Peppers
-Extra cheese
Assigning an alias to a function using as
--------------------------------------------------------------------
From pizza import Make_pizza as MP
MP (+, ' pepperoni ')
MP (mushrooms ', ' green peppers ', ' extra cheese ')
Assigning an alias to a module using as
------------------------------------------------------------------------------------
Import Pizza as P
P.make_pizza (+, ' pepperoni ')
P.make_pizza (' mushrooms ', ' green peppers ', ' extra cheese ')
Import all functions in a module
-----------------------------------------------------------------------------------
From Pizza Import *
Make_pizza (+, ' pepperoni ')
Make_pizza (' mushrooms ', ' green peppers ', ' extra cheese ')
This article is from the "LULU" blog, make sure to keep this source http://aby028.blog.51cto.com/5371905/1965495
Getting started with Python programming to Practice-notes (Chapter 8)