Python Reference Sheet

Why Use Python

Python is a powerful and user-friendly programming language known for its open-source nature, community-driven development, and cross-platform compatibility. As a high-level language, it abstracts away complex details of computer hardware, allowing programmers to focus on the logic of their code.

One of Python's key strengths is its readability. It utilizes clear syntax, making code easier to understand and maintain, both for beginners and experienced developers alike. Additionally, Python is dynamically typed, meaning variable types are determined at runtime, offering flexibility during development.

Beyond its ease of use, Python boasts a robust standard library, providing a rich set of built-in modules for common tasks like file handling, networking, and data manipulation. This extensive library, coupled with the vast ecosystem of third-party modules available for download, empowers developers to tackle a wide range of challenges.

The versatility of Python extends to its diverse applications. It is a popular choice for web development, system scripting, and scientific computing due to its powerful mathematical libraries. In recent years, Python has become a prominent language in the fields of artificial intelligence and machine learning, with frameworks like TensorFlow and PyTorch leveraging its capabilities.

Note: 

Most of the code examples are written using Python REPL (i.e. '>>>'), this makes testing small segments of code easier.  REPL is an acronym for Read, Evaluate, Print, and Loop. Developers use REPL Python to communicate with the Python Interpreter. In contrast to running a Python file, you can input commands in the REPL and see the results displayed immediately. Anything after a ":" will require an indent represented by the three dots ('...').  To access the REPL, just type python3 or python.

For example: 

>>> for i in range(5, 10):

...     print(i)


Table of Contents

Why Use Python

Important Python Tips

Python Basics

Built-in Python Data Types

Built-in Python Functions

Other Useful Python Syntax

Python Conditionals

Python Comparison Operators 

Using Lists in Python (Examples)

Using Dictionaries in Python (Examples)

Defining Custom Functions in Python

Python Loops (For and While) and Switch

Useful Python Methods

Bonus Python Information

Python Exceptions

Python Terminology

Python Interviewing Reference Materials


Important Python Tips

Below are important tips to remember when programming in Python:


Python Basics

These are the basic things you need to know to use Python for programming.

Printing a number

>>> print(123)

123

Printing a string

>>> print("test")

test

Adding two numbers (you can also use the following operators: '-', '/', '*', etc.)

>>> print(2+2)

4

Division (result is a floating point number) and Floor Division (result is an integer number)

>>> 5//2

2

>>> 5/2

2.5

Variable assignment (using '=' [equal sign] to put a value into a variable)

>>> number = 123456

Print a variable

>>> print(number)

123456

Function call (to run the code of the function)

>>> x = min(1, 2)

>>> print(x)

1

Comment (single line)

# a comment

Comment (multiple lines)

""" 

Multiline comment

"""


Built-in  Python Data Types

Data types are used for storing different types of data (i.e. integers, floating, strings, etc.).  It is important to note that Pyton is a Dynamically Typed language.  So when you assign a value to variable, it will automatically try to figure out what its data types is.

Integer (no decimal point): 

42

Floating Point (has a decimal point)

42.5

String (a sequence of letters surrounded by quotes)

"a string"

List (a type of value that holds other values, and can be change [i.e. mutable])

[1, 2, 3, ...] | ['a', 'b', 'c', ...]

Tuple (like a list, but cannot be changed [i.e. immutable])

(1, 2, 3, ...) | ['a', 'b', 'c', ...]

Dictionary (a mapping from keys to values)

{"a":1, "b":2, "c":3, ...}

Boolean (Can only be True or False)

True | False


Built-in Python Functions

This section displays useful  built-in functions for performing different types of actions or operations.

Calculate length the size (i.e. the amount of object it contains) of a variable.

>>> len("test")

4

Display the minimum value of the data passed as a parameter (i.e. 1, 2, 3 would be 1, a, b, c would be a)

>>> min(1, 2)

1

Display the maximum value of the data passed as a parameter (i.e. 1, 2, 3 would be 3, a, b, c would be c)

>>> max(1, 2)

2

Cast a value as an integer

>>> int("123")

123

Cast a value as a string

>>> str(123)

'123'

Cast a value as a boolean

>>> bool(1)

True

Display a range of numbers

>>> for i in range(5, 10):

...     print(i)

5

6

7

