0% found this document useful (0 votes)
8 views

Beginners Python Cheat Sheet PCC Functions BW

Uploaded by

amkslade101
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Beginners Python Cheat Sheet PCC Functions BW

Uploaded by

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

Beginner's Python

Positional and keyword arguments Return values


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

Cheat Sheet - 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
a variable which the return value can be assigned to. A
function stops running when it reaches a return statement.
Returning a single value

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

You might also like