My Python Cheat Sheet (from 'Introduction to Python')

Collected information from Jetbrains PyCharm Edu Course: https://www.jetbrains.com/pycharm-edu/learners/

Hello World

print("Hello World")

Comments

# starts a comment for the whole line

# This line is a comment

Variables

Definition

a = 2
b = "Hello"

Convert a variable to a string

str() is used to convert a variable to a string.

theAnswer = 42
print("The answer to all things: " + str(a))

Number types

int_number = 42
print(type(int_number))   # print type of variable "number": <class 'int'>

float_number = 42.42
print(type(float_number)) # print type of variable "number": <class 'float'>

Type conversions

str(x)    # to string
int(x)    # to integer
float(x)  # to float

Special Operators

result = 2 ** 8  # 2^8 -> power operator
# result is now 256

Boolean Type

Booleans can only be True or False. To compare the equality of to variables, use the == operator.

Strings

String Concatenation

The string concatenation operator in Python is the + symbol.

hello = "Hello"
world = 'World'
hello_world = hello + ' ' + world
print(hello_world)

String Multiplication

hello = "hello"
ten_hellos = hello * 10
print(ten_hellos)

Prints out: hellohellohellohellohellohellohellohellohellohello

String Index

long_string = "This is a very long string!"
begin_of_string = long_string[0]
end_of_string = long_string[-1]
print(begin_of_string)
print(end_of_string)

Prints:

T
!

String Slicing (Substring)

str[start:end] # items start through end-1
str[start:]    # items start through the rest of the array
str[:end]      # items from the beginning through end-1
str[:]         # a copy of the whole array

Check if String contains Substring

Use the in keyword.

ice_cream = "ice cream"
print("cream" in ice_cream)    # prints: True

Multiline Strings

Strings can span multiple lines, if you enclose them in triple quotes.

phrase = """
It is a really long string
triple-quoted strings are used
to define multi-line strings
"""
first_half = phrase[:int(len(phrase)/2)]
print(first_half)

Lower-/Upper-Case Strings

„A String“.upper() # -> A STRING
„A String“.lower() # -> a string

String formatting

name = "John"
print("Hello, PyCharm! My name is %s!" % name)     # Note: %s is inside the string, % is after the string
years = 42
print("I'm %d years old" % years)

Lists

A single List in python can hold different types (… just think twice before you do it :)

multiple_types = ["A String", 42]

Lists can be indexed and sliced:

squares = [1, 4, 9, 16, 25]   # create new list
print(squares)
print(squares[1:4])

# Prints out:
# [1, 4, 9, 16, 25]
# [4, 9, 16]

List Operations

animals = ['elephant', 'lion', 'tiger', "giraffe"]  # create new list
print(animals)

animals += ["monkey", 'dog']    # add two items to the list
print(animals)

animals.append("dino")   # add one more item to the list using append() method
print(animals)

animals[6] = "dinosaur"  # Replace 'dino' with 'dinosaur'
print(animals)

Output:

['elephant', 'lion', 'tiger', 'giraffe']
['elephant', 'lion', 'tiger', 'giraffe', 'monkey', 'dog']
['elephant', 'lion', 'tiger', 'giraffe', 'monkey', 'dog', 'dino']
['elephant', 'lion', 'tiger', 'giraffe', 'monkey', 'dog', 'dinosaur']

Removing list elements

animals = ['elephant', 'lion', 'tiger', "giraffe", "monkey", 'dog']   # create new list
print(animals)

animals[1:3] = ['cat']    # replace 2 items -- 'lion' and 'tiger' with one item -- 'cat'
print(animals)

animals[1:3] = []     # remove 2 items -- 'cat' and 'giraffe' from the list
print(animals)

animals = []   # assign an empty list
print(animals)

Output:

['elephant', 'lion', 'tiger', 'giraffe', 'monkey', 'dog']
['elephant', 'cat', 'giraffe', 'monkey', 'dog']
['elephant', 'monkey', 'dog']
[]

Tuples

Tuples are like Lists, that can not be changed. You can’t add, change or delete elements from a Tuple. Tuples are comma separated and enclosed in parentheses (a, b, c). Single item tuples must end with a trailing comma (a,).

Dictionaries

Dictionaries are key/value pairs. Dictionaries are enclosed in curly braces. The keys are separated from the values with a colon. And the key/value pairs are separated with commas.

# create new dictionary.
phone_book = {"John": 123, "Jane": 234, "Jerard": 345}    # "John", "Jane" and "Jerard" are keys and numbers are values
print(phone_book)

# Add new item to the dictionary
phone_book["Jill"] = 345
print(phone_book)

# Remove key-value pair from phone_book
del phone_book['John']
print(phone_book)

# Print Jane's phone number
print(phone_book["Jane"])

# Print all keys
print(phone_book.keys())

# Print all values
print(phone_book.values())

Output:

{'John': 123, 'Jane': 234, 'Jerard': 345}
{'John': 123, 'Jane': 234, 'Jerard': 345, 'Jill': 345}
{'Jane': 234, 'Jerard': 345, 'Jill': 345}
234
dict_keys(['Jane', 'Jerard', 'Jill'])
dict_values([234, 345, 345])

