Data Types
x = 42 # int
y = 3.14 # float
s = "hello" # str
b = True # bool
n = None # NoneType
lst = [1,2,3] # list (mutable)
tup = (1,2,3) # tuple (immutable)
d = {k:v} # dict
st = {1,2,3} # set (unique)
String Operations
s = "Hello World"
s.upper() # HELLO WORLD
s.lower() # hello world
s.split(" ") # ['Hello','World']
s.strip() # remove whitespace
s.replace("l","L") # HeLLo WorLd
s.startswith("H") # True
f"Name: {name}" # f-string
",".join(lst) # "a,b,c"
s[0:5] # "Hello" (slice)
List Operations
lst = [1,2,3,4,5]
lst.append(6) # [1,2,3,4,5,6]
lst.insert(0,0) # insert at index
lst.pop() # remove & return last
lst.remove(3) # remove first match
lst.sort() # sort in-place
sorted(lst) # returns new list
lst.reverse() # reverse in-place
len(lst) # length
lst[1:3] # [2,3] slice
lst[-1] # last element
3 in lst # True
Control Flow
if x > 0:
print("positive")
elif x == 0:
print("zero")
else:
print("negative")
# Ternary
result = "yes" if x > 0 else "no"
# Loops
for i in range(5): # 0,1,2,3,4
for i in range(2,10,2): # 2,4,6,8
for k,v in d.items(): # dict
for i,v in enumerate(lst): # idx+val
while condition:
break # exit loop
continue # skip iteration
# Comprehensions
squares = [x**2 for x in range(10)]
evens = [x for x in lst if x%2==0]
sq_dict = {x:x**2 for x in range(5)}
Functions
def greet(name, greeting="Hello"):
# Docstring goes here
return f"{greeting}, {name}!"
# *args — variable positional
def add(*nums):
return sum(nums)
# **kwargs — variable keyword
def config(**opts):
print(opts)
# Lambda
double = lambda x: x * 2
# map/filter/reduce
list(map(lambda x: x*2, lst))
list(filter(lambda x: x>2, lst))
from functools import reduce
reduce(lambda a,b: a+b, lst)
Exception Handling
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
except (TypeError, ValueError):
print("Type or Value error")
else:
print("No exception")
finally:
print("Always runs")
# Raise
raise ValueError("Bad input")
# Custom exception
class MyError(Exception):
pass
File I/O
# Read text
with open("file.txt") as f:
content = f.read()
lines = f.readlines()
# Write text
with open("out.txt", "w") as f:
f.write("Hello
")
# Append
with open("log.txt", "a") as f:
f.write("new line
")
# CSV with pandas
import pandas as pd
df = pd.read_csv("data.csv")
df.to_csv("out.csv", index=False)
# JSON
import json
data = json.loads(json_str)
json_str = json.dumps(data, indent=2)
OOP Basics
class Animal:
species = "Unknown" # class var
def __init__(self, name):
self.name = name # instance var
def speak(self):
return f"{self.name} speaks"
@classmethod
def create(cls, name):
return cls(name)
@staticmethod
def info():
return "I am an animal"
class Dog(Animal):
def speak(self): # override
return f"{self.name}: Woof!"
d = Dog("Rex")
isinstance(d, Animal) # True