8

9


Other Useful Python Syntax

Below are examples of useful syntax in Python

Returning a value from custom function

>>> def test():

...     return "abc"

>>> print(test())

abc

Indexing (extracting one element at a certain position)

>>> "test"[0]

't'

>>> "test"[1]

'e'

Slicing (extracting some elements in a series from a string)

>>> "test"[1:3]

'es'

Continue to next loop iteration (stop processing at the position in the loops and starts at the next number)

continue

Exits a loop at the point where this statement is located.

break

Appending elements to a list

>>> numbers = [123,456,789]

>>> numbers.append(987)

>>> print(numbers)

[123, 456, 789, 987]

Getting a value from a list

>>> numbers = [123,456,789]

>>> value = numbers[0]

>>> print(value)

123

Replacing a value in a list

>>> numbers = [123,456,789]

>>> print(numbers)

[123, 456, 789]

>>> numbers[0] = 321

>>> print(numbers)

[321, 456, 789]

The Walrus Operator is represented by the `:=` syntax and can be used in a variety of contexts including while loops and if statements. (Requires: Python 3.8 or higher)

names = ["Jason", "Fred", "Jacob"]

if (name := input("Enter a name: ")) in names:

    print(f"Hello, {name}!")

else:

    print(f"Name {name} not found.")


Python Conditionals

Conditionals in Python allow for the controlling of logic when certain conditions are met.

>>> x = 2

>>> if x == 1:

...     print("x is one")

... else:

...     print("x is not one")

...

x is not one


Python Comparison Operators 

The comparison operators in Python are used by conditional logic (i.e. if, while, etc.) for making boolean comparison.

Equals Operator

>>> a = 2

>>> if a == 1:

...     print(True)

False

Not Equals Operator

>>> a = 2

>>> if a != 1:

...     print(True)

True

Less than Operator

>>> a = 2

>>> if a < 1:

...     print(True)

False

Less Than or Equal  Operator

>>> a = 2

>>> if a <= 1:

...     print(True)

False

Greater than Operator

>>> a = 2

>>> if a > 1:

...     print(True)

True

Greater Than or Equal Operator

>>> a = 2

>>> if a >= 1:

...     print(True)

True


Using Lists in Python (Examples)

List (a type of value that holds other values, and can be change [i.e. mutable])

>>> numbers = [7, 8, 9]

>>> first_number = numbers[0]

7


>>> numbers[2] = 11

>>> if 11 in numbers:

...    print("11 is in the list!")

11 is in the list!


>>> for n in numbers:

...    print(n)

[7, 11, 9]


Using Dictionaries in Python (Examples)

The dictionary data type allows the mapping of keys to values.

>>> numbers = {1: "one", 2: "two"}

>>> print(numbers[1])

one

>>> print(numbers[2])

two


Defining Custom Functions in Python

A custom function is a  reusable set of code where arguments can be passed, and new value returned

>>> def my_func (a, b):

...     result = a + b

...     return result

>>> if __name__ == '__main__':

...     print(my_func(5, 10))

15


Python Loops (For and While) and Switch

Python supports two different types of loops (i.e. For and While), and recent versions of Python now support switches

For Loop Example

>>> for numbers in [1, 2, 3, 4, 5]:

...     print(numbers)

While Loop Example

>>> a = 0

>>> while a < 10:

...     print(a)

...     a = a + 1

Switch Statement: The switch case feature called “structural pattern matching”.  (Requires: Python 3.10 or higher)

>>> fruit = "apple"

>>> match fruit:

...     case "apple":

...         print("This is an apple!")

...     case "banana":

...         print("This is a banana!")

...     case "orange":

...         print("This is an orange!")

...     case _:  # This is the default case

...         print("This is an unknown fruit.")


Useful Python Methods

Below is a list of useful Python methods that you can use in your coding.

String to lowercase

>>> "AA".lower()

'aa'

String to uppercase

>>> "aa".upper()

'AA'

Splits a string using spaces into a list

>>> "a b c".split(" ")

['a', 'b', 'c']

Removes unused whitespace around a string

>>> " this is a test ".strip()

'this is a test'

Combines a list of strings into one string with a space between the different elements

>>> " ".join(["a", "b", "c"])

'a b c'

Checks if a string starts with a substring

