Skip to content

Python

Hello World program

print("Hello, world!")

Variables and constants

x = 10
y = 20
Pi = 3.14159

Functions

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

Loops

for i in range(10):
    print(i)

Conditional statements

if x > y:
    print("x is greater than y")
elif x < y:
    print("x is less than y")
else:
    print("x is equal to y")

Lists and tuples

a = [1, 2, 3, 4, 5]
b = (1, 2, 3, 4, 5)

Dictionaries

d = {"one": 1, "two": 2, "three": 3}

String formatting

name = "John"
age = 30
print("My name is {} and I am {} years old.".format(name, age))

File I/O

with open("example.txt", "w") as f:
    f.write("Hello, world!")
with open("example.txt", "r") as f:
    print(f.read())

Classes

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def get_name(self):
        return self.name
    def get_age(self):
        return self.age
p = Person("John", 30)
print(p.get_name())
print(p.get_age())

Modules and packages

import math
print(math.pi)

Error handling

try:
    x = 1 / 0
except ZeroDivisionError:
    print("Cannot divide by zero.")