0% found this document useful (0 votes)
137 views2 pages

Python Crash Course: A Hands-On, Project-Based Introduction To Programming

This document provides a summary of key concepts about functions in Python including: 1) Functions allow you to write reusable code and take in arguments to operate on. They can return values. 2) There are two types of arguments - positional which are matched by order, and keyword which are matched by name. Default values can also be used. 3) Functions can return single values, dictionaries, or other objects. Optional arguments allow omitting values.

Uploaded by

ROBERTO CUJIA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
137 views2 pages

Python Crash Course: A Hands-On, Project-Based Introduction To Programming

This document provides a summary of key concepts about functions in Python including: 1) Functions allow you to write reusable code and take in arguments to operate on. They can return values. 2) There are two types of arguments - positional which are matched by order, and keyword which are matched by name. Default values can also be used. 3) Functions can return single values, dictionaries, or other objects. Optional arguments allow omitting values.

Uploaded by

ROBERTO CUJIA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 2

Beginner's Python

Positional and keyword arguments Return values


The two main kinds of arguments are positional and A function can return a value or a set of values. When a
keyword arguments. When you use positional arguments function returns a value, the calling line should provide a

Cheat Sheet – Python matches the first argument in the function call with
the first parameter in the function definition, and so forth.
With keyword arguments, you specify which parameter
variable which the return value can be assigned to. A
function stops running when it reaches a return statement.

