Python Cheat-Sheet

Intro Happy revenge of the fifth! This week, I've been working with Python as I learn more about Machine Learning. I thought it'd be a good idea to put together a cheat-sheet that summarizes some of the things I've learned so far. This is a work in progress, and I will be adding more to it as I learn more. Basics Comments, variable assignment, adding, conditionals and printing. rarecandy_count = 0 print(rarecandy_count) # Found 4 more Rare Candy while exploring Route 119 rarecandy_count = rarecandy_count + 4 if rarecandy_count > 0: print("Sweet! Time to grind some levels.") battle_cry = "Pika! " * rarecandy_count print(battle_cry) Output: 0 Sweet! Time to grind some levels. Pika! Pika! Pika! Pika! Arithmetic in Python Python follows PEMDAS (Parentheses, Exponents, Multiplication and Division, Addition and Subtraction) order of operations. Operator Name Description a + b Addition Sum of a and b a - b Subtraction Difference of a and b a * b Multiplication Product of a and b a / b True division Quotient of a and b a // b Floor division Quotient of a and b, removing fractional parts a % b Modulus Integer remainder after division of a by b a ** b Exponentiation a raised to the power of b -a Negation The negative of a Easily call mathematical functions. min(12, 25, 7) # 7 max(31, 4, 18) # 31 abs(-42) # 42 float(10) # 10.0 int("256") # 256 Note: float and int are functions that convert values to float and int respectively. Functions help The help() function is used to display the documentation of a function or module. It provides information about the function's parameters, return values, and usage examples. help(round) help displays two things: The header of the function round(number, ndigits=None) A brief description of what the function does Defining Functions Functions are defined using the def keyword, followed by the function name and parentheses. The function body is everything indented after the : and contains the code that will be executed when the function is called. return is another keyword uniquely associated with functions. When a return statement is used, it exits the function immediately, and passes the value on the right hand side to the calling context. def least_difference(a, b, c): diff1 = abs(a - b) diff2 = abs(b - c) diff3 = abs(a - c) return min(diff1, diff2, diff3) Docstrings Docstrings are a way to document functions in Python. They are written as a string immediately after the function definition and can be accessed using the __doc__ attribute of the function. def least_difference(a, b, c): """Return the smallest difference among a, b and c. >>> least_difference(33, 45, 29) 4 """ diff1 = abs(a - b) diff2 = abs(b - c) diff3 = abs(a - c) return min(diff1, diff2, diff3) Now when help is called using the above function, it will display the docstring as well. None None is a special value in Python that represents the absence of a value or a null value. It is often used as a default return value for functions that do not explicitly return a value. Default Arguments Default arguments are values that are assigned to function parameters if no value is provided when the function is called. They are defined in the function signature by assigning a value to the parameter. def print_hello(name="World"): print("Hello, " + name + "!") print_hello() # Hello, World! Booleans and Conditionals Operation Descriptions a == b a equal to b a < b a less than b a b a greater than b a >= b a greater than or equal to b 3.0 == 3 => True, '3' == 3 => False And, Or, Or Not and, or, and not are logical operators in Python. They are used to combine or negate boolean expressions. a = True b = False print(a and b) # False print(a or b) # True print(not a) # False If Statements Python uses if, elif and else statements. Note: Python uses indentation to define blocks of code. Make sure to use consistent indentation (spaces or tabs) throughout your code. def inspect(x): if x == 0: print(x, "is zero") elif x > 0: print(x, "is positive") elif x 0: print("Taking damage!") hp -= 5 list comprehension is a concise way to create lists in Python. It allows you to create a new list by applying an expression to each item in an existing list. squares = [x**2 for x in range(10)] print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] another example using the pokemon list: loud_pokemon = [poke.upper() + '!' for poke in pokemon if len(poke)

May 5, 2025 - 16:06
 0
Python Cheat-Sheet

Intro

Happy revenge of the fifth! This week, I've been working with Python as I learn more about Machine Learning. I thought it'd be a good idea to put together a cheat-sheet that summarizes some of the things I've learned so far. This is a work in progress, and I will be adding more to it as I learn more.

Basics

Comments, variable assignment, adding, conditionals and printing.

rarecandy_count = 0
print(rarecandy_count)

# Found 4 more Rare Candy while exploring Route 119
rarecandy_count = rarecandy_count + 4

if rarecandy_count > 0:
    print("Sweet! Time to grind some levels.")

battle_cry = "Pika! " * rarecandy_count
print(battle_cry)

Output:

0
Sweet! Time to grind some levels.
Pika! Pika! Pika! Pika!

Arithmetic in Python

Python follows PEMDAS (Parentheses, Exponents, Multiplication and Division, Addition and Subtraction) order of operations.

