Strings
s = "hello"
s.upper()
s.lower()
s.strip()
s.replace("h", "H")
s.split(",")
s.find("l")
s[0]
s[::-1]
List
lst = [1, 2, 3]
lst.append(4)
lst.extend([5, 6])
lst.insert(1, 10)
lst.remove(2)
lst.pop()
lst[1] = 100
len(lst)
lst.sort()
lst.reverse()
List Comprehension
squares = [x*x for x in range(5)]
evens = [x for x in range(10) if x % 2 == 0]
Tuple
t = (1, 2, 3)
t[0]
len(t)
Dictionary
d = {'a': 1, 'b': 2}
d['a']
d['c'] = 3
d.get('d', 0)
d.keys()
d.values()
d.items()
d.pop('a')
Set
s = {1, 2, 3}
s.add(4)
s.remove(2)
s.union({5})
s.intersection({3, 4})
s.difference({1})
Function (def)
def greet(name):
return "Hello " + name
Class & Object
class Person:
def __init__(self, name):
self.name = name
def speak(self):
print("Hi", self.name)
p = Person("Alice")
p.speak()
Inheritance
class Animal:
def sound(self):
print("Some sound")
class Dog(Animal):
def sound(self):
print("Bark")
Polymorphism
def animal_sound(animal):
animal.sound()
animal_sound(Dog())
Abstraction & Abstract Method
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
Class Method
class A:
count = 0
@classmethod
def show(cls):
print(cls.count)
Static Method
class Math:
@staticmethod
def add(x, y):
return x + y
Date Functions
from datetime import datetime, date
now = datetime.now()
today = date.today()
now.strftime("%Y-%m-%d")
Common Built-in Functions
len(), type(), range(), sum(), min(), max(), sorted(), input(), print()
Lambda Function
square = lambda x: x * x
Map, Filter, Reduce
list(map(lambda x: x*2, [1,2,3]))
list(filter(lambda x: x%2==0, [1,2,3]))
from functools import reduce
reduce(lambda x,y: x+y, [1,2,3])
Exception Handling
try:
x=1/0
except ZeroDivisionError:
print("Error")
finally:
print("Done")
File Handling
with open("file.txt", "r") as f:
data = f.read()
with open("file.txt", "w") as f:
f.write("Hello")
Important Keywords
and, or, not, in, is, if, elif, else, for, while, break, continue, return, import, from, as, pass, class, def, with,
lambda, yield, try, except, finally, global, nonlocal