Python Passing a list to a function - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript Python Passing a list to a function - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Thursday, December 13, 2018

Python Passing a list to a function

Python Passing a list to a function



Passing a list to a function

You can pass a list as an argument to a function, and the function can work with the values in the list. Any changes the function makes to the list will affect the original list. You can prevent a function from modifying a list by passing a copy of the list as a argument.

#Passing a list as an argument
def greet users(names):
 """print a simple greeting to everyone ."""
 for name in names:
  msg = "Hello," + name + "!"
  print(msg)

usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)

def print_models(unprinted, printed):
 """3d print a set of models."""
 while unprinted:
  current_model = unprinted.pop()
  print("printing " + current_model)
  printed.append(current_model)

#Store some unprinted designs,
# and print each of them.
unprinted = ['phone case', 'pendant', 'ring']
printed = []
print_models(unprinted, printed)

print("\nUnprinted;", unprinted)
print("printed:", printed)

defprint_models(unprinted, printed):
 """3d print a set of models."""
 while unprinted:
  current_model = unprinted .pop()
  print("printing " + current_model
  printed.append(current_model)
# Store some unprinted designs
# and print each of them.
original =['phone case', 'pendan', 'ring']
printed = []

print_models(original[:], printed)
print("\nOriginal:", original)
print("printed:",printed)



Screenshot

list function

Passing an arbitrary number of arguments 

Sometimes you won't know how many arguments a function will need to accept. Python allows you to collect an arbitrary number of arguments
into one parameter using the operator. A parameter that accepts an arbitrary number of arguments must come last in the function definition.

The ** operator allows a parameter to collect an arbitrary number of keyword arguments.


#Collecting an arbitrary number of arguments
def make_pizza(size, *toppings):
 """Make a pizza."""
 print("\nMaking a " + size + "pizza.")
 print("Toppings:")
 for topping in toppings:
  print("-" + topping)

#Make three pizzas with different toppings.
make_pizza('small', 'pepperoni')
make_pizza('large', 'bacon bits', 'pineapple')
make_pizza('medium', 'mushroom', 'peppers', 'onions', 'extra cheese')
#Collecting a arbitrary number of keywords arguments
def build_profile(first, last, **user_info):
 """Build a user's profile dictionary."""
 # Build a dict with the required keys.
 profile = {'first': first, 'last': last}

 # Add any other keys and values.
 for key, value in user_info.items():
  profile[key] = value

 return profile

#Create two users with different kinds 
# of information.
user_0 = build _profile('albert', 'einstein', location='princeton') 
user_1 =build _profile('marie', 'curie', location='paris', field='chemistry')

print(user_0)
print(user_1)

Screenshot 

arbitary list

 

What's the best way to structure a function?

 As you can see there are many ways to write and call a function. When you're starting out, aim for something that simply works. As you gain experience you'll develop an understanding of the more subtle advantages of different structures such as positional and keywords arguments, and the various approaches to importing functions. For now if your functions do what you need them to, you're doing well.

Modules

You can store your functions in a separate file called a module, and then import the functions you need into the file containing your main program. This alows for cleaner program files. (Make sure your module is stored in the same directory as your main program.)

modules.py

#Importing an entire module
import pizza 
pizza.make_pizza('medium', 'pepperoni')
pizza.make_pizza('small', 'bacon', 'pineapple')
#Importing specific function
from pizza import make_pizza

make_pizza('medium', 'pepperoni')
make_pizza('small', 'bacon', 'pineapple')
#Giving a module an alias
import pizza as p

p.make_pizza('medium', 'pepperoni')
p.make_pizza('small', 'bacon', 'pineapple')
#Giving a function an alias
from pizza import make_pizza as mp

mp('medium', 'pepperoni')
mp('small', 'bacon', 'pineapple')
#Importing all functions from a module
from pizza import *

make_pizza('medium', 'pepperoni')
make_pizza('small', 'bacon', 'pineapple')

pizza.py

def make_pizza(size, *toppings):
 """Make a pizza."""
 print("\n Making a " + size + "pizza.")
 print("Topping:")
 for topping in toppings:
  print("-" + topping)

Screenshot 

python modules

 

No comments:

Post a Comment

Post Top Ad