>>> "AA".startswith("a")

False

Checks if a string ends with a substring

>>> "AA".endswith("A")

True

Checks for the occurrence of an element in a list

>>> [1, 2, 3, 4, 4, 5].count(4)

2

Remove an element from a list

>>> a = [1, 2, 3, 4, 5]

>>> a.remove(2)

>>> print(a)

[1, 3, 4, 5]

Dictionary keys

>>> {1:2, 3:4, 5:6}.keys()

dict_keys([1, 3, 5])

Dictionary values

>>> {1:2, 3:4, 5:6}.values()

dict_values([2, 4, 6])

Dictionary key/value pairs

>>> {1:2, 3:4, 5:6}.items()

dict_items([(1, 2), (3, 4), (5, 6)])


Bonus Python Information

Below are some bonus tips that can help you.

Zipping two  lists (i.e. converting two lists into a dictionary)

>>> numbers = [1, 2]

>>> words = ["one", "two"]

>>> combined = list(zip(numbers, words))

>>> print(combined)

[(1, 'one'), (2, 'two')]

Set intersection (which element is in both sets)

>>> {1, 2} & {2, 3}

{2}

Set union (which elements are unique to both sets)

>>> {1, 2} | {2, 3}

{1, 2, 3}

Finds the index value of an element in a list.

>>> [1, 2, 3].index(2)

1

Sorts the order of a list of elements

>>> a = [3, 2, 1]

>>> a.sort()

>>> print(a)

[1, 2, 3]

Reverses the order of a list of elements

>>> a = [1, 2, 3]

>>> a.reverse()

>>> print(a)

[3, 2, 1]

Sums the value of a list of elements

>>> sum([1, 2, 3])

6

Numbering a list of elements (displays the index and value of different elements)

>>> a = [1, 2, 3]

>>> for i, item in enumerate(a):

...    print(i,item)

...

0 1

1 2

2 3

Read a file line by line

with open("sample_file.txt", "r") as file:

    # Read all lines of the file and store them in a list

    lines = file.readlines()


    # Print each line

    for line in lines:

        print(line, end="")  # Print without adding a newline at the end

Reads and writes a file contents

# Simulate a file with some content

fake_file_content = "This is some sample text content."


# Using with clause to open and close the file automatically

with open("sample_file.txt", "w") as file:  # Open in write mode for this example

    file.write(fake_file_content)  # Write the content to the file


# Now, read the contents using another with clause (assuming the file exists)

with open("sample_file.txt", "r") as file:

    contents = file.read()

    print(contents)

Generate a random number between 1 and 10

>>> import random

>>> x = random.randint(1, 10)

>>> print(x)

6

List comprehensions (a syntax construction to ease the creation of a list based on existing iterable.)

>>> a = [i for i in range(1, 5)]

>>> print(a)

[1, 2, 3, 4]

Checks if ANY condition holds

# Check if any element in a list is greater than 5

numbers = [1, 3, 7, 2, 4]

is_any_greater_than_5 = any(element > 5 for element in numbers)


# Print the result

print(is_any_greater_than_5)  # Output: True

Checks if ALL conditions hold

my_list = [True, True, True, True]

all_true = all(my_list)

print(all_true)  # Output: True

Lambda function (an anonymous function. This function can have any number of parameters but, can have just one statement. )

>>> a = lambda a, b : a*b

>>> print(a(5, 10))

50


Python Exceptions

A Python exception is an event that occurs during the execution of a program that disrupts the normal flow of the program.

Python exception syntax using try, except, else, and finally statements 

try:

    # Code... 

except:

    # optional block

    # Handling of exception (if required)

else:

    # execute if no exception

finally:

    # Code... (always executed)


Exception Groups: Can be handled using a new except* syntax. The * symbol indicates that multiple exceptions can be handled by each except* clause. (Requires: Python 3.11 or higher)

try:

raise ExceptionGroup('Example ExceptionGroup', (

TypeError('Example TypeError'),

ValueError('Example ValueError'),

KeyError('Example KeyError'),

AttributeError('Example AttributeError')

))

except* TypeError:

...

except* ValueError as e:

...

except* (KeyError, AttributeError) as e:

...


Python Terminology



Python Interviewing Reference Materials


Coding Exercises

Books