Skip to main content

Python

This page provides a quick overview of python basics.

Variables

price = 10 # int
print(type(price))

rating = 4.9 # float
print(type(rating))

is_published = True # bool
print(type(is_published))

Inputs

name = input('what is your name? ')

Type Conversions

int(2.3) # 2

float('2.2222') #2.2222

str(23.1) # '23.1'

String

string_example = "python course"

# Print Ranges
print(string_example[0:3]) # prints pyt
print(string_example[0]) # p
print(string_example[-1]) # e
print(string_example[0:-3]) # python cou
print(string_example[-3:-1]) # rs
print(string_example[-3:-2]) # r
print(string_example[-3:-4]) #
print(string_example[:2]) # py
print(string_example[2:]) # thon course
print(string_example[:]) # python course

# Len
string_example = "python course"
len(string_example)

# Find
string_example = "python course"
print(string_example.find('p')) # 0

# Replace
string_example = "python course"
print(string_example.replace('p', 'j')) # jython course

# In
string_example = "python course"
print('python' in string_example) # True

Arithmetic Operations

# Float division
10 / 3 # 3.3333333333333335

# Int division
10 // 3 # 3

# Modulus
10 % 3 # 1

# Power
10 ** 3 # 1000

Match Statment

def weekday(n):
match n:
case 0: return "Monday"
case 1: return "Tuesday"
case 2: return "Wednesday"
case 3: return "Thursday"
case 4: return "Friday"
case 5: return "Saturday"
case 6: return "Sunday"
case _: return "Invalid day number"

print(weekday(3))

If Else Statement

is_hot = True 
is_cold = False

if is_hot:
print("It's a hot day")
elif is_cold:
print("It's a cold day")
else:
print("Enjoy your day")

While Loop

i = 1 
while i <= 5:
print('*' * i)
i = i + 1

For Loop

for item in 'Python':
print(item) # P y t h o n

for item in range(3):
print(item) # 0 1 2

for item in range(1, 3):
print(item) # 1 2

Lists

list_example = ["1", 2, "2.4", 3.12, True]

# Print single element
print(list_example[0])
print(list_example[1])
print(list_example[2])
print(list_example[3])
print(list_example[4])

# Print all elements
for item in list_example:
print(item) # 1 2 2.4 3.12

# Sorting
list_example = [1, 4, 5, 2, 4]
sorted_list_example = sorted(list_example)
print(sorted_list_example) # [1, 2, 4, 4, 5]

# In Place sorting
print(list_example) # [1, 4, 5, 2, 4]
print(list_example.sort()) # None
print(list_example) # [1, 2, 4, 4, 5]

# In Place Reverse
print(list_example.reverse()) # None
print(list_example) # [5, 4, 4, 2, 1]

# Copy
list_example_copy = list_example.copy()
print(list_example_copy)

2D Lists

matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]

# Print single element
print(matrix[0][0])
matrix[0][0] = 20
print(matrix[0][0])

# Print all elements
for rows in matrix:
for item in rows:
print(item) # 20 2 3 4 5 6 7 8 9

Tuples

Tuples are immutable

tuple_example = (1, 2, 3)

# Print single element
print(tuple_example[0])

# Unpacking
x, y, z = tuple_example
print(x)

Sets

set_example = {1, 2, 3, 4, 4}

# Print all elements
print(set_example) # {1, 2, 3, 4}

# adding an element
set_example.add(5)
print(set_example) # {1, 2, 3, 4, 5}

# removing an element
set_example.remove(1)
print(set_example) # {2, 3, 4, 5}

# check if exists
print(2 in set_example) # True

Dictionaries

Key value pair, where both the key and value can be of any type. The key cannot be duplicated.

dict_example = {
"name": "John Smith",
"age" : 30,
"is_verified": True
}

# Print single element
print(dict_example["name"]) # John Smith

# Print non existing value
print(dict_example["Name"]) # KeyError: 'Name'

# Print non existing value with get
print(dict_example.get("Name", "default value")) # default value

Functions

def greet_user(name):
print(f'Hi {name}!')

print(greet_user(name="John"))

Exception

try:
age = int(input("Age: "))
print(age)
except ZeroDivisionError:
print('Age can not be divied by zero')
except ValueError:
print('Invalid value')

Classes

class Point:
def move(self):
print("move")

def draw(self):
print("draw")

point = Point()
# even though we don't have variables x and y we can assign x and y values
point.x = 10
point.y = 20
print(f"x: {point.x}, y: {point.y}")
point.move()
point.draw()

Constructor

class Point:
def __init__(self, x, y):
self.x = x
self.y = y

point = Point(20, 40)
print(f"x: {point.x}, y: {point.y}")
point.x = 10
point.y = 20
print(f"x: {point.x}, y: {point.y}")

Inheritance

class Mammal:
def walk(self):
print("walk")

class Dog(Mammal):
pass

class Cat(Mammal):
pass

dog = Dog()
dog.walk()

cat = Cat()
cat.walk()

Random

import random

# Print random floating point number between 0 and 1
for i in range(3):
print(random.random())

# Print random int number within given range(Both included)
for i in range(3):
print(random.randint(10, 20))

# Randomly select element in a list
list_example = range(1, 5)
print(random.choice(list_example))