DM
Technical reference

Python Cheatsheet

Readable, versatile programming language

Getting Started

Hello World

The famous Hello World program in Python.

print("Hello, World!")

Variables

Python doesn't require variable type declaration.

age = 18
name = "John"
print(name)

Slicing String

Get a substring from a string.

msg = "Hello, World!"
print(msg[2:5])

Control Flow

If Else

num = 200
if num > 0:
    print("greater than 0")
else:
    print("not greater than 0")

Loops

for item in range(6):
    if item == 3: break
    print(item)
else:
    print("Finished!")

Functions

Defining a Function

def my_function():
    print("Hello from a function")

my_function()

Returning Values

def add(x, y):
    return x + y

result = add(5, 3)

File Handling

Read File Line by Line

with open("myfile.txt", "r", encoding='utf8') as file:
    for line in file:
        print(line)

Write String to File

with open("myfile.txt", "w") as file:
    file.write("Hello")

Data Types

String

text = "Hello World"

List

mylist = [1, 2, 3]

Dictionary

data = {"one": 1, "two": 2}

Set

unique_items = {"a", "b"}

F-Strings

Basic f-String

name = "Alice"
print(f"Hello, {name}")

F-String Math

num = 5
print(f"{num} + 5 = {num + 5}")

Lists

Create and Append

mylist = []
mylist.append(1)
mylist.append(2)

Slicing

a = ['a','b','c','d']
print(a[1:3])

Modules

Import

import math
print(math.sqrt(16))

Import Specific

from math import floor
print(floor(3.7))

Classes

Basic Class

class MyClass:
    pass

obj = MyClass()

Constructor & Method

class Animal:
    def __init__(self, name):
        self.name = name

a = Animal("Dog")
print(a.name)

Exceptions

Try Except

try:
    raise ValueError("Oops!")
except ValueError as e:
    print(e)