Operator Name Description
a + b Addition Sum of a and b
a - b Subtraction Difference of a and b
a * b Multiplication Product of a and b
a / b True division Quotient of a and b
a // b Floor division Quotient of a and b, removing fractional parts
a % b Modulus Integer remainder after division of a by b
a ** b Exponentiation a raised to the power of b
-a Negation The negative of a

Easily call mathematical functions.

min(12, 25, 7)     # 7
max(31, 4, 18)     # 31
abs(-42)           # 42
float(10)          # 10.0
int("256")         # 256

Note: float and int are functions that convert values to float and int respectively.

Functions

help

The help() function is used to display the documentation of a function or module. It provides information about the function's parameters, return values, and usage examples.

help(round)

help displays two things:

  • The header of the function round(number, ndigits=None)
  • A brief description of what the function does

Defining Functions

Functions are defined using the def keyword, followed by the function name and parentheses. The function body is everything indented after the : and contains the code that will be executed when the function is called.

return is another keyword uniquely associated with functions. When a return statement is used, it exits the function immediately, and passes the value on the right hand side to the calling context.

def least_difference(a, b, c):
    diff1 = abs(a - b)
    diff2 = abs(b - c)
    diff3 = abs(a - c)
    return min(diff1, diff2, diff3)

Docstrings

Docstrings are a way to document functions in Python. They are written as a string immediately after the function definition and can be accessed using the __doc__ attribute of the function.

def least_difference(a, b, c):
    """Return the smallest difference among a, b and c.

    >>> least_difference(33, 45, 29)
    4
    """
    diff1 = abs(a - b)
    diff2 = abs(b - c)
    diff3 = abs(a - c)
    return min(diff1, diff2, diff3)

Now when help is called using the above function, it will display the docstring as well.

None

None is a special value in Python that represents the absence of a value or a null value. It is often used as a default return value for functions that do not explicitly return a value.

Default Arguments

Default arguments are values that are assigned to function parameters if no value is provided when the function is called. They are defined in the function signature by assigning a value to the parameter.

def print_hello(name="World"):
    print("Hello, " + name + "!")

print_hello() # Hello, World!

Booleans and Conditionals

Operation Descriptions
a == b a equal to b
a < b a less than b
a <= b a less than or equal to b
a != b a not equal to b
a > b a greater than b
a >= b a greater than or equal to b

3.0 == 3 => True, '3' == 3 => False

And, Or, Or Not

and, or, and not are logical operators in Python. They are used to combine or negate boolean expressions.

a = True
b = False
print(a and b) # False
print(a or b) # True
print(not a) # False

If Statements

Python uses if, elif and else statements.

Note: Python uses indentation to define blocks of code. Make sure to use consistent indentation (spaces or tabs) throughout your code.

def inspect(x):
    if x == 0:
        print(x, "is zero")
    elif x > 0:
        print(x, "is positive")
    elif x < 0:
        print(x, "is negative")
    else:
        print(x, "is... something else")

Similar to int() and float(), you can use bool() to convert values to boolean. Additionally, python will implicitly convert values to boolean in a conditional statement.

You can also use if statements in a single line.

print("Shiny!") if is_shiny else print("Regular.")

Python will implicitly add together booleans as integers without any issues.

print(True + True) # 2
print(True + False) # 1
print(False + False) # 0

caught = True + False + True # 2

Lists

Lists are ordered collections of items. They can contain any type of data, including other lists. Lists are defined using square brackets [] and can be indexed using zero-based indexing.

pokemon = [
    "Chikorita", "Cyndaquil", "Totodile", # Johto starters
    "Treecko", "Torchic", "Mudkip", # Hoenn starters
    "Gardevoir", "Metagross" # Fan-faves
]

pokemon[0] # 'Chikorita'
pokemon[-1] # 'Metagross'
pokemon[2:5] # ['Totodile', 'Treecko', 'Torchic']

Lists are mutable, meaning you can change their contents after they are created. You can add, remove, or modify items in a list.

pokemon[0] = "Bayleef" # Chikorita evolved

Slicing

Python can slice lists using the : operator. The first number is the starting index, and the second number is the ending index (exclusive). You can also use negative indices to count from the end of the list.

# Grab the first three pokemon
pokemon[0:3] # ['Chikorita', 'Cyndaquil', 'Totodile']
# Grab the full list starting at index 3
pokemon[3:] # ['Treecko', 'Torchic', 'Mudkip', 'Gardevoir', 'Metagross']
# Grab the full list up to index 3
pokemon[:3] # ['Chikorita', 'Cyndaquil', 'Totodile']
# Grab the full list except for the first and last pokemon
pokemon[1:-1] # ['Cyndaquil', 'Totodile', 'Treecko', 'Torchic', 'Mudkip', 'Gardevoir']
# Grab the last 3 items
pokemon[-3:] # ['Mudkip', 'Gardevoir', 'Metagross']