Check if a Dictionary contains a Key

grocery_dict = {"fish": 1, "tomato": 6, 'apples': 3}   # create new dictionary

# Is 'fish' in grocery_dict
print('fish' in grocery_dict)  # prints: True

Conditional Expressions

Boolean operators

The boolean operators are and, or, not.

name = "John"
age = 17

# checks that either name equals to "John" OR age equals to 17
print(name == "John" or age == 17)    

# Check if name is equal to "John" and he is not 23 years old. 
print(name == "John" and not age == 23)

Output:

True
True

Boolean Operator Order

The order of evaluation is: not -> and -> or

if Statement

Note: Indention marks ‘code blocks’.

x = 42

if x < 0:
    print('x < 0')        # executes only if x < 0
elif x == 0:
    print('x is zero')    # if it's not true that x < 0, check if x == 0
elif x == 1:
    print('x == 1')       # if it's not true that x < 0 and x != 0, check if x == 1
else:
    print('non of the above is true‘)

Output:

non of the above is true

for Loop

for i in range(5):    # for each number i in range 0-4. range(5) function returns list [0, 1, 2, 3, 4]
    print(i)          # this line is executed 5 times. First time i equals 0, then 1, ...

# 0
# 1
# 2
# 3
# 4

primes = [2, 3, 5, 7]
for prime in primes:
    print(prime)

# 2
# 3
# 5
# 7

for Loop with String

hello_world = "Hello World!"

for ch in hello_world:    # print each character from hello_world
    print(ch)

# H
# e
# l
# l
# o
#  
# W
# o
# r
# l
# d
# !

while Loop

Print all squares from 1 to 9 (1, 4, …, 81)

square = 0
number = 1

while number < 10:
    square = number ** 2
    print(square)
    number += 1
    
print("Finished")  # This code is executed once

break Keyword

count = 0

while True:  # this condition is always True
    print(count)
    count += 1
    if count >= 5:
        break           # exit loop if count >= 5

continue Keyword

Print only odd numbers.

for x in range(10):
    if x % 2 == 0:
        continue   # skip print(x) for this loop
    print(x)

# 1
# 3
# 5
# 7
# 9

Functions

Function Definition

Note: Indention marks the body of a function

def hello_world():  # function named my_function
    print("Hello, World!")

# With typed parameter    
def square(x: int):
    print(x ** 2)

# With untyped parameters and return value    
def sum_two_numbers(a, b):
    return a + b 

# Calculate the Fibonacci sequence    
def fib(n):
    """This is documentation string for function. It'll be available by fib.__doc__()
    Return a list containing the Fibonacci series up to n."""
    result = []
    a = 1
    b = 1
    while a < n:
        result.append(a)
        tmp_var = b
        b = a + tmp_var
        a = tmp_var
    return result

Default Parameters

def multiply_by(a, b=2):
    return a * b

print(multiply_by(3, 47))
print(multiply_by(3))    # call function using default value for b parameter

# 126
# 6

Classes and Objects

Definition

class MyClass:
    variable = assign any value to variable

    def foo(self):   # self parameter is explained later
        print("Hello from function foo")
        
# Create an instance of the class
my_instance = MyClass()

Variable Access

class MyClass:
    variable = 1

# Create an instance
my_object = MyClass()

# Change variable
my_object.variable = 2     

self Parameter

The self parameter is a Python convention. self is the first parameter passed to any class method. Python will use the self parameter to refer to the object being created.

class Calculator:
    current = 0

    def add(self, amount):
        self.current += amount

    def get_current(self):
        return self.current


c = Calculator()
c.add(22)
c.add(11)
print(c.get_current())

# 33

__init__ method

__init__ function is used to initialize the objects it creates. __init__ is short for “initialize”. __init__() always takes at least one argument, self, which refers to the object being created. __init__() function sets up each object the class creates.

class Square:

    def __init__(self):    # special method __init__
        self.sides = 4


square = Square()
print(square.sides)
# Prints: 4


class Car:
    def __init__(self, color):
        self.color = color


car = Car("blue")  # Note: you should not pass self parameter explicitly, only color parameter
print(car.color)
# Prints: blue

Modules and Packages

Modules in Python are simply Python files with the .py extension containing Python definitions and statements. Modules can be handy when you want to use your function in a number of programs without copying its definition into each program. Modules are imported from other modules using the import keyword and the file name without an extension. The first time a module is loaded into a running Python script, it is initialized by executing the code in the module once.

import calculator

# Create new instance of Calculator class defined in calculator module
calc = calculator.Calculator()    


import my_module

# Call function hello_world defined in my_module
my_module.hello_world("Kai")

from Statement

With the from statement, you can import names. This way you can use the imported name without the ‘module name’ prefix.

from calculator import Calculator

# Use Calculator class directly without prefix calculator.
calc = Calculator()    


import hello_world from my_module

# Call function hello_world without prefix
hello_world("Kai")