Python Notes
Quick reference guide for Python basics to advanced concepts.
Introduction to Python
Python is a high-level, interpreted programming language known for its simplicity and readability.
Data Types & Variables
Common data types: int, float, str, bool, list, tuple, set, dict.
Example:
x = 10
y = 3.14
name = 'Alice'
is_active = True
Operators
Python supports arithmetic (+, -, *, /, %), comparison (==, !=, >, <), logical (and, or, not), and
Example:
a, b = 5, 2
print(a + b) # 7
print(a ** b) # 25
Control Flow
Conditional statements and loops:
if x > 0:
print('Positive')
else:
print('Non-positive')
for i in range(5):
print(i)
Functions
Functions are defined using 'def'.
def greet(name):
return f'Hello, {name}!'
print(greet('Bob'))
Collections
Lists, Tuples, Sets, Dictionaries:
fruits = ['apple', 'banana', 'cherry']
point = (3, 4)
unique = {1, 2, 3}
person = {'name': 'Alice', 'age': 25}
File Handling
with open('example.txt', 'w') as f:
f.write('Hello File')
with open('example.txt', 'r') as f:
print(f.read())
Object-Oriented Programming
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f'{self.name} makes a sound')
dog = Animal('Dog')
dog.speak()
Modules & Packages
import math
print(math.sqrt(16))
from datetime import datetime
print(datetime.now())
Exceptions
try:
x = 10 / 0
except ZeroDivisionError:
print('Cannot divide by zero')
finally:
print('Done')