List Functions

  • len() - Returns the length of a list.
  • sorted() - Returns a sorted copy of a list. (strs are sorted alphabetically)
  • sum() - Returns the sum of all items in a list.
  • min() - Returns the smallest item in a list.
  • max() - Returns the largest item in a list.

List Methods

  • append() - Adds an item to the end of a list.
  • pop() - Removes and returns the last item from a list.
  • index() - Returns the index of the first occurrence of an item in a list.
  • clear() - Removes all items from a list.
  • insert() - Inserts an item at a specified index in a list.
  • remove() - Removes the first occurrence of an item from a list.
  • copy() - Returns a shallow copy of a list.

To determine if an item is in a list, you can use the in operator.

"Mudkip" in pokemon # True

Tuples

Tuples are very similar to Lists, but they differ in a few key ways:

  • Tuples are immutable, meaning you cannot change their contents after they are created.
  • Tuples are defined using parentheses () instead of square brackets [].
legendary_pair = ("Latios", "Latias")
legendary_pair = "latios", "latias" # Same thing

Objects

Similar to JavaScript, everything in Python is an object. This includes functions, classes, and modules. You can use the type() function to check the type of an object.

A function attached to an object is called a method

Loops

The for in loop is used to iterate over a sequence (like a list or string) and execute a block of code for each item in the sequence. We can use this to iterate over lists, tuples, strings, and dictionaries.

for poke in pokemon:
    print(f"{poke} used TACKLE!")

range() is a built-in function that generates a sequence of numbers. It can be used in for loops to iterate over a range of numbers, or to do something a specific number of times.

for i in range(3):
    print("Battle", i)

A while loop is used to execute a block of code as long as a condition is true. It is often used when the number of iterations is not known in advance.

hp = 20
while hp > 0:
    print("Taking damage!")
    hp -= 5

list comprehension is a concise way to create lists in Python. It allows you to create a new list by applying an expression to each item in an existing list.

squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

another example using the pokemon list:

loud_pokemon = [poke.upper() + '!' for poke in pokemon if len(poke) < 8]
loud_pokemon
# ['TREECKO!', 'TORCHIC!', 'MUDKIP!']

Note: A helpful trick to wrap your head around list comprehensions is to think of SQL SELECT, FROM, WHERE.

[
  poke.upper() + '!' # SELECT
  for poke in pokemon # FROM
  if len(poke) < 6 # WHERE
]

Strings

You can use triple quotes to create multi-line strings. Triple quotes can also be used to create docstrings.

"""Prepare for trouble,
and make it double!"""

String Methods

  • upper() - Converts a string to uppercase.
  • lower() - Converts a string to lowercase.
  • startswith() - Checks if a string starts with a specified substring.
  • endswith() - Checks if a string ends with a specified substring.
  • split() - Splits a string into a list of substrings based on a specified delimiter.
  • join() - Joins a list of strings into a single string using a specified delimiter.

format is a method that allows you to format strings by replacing placeholders with values. It is similar to string interpolation in other languages.

trainer = "May"
badges = 8
progress = "{} collected {} badges!".format(trainer, badges)
print(progress) # May collected 8 badges!

Additionally, you can use f-strings (formatted string literals) to format strings in Python 3.6 and later. F-strings are prefixed with f and allow you to embed expressions inside curly braces {}.

# Using the values from above
print(f"{trainer} collected {badges} badges!")  # May collected 8 badges!

Dictionaries

Dictionaries are unordered collections of key-value pairs. They are defined using curly braces {} and can be indexed using keys.

types = {
    "Chikorita": "Grass",
    "Cyndaquil": "Fire",
    "Totodile":  "Water",
    "Treecko":   "Grass",
    "Torchic":   "Fire",
    "Mudkip":    "Water",
    "Gardevoir": "Psychic",
    "Metagross": "Steel"
}

types["Totodile"]  # 'Water'

initials = {name: name[0] for name in types}
# {'Chikorita': 'C', 'Cyndaquil': 'C', ...}

Note: The in operator can be used to check if a key exists in a dictionary.

"Umbreon" in types # False

A for loop can be used to iterate over the keys in a dictionary.

for poke in pokemon:
    print(poke)

Dictionary Methods

  • keys() - Returns a list of keys in a dictionary.
  • values() - Returns a list of values in a dictionary.
  • items() - Returns a list of key-value pairs in a dictionary.
for name, poke_type in types.items():
    print(f"{name:>10}{poke_type}")