Welcome to the comprehensive Python course. Python is a versatile, beginner-friendly programming language.
Getting Started
Chapter I
Chapter II
Chapter III
Chapter IV
Chapter V
Appendix
Python is a high-level, interpreted programming language known for its readability and versatility. Created by Guido van Rossum in 1991.
- Easy to Learn: Simple syntax similar to English
- Interpreted: No compilation needed
- Dynamically Typed: No type declarations required
- Multi-paradigm: Supports OOP, functional, and procedural programming
- Huge Ecosystem: Extensive standard library and third-party packages
Python's syntax is clean and easy to understand.
print("Hello, World!")Used in web development, data science, AI/ML, automation, and more.
Python developers are in high demand across industries.
Massive ecosystem with extensive documentation and libraries.
Download from python.org or use a distribution like Anaconda.
python --version
python3 --versionpython script.py
python -c "print('Hello')"
python -i # Interactive modeRecommended: VS Code with Python extension, PyCharm, or Jupyter Notebook.
print("Hello, World!")Variables:
name="Python"version=3.12print(f"Welcome to {name}{version}!")name="John"# Stringage=30# Integerheight=5.9# Floatis_active=True# Booleannothing=None# None# Integersx=42binary=0b1010hexadecimal=0xFF# Floatspi=3.14159scientific=2.5e6# Stringssingle='Hello'double="World"multi="""Multiplelines"""# Booleansis_valid=Trueis_empty=Falseprint(type("hello")) # <class 'str'>print(type(42)) # <class 'int'>print(type(3.14)) # <class 'float'>print(type(True)) # <class 'bool'>int("42") # 42str(42) # "42"float("3.14") # 3.14bool(1) # Truebool(0) # Falsea, b=10, 3print(a+b) # 13print(a-b) # 7print(a*b) # 30print(a/b) # 3.333...print(a//b) # 3 (floor division)print(a%b) # 1 (modulus)print(a**b) # 1000 (exponent)print(5==5) # Trueprint(5!=3) # Trueprint(5>3) # Trueprint(5>=5) # Trueprint(5<3) # Falseprint(5<=5) # Trueprint(TrueandFalse) # Falseprint(TrueorFalse) # Trueprint(notTrue) # Falseprint(5&3) # 1 (AND)print(5|3) # 7 (OR)print(5^3) # 6 (XOR)print(~5) # -6 (NOT)print(4<<1) # 8 (left shift)print(4>>1) # 2 (right shift)x=10x+=5# 15x-=3# 12x*=2# 24x/=4# 6.0score=85ifscore>=90:
print("A grade")
elifscore>=80:
print("B grade")
elifscore>=70:
print("C grade")
else:
print("Need improvement")age=20status="adult"ifage>=18else"minor"# Rangeforiinrange(5):
print(i) # 0, 1, 2, 3, 4# Sequencefruits= ["apple", "banana", "cherry"]
forfruitinfruits:
print(fruit)
# With indexfori, fruitinenumerate(fruits):
print(f"{i}: {fruit}")count=0whilecount<5:
print(count)
count+=1foriinrange(10):
ifi==5:
break# Exit loopifi==2:
continue# Skip iterationprint(i)status="success"matchstatus:
case"success":
print("Operation succeeded")
case"error":
print("Operation failed")
case _:
print("Unknown status")defgreet(name):
returnf"Hello, {name}!"print(greet("World"))# Default parametersdefgreet(name, greeting="Hello"):
returnf"{greeting}, {name}!"print(greet("John")) # Hello, John!print(greet("John", "Hi")) # Hi, John!# *argsdefsum(*args):
total=0fornuminargs:
total+=numreturntotalprint(sum(1, 2, 3, 4, 5)) # 15# **kwargsdefprint_info(**kwargs):
forkey, valueinkwargs.items():
print(f"{key}: {value}")
print_info(name="John", age=30)defdivide(a, b):
ifb==0:
returnNonereturna/b# Multiple returnsdefget_stats(numbers):
returnmin(numbers), max(numbers), sum(numbers)
min_val, max_val, total=get_stats([1, 2, 3, 4, 5])square=lambdax: x**2print(square(5)) # 25add=lambdaa, b: a+bprint(add(3, 4)) # 7defgreet(name: str) ->str:
returnf"Hello, {name}!"defprocess(items: list[int], multiplier: int=2) ->list[int]:
return [x*multiplierforxinitems]s1="Hello"s2='World's3="""Multi-linestring"""s4="Hello "+"World"s=" Hello, World! "s.upper() # " HELLO, WORLD! "s.lower() # " hello, world! "s.strip() # "Hello, World!"s.replace("World", "Python")
s.split(",") # [" Hello", " World! "]s.find("World") # 9s.count("l") # 3s.startswith(" H") # Trues.endswith("! ") # Truename="John"age=30# f-strings (Python 3.6+)print(f"My name is {name} and I'm {age}")
# format()print("My name is {} and I'm {}".format(name, age))
print("My name is {n} and I'm {a}".format(n=name, a=age))
# % operatorprint("My name is %s"%name)s="Hello World"s[0] # "H"s[0:5] # "Hello"s[6:] # "World"s[-5:] # "World"s[::2] # "HloWrd" (every 2nd char)s[::-1] # "dlroW olleH" (reversed)numbers= [1, 2, 3, 4, 5]
mixed= [1, "hello", True, 3.14]
nested= [[1, 2], [3, 4]]
empty= []fruits= ["apple", "banana", "cherry"]
fruits[0] # "apple"fruits[-1] # "cherry"fruits[0:2] # ["apple", "banana"]fruits= ["apple", "banana", "cherry"]
fruits.append("orange") # Add to endfruits.insert(1, "mango") # Insert at indexfruits.extend(["grape"]) # Add multiplefruits.remove("banana") # Remove by valuefruits.pop() # Remove and return lastfruits.pop(0) # Remove at indexfruits.clear() # Remove allnumbers= [3, 1, 4, 1, 5, 9, 2, 6]
len(numbers) # 8sorted(numbers) # Returns sorted copynumbers.sort() # Sorts in placenumbers.reverse() # Reverses in placenumbers.count(1) # Count occurrencesnumbers.index(4) # Find indexnumbers.copy() # Shallow copy"cherry"infruits# Membership test# Basicsquares= [x**2forxinrange(10)]
# With conditionevens= [xforxinrange(10) ifx%2==0]
# Nestedmatrix= [[i*jforjinrange(3)] foriinrange(3)]point= (10, 20)
single= (42,) # Comma required for single elementmixed= (1, "hello", True)point= (10, 20, 30)
point[0] # 10point[-1] # 30point[0:2] # (10, 20)point= (10, 20, 30)
point.count(10) # 1point.index(20) # 1point= (10, 20, 30)
x, y, z=point# Extended unpackingfirst, *middle, last= [1, 2, 3, 4, 5]
# first=1, middle=[2,3,4], last=5fromcollectionsimportnamedtuplePoint=namedtuple('Point', ['x', 'y'])
p=Point(10, 20)
print(p.x, p.y)numbers= {1, 2, 3, 4, 5}
from_list=set([1, 2, 2, 3]) # {1, 2, 3}empty=set() # Note: {} creates dicta= {1, 2, 3, 4}
b= {3, 4, 5, 6}
a.union(b) # {1, 2, 3, 4, 5, 6}a.intersection(b) # {3, 4}a.difference(b) # {1, 2}a.symmetric_difference(b) # {1, 2, 5, 6}# In-placea.update(b)
a.intersection_update(b)s= {1, 2, 3}
s.add(4) # Add elements.remove(2) # Remove (raises error if missing)s.discard(10) # Remove (no error)s.pop() # Remove arbitrary elements.clear() # Remove alllen(s) # 32ins# Trueperson= {"name": "John", "age": 30}
from_tuples=dict([("a", 1), ("b", 2)])
comprehension= {x: x**2forxinrange(5)}person= {"name": "John", "age": 30}
person["name"] # "John"person.get("name") # "John"person.get("email", "not found") # Default valueperson.keys() # dict_keys(['name', 'age'])person.values() # dict_values(['John', 30])person.items() # dict_items([('name', 'John'), ...])person= {"name": "John", "age": 30}
person["email"] ="john@example.com"# Addperson["age"] =31# Updatedelperson["age"] # Deleteperson.pop("email") # Remove and return# Update with another dictperson.update({"city": "NYC", "age": 32})person= {"name": "John", "age": 30}
len(person) # 2person.clear() # Remove allperson.copy() # Shallow copyperson.setdefault("country", "USA") # Set if not existssquares= {x: x**2forxinrange(5)}
word_lengths= {word: len(word) forwordin ["apple", "banana"]}squares= [x**2forxinrange(10)]
evens= [xforxinrange(20) ifx%2==0]
matrix= [[i*jforjinrange(3)] foriinrange(3)]numbers= [1, 2, 2, 3, 3, 4, 5]
unique_squares= {x**2forxinnumbers}words= ["apple", "banana", "cherry"]
word_lengths= {word: len(word) forwordinwords}# If-else in comprehension
[xifx>0else-xforxin [-1, 2, -3]]
# [1, 2, 3]classPerson:
def__init__(self, name, age):
self.name=nameself.age=agedefgreet(self):
returnf"Hello, I'm {self.name}"defbirthday(self):
self.age+=1person=Person("John", 30)
print(person.greet())
person.birthday()classDog:
species="Canis familiaris"# Class variabledef__init__(self, name, breed):
self.name=name# Instance variableself.breed=breedd1=Dog("Rex", "German Shepherd")
d2=Dog("Buddy", "Labrador")classPerson:
def__init__(self, name, age):
self.name=name# Publicself._age=age# Protected (convention)self.__ssn="123-45-6789"# Private (name mangling)person=Person("John", 30)
print(person.name) # OKprint(person._age) # Works but discouragedprint(person._Person__ssn) # Name manglingclassCircle:
def__init__(self, radius):
self._radius=radius@propertydefradius(self):
returnself._radius@radius.setterdefradius(self, value):
ifvalue<0:
raiseValueError("Radius cannot be negative")
self._radius=value@propertydefarea(self):
return3.14159*self._radius**2classMath:
@staticmethoddefadd(a, b):
returna+b@classmethoddeffrom_string(cls, s):
returncls(*map(int, s.split(",")))
Math.add(2, 3) # 5Math.from_string("1,2,3") # Math instanceclassAnimal:
def__init__(self, name):
self.name=namedefspeak(self):
raiseNotImplementedErrorclassDog(Animal):
defspeak(self):
returnf"{self.name} says Woof!"classCat(Animal):
defspeak(self):
returnf"{self.name} says Meow!"dog=Dog("Rex")
print(dog.speak()) # Rex says Woof!classFlyable:
deffly(self):
return"Flying!"classSwimmable:
defswim(self):
return"Swimming!"classDuck(Flyable, Swimmable):
passduck=Duck()
print(duck.fly())
print(duck.swim())classA:
defmethod(self):
return"A"classB(A):
defmethod(self):
return"B"classC(A):
defmethod(self):
return"C"classD(B, C):
passprint(D().method()) # B (MRO: D -> B -> C -> A)classAnimal:
def__init__(self, name):
self.name=nameclassDog(Animal):
def__init__(self, name, breed):
super().__init__(name)
self.breed=breedfromabcimportABC, abstractmethodclassShape(ABC):
@abstractmethoddefarea(self):
passdefdescribe(self):
returnf"Area: {self.area()}"classCircle(Shape):
def__init__(self, radius):
self.radius=radiusdefarea(self):
return3.14159*self.radius**2# Import entire moduleimportmathprint(math.sqrt(16))
# Import specific itemsfrommathimportsqrt, piprint(sqrt(16))
# Import with aliasimportnumpyasnpfromdatetimeimportdatetimeasdt# Import everything (not recommended)frommathimport*# my_module.pydefgreet(name):
returnf"Hello, {name}!"PI=3.14159# main.pyfrommy_moduleimportgreet, PIprint(greet("World"))importsysprint(sys.path)my_package/
__init__.py
module1.py
module2.py
subpackage/
__init__.py
module3.py
# Expose package contentsfrom .module1importfunction1from .module2importfunction2__all__= ["function1", "function2"]# From subpackage/module3.pyfrom . importmodule1# Same packagefrom .. importmodule2# Parent package# Read entire filewithopen("file.txt", "r") asf:
content=f.read()
# Read lineswithopen("file.txt", "r") asf:
lines=f.readlines()
# orforlineinf:
print(line)
# Read all lines as listwithopen("file.txt", "r") asf:
lines=f.read().splitlines()# Write (overwrites)withopen("output.txt", "w") asf:
f.write("Hello, World!")
# Appendwithopen("output.txt", "a") asf:
f.write("\nNew line")
# Write multiple lineswithopen("output.txt", "w") asf:
f.writelines(["line1\n", "line2\n"])importjson# Write JSONdata= {"name": "John", "age": 30}
withopen("data.json", "w") asf:
json.dump(data, f, indent=2)
# Read JSONwithopen("data.json", "r") asf:
data=json.load(f)try:
result=10/0exceptZeroDivisionError:
print("Cannot divide by zero!")
exceptExceptionase:
print(f"Error: {e}")
else:
print("No errors occurred")
finally:
print("Always executes")defvalidate_age(age):
ifage<0:
raiseValueError("Age cannot be negative")
returnagetry:
validate_age(-5)
exceptValueErrorase:
print(e)classValidationError(Exception):
def__init__(self, message, field):
super().__init__(message)
self.field=fieldraiseValidationError("Invalid input", "email")BaseException
├── SystemExit
├── KeyboardInterrupt
└── Exception
├── ValueError
├── TypeError
├── KeyError
└── ...
defmy_decorator(func):
defwrapper(*args, **kwargs):
print("Before function")
result=func(*args, **kwargs)
print("After function")
returnresultreturnwrapper@my_decoratordefsay_hello(name):
print(f"Hello, {name}!")
say_hello("World")defrepeat(times):
defdecorator(func):
defwrapper(*args, **kwargs):
for_inrange(times):
result=func(*args, **kwargs)
returnresultreturnwrapperreturndecorator@repeat(3)defgreet():
print("Hello!")
greet() # Prints "Hello!" 3 timesclassCountCalls:
def__init__(self, func):
self.func=funcself.count=0def__call__(self, *args, **kwargs):
self.count+=1print(f"Called {self.count} times")
returnself.func(*args, **kwargs)
@CountCallsdefsay_hello():
print("Hello!")classMyClass:
@propertydefvalue(self):
returnself._value@staticmethoddefstatic_method():
print("Static method")
@classmethoddefclass_method(cls):
print("Class method")defcount_up_to(n):
count=1whilecount<=n:
yieldcountcount+=1fornumincount_up_to(5):
print(num) # 1, 2, 3, 4, 5# Like list comprehension but lazysquares= (x**2forxinrange(10))
forsqinsquares:
print(sq)defmy_gen():
yield1yield2yield3gen=my_gen()
print(next(gen)) # 1print(next(gen)) # 2print(next(gen)) # 3# print(next(gen)) # StopIterationdeffibonacci():
a, b=0, 1whileTrue:
yieldaa, b=b, a+bfib=fibonacci()
print([next(fib) for_inrange(10)])
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]withopen("file.txt", "r") asf:
content=f.read()
# File automatically closedwithopen("output.txt", "w") asf:
f.write("Hello")
# File automatically closedclassFileManager:
def__init__(self, filename, mode):
self.filename=filenameself.mode=modeself.file=Nonedef__enter__(self):
self.file=open(self.filename, self.mode)
returnself.filedef__exit__(self, exc_type, exc_val, exc_tb):
ifself.file:
self.file.close()
returnFalse# Don't suppress exceptionswithFileManager("test.txt", "w") asf:
f.write("Hello!")fromcontextlibimportcontextmanager@contextmanagerdeftimer():
importtimestart=time.time()
yieldprint(f"Took {time.time() -start:.2f}s")
withtimer():
# code to timesum(range(1000000))fromcontextlibimportsuppresswithsuppress(FileNotFoundError):
os.remove("nonexistent.txt")square=lambdax: x**2print(square(5)) # 25add=lambdaa, b: a+bprint(add(3, 4)) # 7# mapnumbers= [1, 2, 3, 4, 5]
squares=list(map(lambdax: x**2, numbers))
# filterevens=list(filter(lambdax: x%2==0, numbers))
# reducefromfunctoolsimportreducetotal=reduce(lambdaa, b: a+b, numbers)
# sorteddata= [{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]
sorted_data=sorted(data, key=lambdax: x["age"])
# max/minpeople= [("John", 30), ("Jane", 25)]
oldest=max(people, key=lambdax: x[1])defmake_multiplier(n):
returnlambdax: x*ndouble=make_multiplier(2)
triple=make_multiplier(3)
print(double(5)) # 10print(triple(5)) # 15importunittestclassTestMath(unittest.TestCase):
deftest_add(self):
self.assertEqual(1+1, 2)
deftest_divide(self):
withself.assertRaises(ZeroDivisionError):
1/0if__name__=="__main__":
unittest.main()pip install pytest# test_math.pydefadd(a, b):
returna+bdeftest_add():
assertadd(1, 1) ==2deftest_add_negative():
assertadd(-1, -1) ==-2pytest test_math.py
pytest -v # Verbose
pytest -k "test_add"# Run specific testsassertx==5, "x should be 5"assertlist(map(lambdax: x**2, [1,2,3])) == [1, 4, 9]# Create
python -m venv myenv
# Activatesource myenv/bin/activate # Linux/Mac
myenv\Scripts\activate # Windows# Deactivate
deactivate
# Install packages
pip install requests
# Freeze requirements
pip freeze > requirements.txt
# Install from requirements
pip install -r requirements.txtpip install package
pip install package==1.2.3
pip install "package>=1.0"
pip uninstall package
pip list
pip show packagepip install poetry
poetry init
poetry add requests
poetry install
poetry run python script.pyimportrequestsresponse=requests.get("https://api.example.com/data")
data=response.json()
print(data)importjson# Parse JSON stringdata=json.loads('{"name": "John"}')
# Convert to JSON strings=json.dumps({"name": "John"}, indent=2)fromdatetimeimportdatetime, timedeltanow=datetime.now()
future=now+timedelta(days=7)
print(now.strftime("%Y-%m-%d %H:%M:%S"))importosos.getcwd() # Current directoryos.listdir(".") # List filesos.mkdir("new_dir") # Create directoryos.remove("file.txt") # Delete fileos.path.exists("file.txt")importrepattern=r"\d{3}-\d{4}"text="Call 123-4567"match=re.search(pattern, text)
ifmatch:
print(match.group())Now that you know Python fundamentals:
- Learn a web framework (Django, Flask, FastAPI)
- Explore data science (pandas, numpy, matplotlib)
- Learn machine learning (scikit-learn, TensorFlow)
- Build APIs and web services
- Practice with real projects