Python variables cheat sheet#
Variables#
Store data using variables. Variables may have text, integer, float, or boolean values, among others.
name = "John Doe" # string (text data)
id = 2 # integer (no decimal)
height = 5.93 # float (decimal)
study_complete = True # boolean (True or False)
print(type(name), type(id), type(height), type(study_complete)) # use type function to see data type
<class 'str'> <class 'int'> <class 'float'> <class 'bool'>
Math#
Python can handle the standard math operations.
print(3 + 5 * 4) # addition and multiplication
print((3 + 5) * 4) # grouping using parentheses
print(2 ** 2, 2 ** 3, 2 ** 4) # powers calculated using **
23
32
4 8 16
More advanced math requires importing the math module, which has useful variables and functions.
import math # import the math module for additional variables and functions
print(math.pi, math.e) # special variables in the math module
print(math.exp(2), math.cos(1)) # special math functions
3.141592653589793 2.718281828459045
7.38905609893065 0.5403023058681398
Displaying variables#
Display variables using print or by accessing a variable in the last line of a cell.
print(id) # can use print to display a variable as a string
print(height, study_complete) # print multiple variables
print(height, study_complete, sep=", ") # default separator is a space
name # last variable in a Jupyter cell is displayed even without print
2
5.93 True
5.93, True
'John Doe'
F-strings#
Use f-strings to create strings from data in variables.
print(f"Hi there, {name}.") # interpolate variables in curly braces
print(f"{id=}, {height=}") # if variable name followed by =, will show name also
print(f"sub-{id}") # default is to convert the variable to a string (id = 2, so get sub-2)
print(f"sub-{id:02d}") # optional format specifiers after : ("02d" means pad to two digits with zeros)
print(f"Height: {height:.1f} m") # ".1f" means show one decimal place
Hi there, John Doe.
id=2, height=5.93
sub-2
sub-02
Height: 5.9 m
Lists#
Store sequences using lists. Lists can hold any kind of data we want.
list_of_strings = ["a", "b", "c"] # can store strings
list_of_ints = [1, 2, 3] # can store integers
list_of_floats = [1.1, 2.2, 3.3] # can store floats
list_of_bools = [True, False, False, True] # can store booleans
mixed_list = ["a", 1, 1.1, True] # can mix different types
new_list = [3, 2, 1]
print(len(new_list)) # len function gets the length of a list
new_list.append(0) # append method adds an item to the end
print(new_list) # list is now modified
print(len(new_list)) # modified list is longer
3
[3, 2, 1, 0]
4
list1 = [1, 2]
list2 = [3, 4]
combined = list1 + list2 # concatenate lists using +
combined
[1, 2, 3, 4]
Indexing#
Use indexing to access data from part of a list. See below for a diagram of the positive and negative indices for a list.
list: [ 1, 2, 3, 4, 5 ]
positive: [ 0 1 2 3 4 ]
negative: [ -5 -4 -3 -2 -1 ]
list3 = [1, 2, 3, 4, 5]
print(list3[1]) # indexing with [] gets item at that position
print(list3[0]) # the first item is at index 0
print(list3[-1]) # negative indices count from the end
2
1
5
print(list3)
list3[2] = 7 # indexing on left, then =, then value, changes the list
print(list3) # list is now modified
list3[2] = 3 # assign back to the original value
print(list3)
[1, 2, 3, 4, 5]
[1, 2, 7, 4, 5]
[1, 2, 3, 4, 5]
Slicing#
Slicing gets part of a list and returns another list, instead of accessing just one item in the list. This diagram shows which parts of the list are accessed by different ranges of indices.
list: [ 1, 2, 3, 4, 5 ]
positive: [ 0 1 2 3 4 5 ]
negative: [-5 -4 -3 -2 -1 0 ]
print(list3[0:3]) # slicing gets part of a list; the syntax is [start:finish]
print(list3[:2]) # if start omitted, start from the first item
print(list3[3:]) # if end omitted, go until the last item
print(list3[-2:]) # use negative indices to start from the end
print(list3[::2]) # there is an optional third number, which indicates step size
[1, 2, 3]
[1, 2]
[4, 5]
[4, 5]
[1, 3, 5]
list3_copy = list3.copy() # can make a copy of a list
list3_copy[::2] = [0, 0, 0] # can assign values to slices
print(list3_copy)
[0, 2, 0, 4, 0]
Lists of lists#
list4 = [[1, 2, 3], [4, 5, 6]] # lists can hold anything, even other lists
print(list4[0]) # can index the first level like normal
print(list4[0][1]) # can chain together indices to index multiple levels
print(list4[0][1:]) # slicing works too
[1, 2, 3]
2
[2, 3]
Tuples#
Tuples are just like lists, but are immutable and cannot be changed after they are created.
tup1 = (1, 2, 3) # usually use parentheses to indicate a tuple
tup2 = 1, 2, 3 # don't actually need parentheses, though
tup3 = 1, # can have a one-item tuple, but need to have a comma after the item
print(tup1)
print(tup1[0]) # can index tuples like lists
print(tup1[:2]) # can slice tuples like lists
# tup1[0] = 4 # cannot change tuples (this code will fail)
(1, 2, 3)
1
(1, 2)
Strings#
Store text data in strings, which must be wrapped in single quotes or double quotes.
name = 'John Doe' # works
name = "John Doe" # also works
# name = John Doe # doesn't work (uncomment this line to try it)
# 'name' = 'John Doe' # also doesn't work (variable names are different from strings)
Dictionaries#
Use dictionaries, or dicts, to store data under keys. Each dict can have multiple keys, which each store a corresponding value.
age = {"John": 23, "Tracy": 27} # create a dict using {}
print(age)
print(age["Tracy"]) # use [] with a key to get the corresponding value
{'John': 23, 'Tracy': 27}
27
participants = {"study1": ["John", "Tracy"], "study2": ["Eve", "Jane"]} # can store lists as values
print(participants["study2"]) # access the list for study 2
print(participants["study2"][1]) # access the second participant of study 2
['Eve', 'Jane']
Jane
Comments#
We can use the
#sign to indicate when something should be interpreted as a comment, not code.