Use functions to process elements in a list.
def greet_users (names): "
send a greeting to a user in the list" for
name in names:
msg = "Hello," + name.title () + "!"
Print (msg)
user_names = [' A John ', ' Zhao Si ', ' Wang er ']
greet_users (user_names)
----------result
:
Hello, John!
Hello, Zhao!
Hello, Wang!
1. Modify the list in the function
when you do not use a function,
**unprinted_designs = [' iphone ', ' robot ', ' cars ']
completed_models = [] While
unprinted_designs:
current_designed = Unprinted_designs.pop ();
Print ("Printing models:" + current_designed)
completed_models.append (current_designed)
print ("\nthe Following models have been printed: ") for
model in Completed_models:
print (model)
----------
* * result:**
Printing models:cars
Printing models:robot
Printing the
models:iphone Models have been printed:
cars
Robot
iphone
Next, use two functions to implement the above functionality.
The first function is used to print the data from the first list while moving the element to the second empty list. The second function is used to print the data in the empty list.
def print_models (Unprinted_designs, completed_models): While
unprinted_designs:
current_designed = Unprinted_designs.pop ()
print ("Printing models:" + current_designed)
completed_models.append (Current_ Designed
def show_comleted_models (completed_models): for
model in Completed_models:
print (model)
unprinted_designs = [' iphone ', ' robot ', ' cars ']
completed_models = []
print_models (unprinted_designs, Completed_models)
show_comleted_models (completed_models)
----------
**result**
Printing Models:cars
Printing models:robot
Printing models:iphone
cars
Robot
iphone
2. Prohibit function modification list
function (list_name[:]) to call a copy of functions