Python Functions and Conditionals Cheat Sheet#
Modules#
Use the import statement to use code from modules, which have additional functions that are useful for specific purposes such as math.
import math # import Python's built-in math module
print(math.exp(2)) # use the exp function to calculate e to a power
print(math.cos(0.5)) # standard trigometric functions are available
print(math.pi) # standard constants are also available
7.38905609893065
0.8775825618903728
3.141592653589793
x = 1.2
x_ceil = math.ceil(x) # use ceil to get the ceiling, the next highest integer
x_floor = math.floor(x) # use floor to get the next lowest integer
print(x, x_ceil, x_floor)
1.2 2 1
Functions#
Use functions to carry out a set of operations on an input variable or variables. The def keyword is used to define a function.
# define a function that will take a number and double it
def double(x):
return x * 2 # use the return statement to pass an output
print(double(2)) # use our function by passing in an input
x = 3
print(double(x)) # we can also pass in a variable
y = 3
print(double(y)) # it doesn't matter what the input variable is named
z = double(4) # we can save the output in a variable
print(z)
4
6
6
8
You should usually use the return statement in your function, so there will be an output.
# if we don't have a return statement, the function will have no output
def double_no_output(x):
y = x * 2
double_no_output(2) # this runs, but is not useful
y = double_no_output(2) # this returns a special variable called None
print(y) # we didn't have a return statement, so there's no real output
None
Use docstrings to document what a function does.
def triple(x):
"""Multiply a number by three."""
return x * 3
help(triple) # displays our docstring
Help on function triple in module __main__:
triple(x)
Multiply a number by three.
Multiple inputs and outputs#
Functions often have multiple inputs, so they can take in multiple variables. They sometimes also have multiple output variables.
tup = 1, 2, 3 # we can write a series of values in a tuple
print(max(1, 2, 3)) # use this same syntax to pass multiple values to a function
a = 1
b = 2
c = 3
print(max(a, b, c)) # can pass in variables also, using the same syntax
3
3
Python has a special syntax called tuple unpacking, which allows a tuple to be unpacked into multiple variables.
tup = 1, 2, 3 # create a tuple with three values
a, b, c = tup # unpack the tuple into three variables
print(a, b, c)
1 2 3
Tuple unpacking allows multiple outputs from a function to be placed in different variables.
outputs = divmod(5, 2) # get outputs in one tuple
print(outputs)
quotient, remainder = divmod(5, 2) # get two outputs in separate variables
print(quotient, remainder)
(2, 1)
2 1
To write a function with multiple inputs, include them all in between the parentheses in the function definition line. To have multiple outputs, give the return statement a tuple of multiple values.
def double_double(x, y): # both x and y are inputs to the function
return x * 2, y * 2 # the return statement has a tuple of values to output
a, b = double_double(2, 4)
print(a, b)
4 8
Function arguments#
There are two types of arguments to functions: positional arguments, which are defined based on the order of the inputs; and keyword arguments, which have names attached to them.
Arguments to a function may include positional arguments, keyword arguments, or a mix of the two. Keyword arguments must come after positional arguments.
def positional_only(pos1, pos2):
"""Take in two position arguments."""
pass # using pass here as a placeholder for the function code
def keyword_only(kw1="a default value", kw2="another default", kw3=3):
"""Take in three keyword arguments with default values."""
pass
def position_and_keyword(pos1, pos2, kw1=1, kw2=2):
"""Take in two position arguments and two keyword arguments."""
pass
Use keyword arguments when there is some value that usually makes sense, but sometimes you might want to change, depending on the situation when you are calling the function.
def greet_user(name, time="morning", location="Milwaukee"):
print(f"Hello, {name}. It is {time} in {location}.")
greet_user("Sam") # if you don't specify time and location, get the default
greet_user("Sam", "evening") # can change the time with a second argument
greet_user("Sam", time="afternoon") # can also set using a keyword
greet_user("Tim", location="New York") # with keywords, can go out of order
greet_user("Tim", time="afternoon", location="New York") # may specify explicitly
greet_user("Tim", "afternoon", "New York") # may also specify by position
Hello, Sam. It is morning in Milwaukee.
Hello, Sam. It is evening in Milwaukee.
Hello, Sam. It is afternoon in Milwaukee.
Hello, Tim. It is morning in New York.
Hello, Tim. It is afternoon in New York.
Hello, Tim. It is afternoon in New York.
Use help to get information about all of a function’s arguments. Any optional keyword arguments will be shown with their default values.
help(print)
Help on built-in function print in module builtins:
print(*args, sep=' ', end='\n', file=None, flush=False)
Prints the values to a stream, or to sys.stdout by default.
sep
string inserted between values, default a space.
end
string appended after the last value, default a newline.
file
a file-like object (stream); defaults to the current sys.stdout.
flush
whether to forcibly flush the stream.
If statements#
Use if statements to specify code that should only run when some condition is met.
positive = [] # this list will hold only positive numbers
a = 2
if a > 0: # check if a is greater than zero (True)
positive.append(a) # this code runs
b = -2
if b > 0: # check if b is greater than zero (False)
positive.append(b) # this code is skipped
print(positive) # only a is included in the list
[2]
If/elif/else statements#
To handle more complicated situations, combine an if statement with additional checks using optional elif statements and an optional else statement.
positive = [] # this list will hold positive numbers
negative = [] # this list will hold negative numbers
zero = [] # this list will hold zeros
c = -3
if c > 0: # check if c is greater than zero (False)
positive.append(c)
elif c < 0: # check if c is less than zero (True)
negative.append(c)
else: # run this code if all previous checks were False
zero.append(c)
print(positive, negative, zero)
[] [-3] []
Conditionals#
When we use if/elif/else statements, can we use various conditional statements to test different conditions.
Use comparison operators (==, !=, <, >, <=, >=) to compare numbers.
a = 1
print(a == 1) # True if a equals 1
print(a != 1) # True if a does not equal 1
print(a < 1) # True if a is less than 1
print(a <= 1) # True if a is less than or equal to 1
print(a > 1) # True if a is greater than 1
print(a >= 1) # True if a is greater than or equal to 1
True
False
False
True
False
True
Use the equal (==) and not equal (!=) operators to compare strings.
s = "hello"
print(s == "hello") # True if s equals "hello"
print(s == "hi") # True if s equals "hi"
print(s != "hello") # True if s does not equal "hello"
print(s != "hi") # True is s does not equal "hi"
True
False
False
True
Use the is operator to test if a variable has the special value None.
v = None # sometimes, a variable will be set to None to indicate it is undefined
print(v is None) # check if v is None
v = 1 # now v is set to a specific value, which is not None
print(v is not None) # check if v is not None
True
True
Test more complicated conditions using the and, or, and not keywords.
n = 5
print(n < 10 and n > 0) # True if n is less than 10 and greater than 0
print(n < 10 or n > 20) # True if n is less than 10 or greater than 20
print(not n < 10) # False if n is less than 10
True
True
False