Functions each argument should be assigned to in the function call. Returning a single value
When you use keyword arguments, the order of the def get_full_name(first, last):
arguments doesn't matter. """Return a neatly formatted full name."""
Using positional arguments full_name = f"{first} {last}"
return full_name.title()
What are functions? def describe_pet(animal, name):
Functions are named blocks of code designed to do """Display information about a pet.""" musician = get_full_name('jimi', 'hendrix')
print(f"\nI have a {animal}.") print(musician)
one specific job. Functions allow you to write code
print(f"Its name is {name}.")
once that can then be run whenever you need to Returning a dictionary
accomplish the same task. Functions can take in the describe_pet('hamster', 'harry') def build_person(first, last):
information they need, and return the information they describe_pet('dog', 'willie') """Return a dictionary of information
generate. Using functions effectively makes your about a person.
programs easier to write, read, test, and fix. Using keyword arguments
"""
def describe_pet(animal, name): person = {'first': first, 'last': last}
Defining a function """Display information about a pet.""" return person
The first line of a function is its definition, marked by the print(f"\nI have a {animal}.")
keyword def. The name of the function is followed by a set print(f"Its name is {name}.") musician = build_person('jimi', 'hendrix')
of parentheses and a colon. A docstring, in triple quotes, print(musician)
describes what the function does. The body of a function is describe_pet(animal='hamster', name='harry')
describe_pet(name='willie', animal='dog') Returning a dictionary with optional values
indented one level.
To call a function, give the name of the function followed def build_person(first, last, age=None):
by a set of parentheses. Default values """Return a dictionary of information
about a person.
Making a function You can provide a default value for a parameter. When
function calls omit this argument the default value will be """
def greet_user(): used. Parameters with default values must be listed after person = {'first': first, 'last': last}
"""Display a simple greeting.""" parameters without default values in the function's definition if age:
print("Hello!") so positional arguments can still work correctly. person['age'] = age
return person
greet_user() Using a default value
musician = build_person('jimi', 'hendrix', 27)
def describe_pet(name, animal='dog'):
print(musician)
Passing information to a function """Display information about a pet."""
Information that's passed to a function is called an print(f"\nI have a {animal}.")
musician = build_person('janis', 'joplin')
argument; information that's received by a function is called print(f"Its name is {name}.")
print(musician)
a parameter. Arguments are included in parentheses after
the function's name, and parameters are listed in describe_pet('harry', 'hamster')
parentheses in the function's definition. describe_pet('willie') Visualizing functions
Try running some of these examples on pythontutor.com.
Passing a single argument Using None to make an argument optional
def greet_user(username): def describe_pet(animal, name=None):
"""Display a simple greeting."""
print(f"Hello, {username}!")
"""Display information about a pet."""
print(f"\nI have a {animal}.")
Python Crash Course
if name: A Hands-On, Project-Based
greet_user('jesse') print(f"Its name is {name}.") Introduction to Programming
greet_user('diana')
greet_user('brandon') describe_pet('hamster', 'harry')
nostarch.com/pythoncrashcourse2e
describe_pet('snake')
Passing a list to a function Passing an arbitrary number of arguments Modules
You can pass a list as an argument to a function, and the Sometimes you won't know how many arguments a You can store your functions in a separate file called a
function can work with the values in the list. Any changes function will need to accept. Python allows you to collect an module, and then import the functions you need into the file
the function makes to the list will affect the original list. You arbitrary number of arguments into one parameter using the containing your main program. This allows for cleaner
can prevent a function from modifying a list by passing a * operator. A parameter that accepts an arbitrary number of program files. (Make sure your module is stored in the
copy of the list as an argument. arguments must come last in the function definition. same directory as your main program.)
The ** operator allows a parameter to collect an arbitrary
Passing a list as an argument number of keyword arguments. These arguments are Storing a function in a module
File: pizza.py
def greet_users(names): stored as a dictionary with the parameter names as keys,
"""Print a simple greeting to everyone.""" and the arguments as values. def make_pizza(size, *toppings):
for name in names: """Make a pizza."""
Collecting an arbitrary number of arguments print(f"\nMaking a {size} pizza.")
msg = f"Hello, {name}!"
print(msg) def make_pizza(size, *toppings): print("Toppings:")
"""Make a pizza.""" for topping in toppings:
usernames = ['hannah', 'ty', 'margot'] print(f"\nMaking a {size} pizza.") print(f"- {topping}")
greet_users(usernames) print("Toppings:")
for topping in toppings: Importing an entire module
Allowing a function to modify a list File: making_pizzas.py
print(f"- {topping}") Every function in the module is available in the program file.
The following example sends a list of models to a function for
printing. The original list is emptied, and the second list is filled. import pizza
# Make three pizzas with different toppings.
def print_models(unprinted, printed): make_pizza('small', 'pepperoni')
"""3d print a set of models.""" make_pizza('large', 'bacon bits', 'pineapple') pizza.make_pizza('medium', 'pepperoni')
while unprinted: make_pizza('medium', 'mushrooms', 'peppers', pizza.make_pizza('small', 'bacon', 'pineapple')
current_model = unprinted.pop() 'onions', 'extra cheese')
Importing a specific function
print(f"Printing {current_model}")
Collecting an arbitrary number of keyword arguments Only the imported functions are available in the program file.
printed.append(current_model)
def build_profile(first, last, **user_info): from pizza import make_pizza
# Store some unprinted designs, """Build a dictionary for a user."""
# and print each of them. user_info['first'] = first make_pizza('medium', 'pepperoni')
unprinted = ['phone case', 'pendant', 'ring'] user_info['last'] = last make_pizza('small', 'bacon', 'pineapple')
printed = []
print_models(unprinted, printed) Giving a module an alias
return user_info
import pizza as p
print(f"\nUnprinted: {unprinted}") # Create two users with different kinds
print(f"Printed: {printed}") # of information. p.make_pizza('medium', 'pepperoni')
user_0 = build_profile('albert', 'einstein', p.make_pizza('small', 'bacon', 'pineapple')
Preventing a function from modifying a list
The following example is the same as the previous one, except the
location='princeton')
Giving a function an alias
original list is unchanged after calling print_models().
user_1 = build_profile('marie', 'curie', from pizza import make_pizza as mp
def print_models(unprinted, printed): location='paris', field='chemistry')
"""3d print a set of models.""" mp('medium', 'pepperoni')
while unprinted: print(user_0) mp('small', 'bacon', 'pineapple')
current_model = unprinted.pop() print(user_1)
print(f"Printing {current_model}") Importing all functions from a module
printed.append(current_model) Don't do this, but recognize it when you see it in others' code. It
can result in naming conflicts, which can cause errors.
# Store some unprinted designs,
What's the best way to structure a function?
from pizza import *
# and print each of them. As you can see there are many ways to write and call a
original = ['phone case', 'pendant', 'ring'] function. When you're starting out, aim for something that
make_pizza('medium', 'pepperoni')
printed = [] simply works. As you gain experience you'll develop an
understanding of the more subtle advantages of different make_pizza('small', 'bacon', 'pineapple')
print_models(original[:], printed) structures such as positional and keyword arguments, and
print(f"\nOriginal: {original}") the various approaches to importing functions. For now if More cheat sheets available at
print(f"Printed: {printed}") your functions do what you need them to, you're doing well.
ehmatthes.github.io/pcc_2e/

You might also like