Python Cheat Sheet

From swissChili
Jump to navigation Jump to search

Basic syntax[edit | edit source]

Literal values[edit | edit source]

# This is a comment
"this is a string"
'so is this'
# This is a number
1234
# These are booleans
True
False

Variable assignment[edit | edit source]

# No need to declare a variable before assigning to it
variable = value
# You can set the value at some index in a list as well
some_list[2] = value
# You can extract several items from a list at once
(first, second, third) = [1, 2, 3]

Arithmetic & logic[edit | edit source]

# Order of operations applies
1 + 2 / 6 + 3  # 4.3333
True and True  # True
True or False  # True
not False      # True
3 == "3"       # False
4 != 4.1       # True

Control flow[edit | edit source]

Conditions[edit | edit source]

if name == "Jim":
    print("Hi Jim")
elif name == "Todd":
    print("go away todd")
else:
    print("do I know you?")

Loops[edit | edit source]

for number in [3, 5, 6, 32]:
   print(number)
for number in range(1, 5):
   print(number) # 1...4
number = 0

while number < 10:
   number += 1
   print(number)

range() is a function you will be using a lot. It returns a list of numbers in a range. range(a, b) returns [a, b) in math terms, ie a is included but b is not.

In python, most functions dealing with ranges, slices, etc, are not inclusive – meaning they don’t include the last number.

range() also has an optional third argument which is the step to count by. If you want to count from 1 to 10 by 2, you can do range(1, 10, 2).

Functions[edit | edit source]

Why? Functions let us do a few things:

  1. Logically separate things into independent units
  2. Avoid repeating ourselves

When beginning programming it may be tempting to dump everything in the top-level of your code and avoid functions, but don’t do this! Functions make your code easier to read and understand, easier to debug, and easier to write. Your functions should logically do one task an operate only on the data passed in as arguments.

When in doubt, break your task into small parts that can each be a self contained function.

Defining functions[edit | edit source]

# a, b, and c are the "formal parameters" of the function
# whatever you pass in the first position will be called "a" within the
# body of the function. 2nd will be b, 3rd c, etc

def my_function(a, b, c):
   return a + b * c

Calling functions[edit | edit source]

my_function(3, 6, 12)
my_function(input("number"), 4, 6)
print(my_function(3, 2, 1/53))

Lists[edit | edit source]

Creating lists[edit | edit source]

You can put anything inside a list, including other lists

colors = ["red", "green", "blue"]
stuff = [32, 4, "hi", colors]
joined = [1, 2, 3] + [4, 5, 6]

Lists that contain other lists are called 2D lists. You use them as shown:

some_2d_list = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
some_2d_list[1][2]  # 6

Accessing parts of lists[edit | edit source]

first_color = colors[0]
last_color = colors[-1]
middle = stuff[1:3] # [4, "hi"]
last2 = stuff[-2:]  # ["hi", [...]]
first2 = stuff[:2]  # [32, 4]

The list[start:end] syntax is called a slice or a range. As is customary in python, the end index is not included, so 1:3 would give indices 1 and 2 but not 3.

Modifying lists[edit | edit source]

Lists are mutable, meaning you can change what’s in them.

# Append a single item onto a list
colors.append("yellow")
# Join two lists together with +
colors += ["indigo", "violet"]
# Remove an item from a list
colors.remove("green")

Dictionaries[edit | edit source]

Creating dictionaries[edit | edit source]

ages = {"joe": 17, "tim": 21}

The string on the left of the : is called the key, whatever is on the right is the corresponding value. Dictionaries associate a value (“definition”) with a certain string (“key”). The definition can be any value: a number, string, another dictionary, some other data structure – anything.

Looking things up in a dictionary[edit | edit source]

joes_age = ages["joe"]
print(ages[input("name")])

Check if there is a value associated with the key "joe"

"joe" in ages   # True

Modifying a dictionary[edit | edit source]

ages["jane"] = 24
del ages["joe"]
ages["joe"]    # KeyError: 'joe'

Libraries[edit | edit source]