Python Basics

1. Introduction to Python
Python is an interpreted, dynamically typed, and high-level programming language.
It supports multiple paradigms: procedural, object-oriented, and functional programming.
Code blocks are defined by indentation (not braces).
2. Conditional Statements
num1 = 34
if num1 > 12:
print("Num1 is good")
elif num1 > 35:
print("Num2 is not gooooo....")
else:
print("Num2 is great")
3. Data Structures
List
- Ordered, mutable, allows duplicates.
my_list = [1, 2, 3, 4]
my_list.append(5)
my_list.remove(2)
print(my_list[0])
Common Functions:append(), extend(), insert(), remove(), pop(), sort(), reverse(), count(), index(), clear()
Tuple
- Ordered, immutable, allows duplicates.
t = (1, 2, 3)
print(t[0])
Common Functions:count(), index(), len(), max(), min(), sum()
Set
- Unordered, mutable, no duplicates.
s = {1, 2, 3}
s.add(4)
s.remove(2)
Common Functions:add(), remove(), discard(), union(), intersection(), difference(), issubset(), issuperset()
Dictionary
- Unordered collection of key-value pairs.
d = {'name': 'Likhitha', 'age': 24}
print(d['name'])
Common Functions:keys(), values(), items(), get(), pop(), update(), clear()
4. Operators
| Operator | Use |
== | Compares values |
is | Compares memory location (object identity) |
in | Checks membership inside iterable |
5. Type Conversion
Implicit Conversion: Done automatically by Python.
Explicit Conversion: Manually done using functions like
int(),float(),str().
6. Global, Local, and Nonlocal Variables
Global: Declared outside functions, can be used anywhere.
Local: Declared inside a function, only accessible within it.
Nonlocal: Used in nested functions to modify a variable from the enclosing scope.
def outer():
x = 10
def inner():
nonlocal x
x = 20
inner()
print(x)
outer()
7. Functions
Basic Function
def greet(name):
print(f"Hello, {name}!")
Arbitrary Arguments
*args→ Non-keyword arguments (tuple)**kwargs→ Keyword arguments (dictionary)
def myFun(*args, **kwargs):
print(args)
print(kwargs)
8. Lambda Function
square = lambda x: x ** 2
print(square(5))
9. Map, Filter, Reduce
from functools import reduce
# map()
nums = [1, 2, 3]
print(list(map(lambda x: x*2, nums)))
# filter()
print(list(filter(lambda x: x%2==0, nums)))
# reduce()
print(reduce(lambda x, y: x+y, nums))
10. Decorators
- Decorators modify the behavior of functions without changing their code.
def decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@decorator
def greet():
print("Hello!")
greet()
11. Inner Functions
Functions inside functions.
Can access variables of outer scope using
nonlocal.
12. Enumerate
fruits = ('apple', 'banana', 'cherry')
for index, fruit in enumerate(fruits, start=1):
print(index, fruit)
13. Iterators
- Objects that can be iterated using
iter()andnext().
s = "GFG"
it = iter(s)
print(next(it))
14. Generators
Used to create iterators with
yieldkeyword.They are memory efficient.
def gen():
for i in range(3):
yield i
for x in gen():
print(x)
15. Exception Handling
try:
x = 10 / 0
except ZeroDivisionError as e:
print(e)
else:
print("No error")
finally:
print("End of block")
User-defined Exception:
class CustomError(Exception):
pass
16. Object-Oriented Programming (OOP)
Class & Object
class Dog:
species = "Canine" # Class attribute
def __init__(self, name, age):
self.name = name
self.age = age
Inheritance
class Dog:
def speak(self):
print("Woof")
class Puppy(Dog):
def play(self):
print("Plays fetch")
Types of Inheritance:
Single, Multiple, Multilevel, Hierarchical, Hybrid
Polymorphism
Same method name, different behavior depending on class.
Achieved via:
Method Overriding
Duck Typing
Operator Overloading (
__add__,__str__, etc.)
Encapsulation
Restricts access using single
_or double__._var→ conventionally private__var→ name mangling used by Python
Abstraction
- Hides implementation using abstract classes.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
Instance vs Class vs Static Methods
class MyClass:
def instance_method(self):
print("Instance method", self)
@classmethod
def class_method(cls):
print("Class method", cls)
@staticmethod
def static_method():
print("Static method")
obj = MyClass()
obj.instance_method()
MyClass.class_method()
MyClass.static_method()
17. GIL (Global Interpreter Lock)
Only one thread executes Python bytecode at a time.
Affects CPU-bound tasks, not I/O-bound.
Alternatives: multiprocessing, asyncio, NumPy, C extensions.
18. Threading vs Multiprocessing
| Feature | Threading | Multiprocessing |
| Execution | Same memory space | Separate memory |
| GIL | Affected | Each process has its own GIL |
| Suitable for | I/O-bound tasks | CPU-bound tasks |
| Library | threading | multiprocessing |
19. Miscellaneous
ord() / chr() → Convert between characters and ASCII codes.
_var→ Private (by convention)__var→ Name mangling__init__,__str__,__add__→ Dunder (special) methods.


