Man

Development & AI | Alper Akgun

Python cheatsheet

August, 2023

Examples covering python


print('Hello, world')

# Variables
name = 'Joe'
weight = 98.2

# Printing text
print(f"My name is {name} and my weight is {weight}.")

# Lists
info = ['bugs', name, weight]
print("I am a loon.", info)

# Functions
def add(a, b):
    """Adds a & b"""
    return a + b

print(add(2, 3))

## multiple
def add_all(*numbers):
    return sum(numbers)

print(add_all(1,2,3))

## arguments
def process(x, *numbers, y=22, **fruits):
    print(x, numbers, y, fruits)

process(42, 1, 2, 3, y=21, n=10, m=20)
# Ranges
print(*range(3))
print(*range(1, 3))
print(*range(1, 9, 2))

# Lists
countries = ['Italy', 'Turkey', 'France']
print(countries[0])
print(countries[-2])

countries.append('England')
print(countries[3:])

# Loops
for country in countries:
    print(country)

for i, country in enumerate(countries):
    print(f"{i} => {country}")

# country capitals
country_capitals = {
    'Italy': 'Rome',
    'Turkey': 'Ankara',
    'France': 'Paris',
}

print(country_capitals['Italy'])
del country_capitals['Turkey']

for country in country_capitals.keys(): # or omit .keys()
    print(country)

for country, capital in country_capitals.items():
    print('{} is capital of {}'.format(capital, country))


# while loop

a, b = 1, 1
while b < 20:
    a, b = b, a + b

print(a, b)


# files

with open('/etc/passwd') as fp:
    for line in fp:
        print(line.strip())

# exceptions

def work(a, b):
    if b == 0:
        raise ValueError("Division by zero")
    return a / b

work(21, 3)
#work(21, 0)

try:
  work(21, 0)
except ValueError:
  print('Ok')

# queues

from queue import Queue

q = Queue()
q.put(22)

print('{!r}'.format(q))
v = q.get()


# Aggregates
numbers = [(x) for x in range(10)]
print(numbers)

print(sum(numbers), max(numbers), min(numbers), sorted(numbers, reverse=True))


# OO
import math

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return math.pi * self.radius ** 2

c = Circle(10)
print(c.area())