0% found this document useful (0 votes)
4 views20 pages

Python BeginnerToAdvanced

This document is a comprehensive guide to Python programming, covering 21 essential topics from variables and operators to classes and exceptions. It includes practical examples and tips for each topic to enhance understanding and coding skills. The guide is designed for learners at all levels, providing a structured approach to mastering Python.

Uploaded by

vladimir280874
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views20 pages

Python BeginnerToAdvanced

This document is a comprehensive guide to Python programming, covering 21 essential topics from variables and operators to classes and exceptions. It includes practical examples and tips for each topic to enhance understanding and coding skills. The guide is designed for learners at all levels, providing a structured approach to mastering Python.

Uploaded by

vladimir280874
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python

Beginner to Advanced
Complete Guide with Real Examples & Code

21 Essential Topics Covered

@CodeWithSiree
Instagram Python Education Channel

1. Variables 2. Operators 3. Functions 4. Libraries & Modules

5. Packages 6. Methods 7. Refactoring 8. Enumerations

9. Tuples / Dicts / Sets 10. Map, Filter, Reduce 11. Classes & Objects 12. Exceptions

13. Overloading 14. Iterators 15. Generators 16. List Comprehensions

17. Regular Expressions 18. Serialization 19. Partial Functions 20. Closures

21. Decorators
CodeWithSiree | Python: Beginner to Advanced Page 2

1. abc Variables
Variables are containers for storing data values. Python dynamically assigns the type based on the value —
no need to declare a type explicitly.

# Basic variable types


name = "Alice" # String
age = 25 # Integer
height = 5.7 # Float
is_dev = True # Boolean
# Multiple assignment
x, y, z = 1, 2, 3
# f-string formatting
print(f"My name is {name}, I am {age} years old.")
# Output: My name is Alice, I am 25 years old.
# Check type
print(type(name)) # <class str>
print(type(age)) # <class int>

■ Tip: Use meaningful variable names to enhance code readability. Avoid single letters except in loops.

2. + Operators
Operators perform operations on variables and values. Python has five main categories:

Type Operators Purpose

Arithmetic + - * / % ** // Math calculations

Comparison == != > < >= <= Compare values

Logical and or not Combine conditions

Assignment = += -= *= /= Assign / update

Bitwise & | ^ ~ << >> Bit-level operations

x = 10; y = 5
result = x + y # Arithmetic: 15
is_equal = (x == y) # Comparison: False
is_greater_even = (x > y) and (x % 2 == 0) # Logical: True
x += 3 # same as x = x + 3 → x is now 13
print(x) # 13

■ Tip: Combine operators for complex calculations or logic checks. Parentheses always clarify precedence.

3. tools Functions

Follow @CodeWithSiree on Instagram | Happy Coding! rocket


CodeWithSiree | Python: Beginner to Advanced Page 3

Functions are reusable blocks of code that perform a specific task. They reduce repetition and improve
organisation.

# Basic function
def greet(name):
return f"Hello, {name}!"
print(greet("Alice")) # Output: Hello, Alice!
# Default parameters
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Bob")) # Hello, Bob!
print(greet("Bob","Hi")) # Hi, Bob!
# *args and **kwargs
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3, 4)) # 10
# Lambda (anonymous) function
square = lambda x: x ** 2
print(square(5)) # 25

■ Tip: Use functions to reduce redundancy and improve code organisation. Keep each function focused on
one task.

Follow @CodeWithSiree on Instagram | Happy Coding! rocket


CodeWithSiree | Python: Beginner to Advanced Page 4

4. books Libraries and Modules


Libraries
Python libraries are collections of pre-written code for common tasks. Examples: NumPy (maths), Pandas
(data), Matplotlib (charts).

import math
result = [Link](16) # Output: 4.0
print([Link]) # 3.14159...
# Import specific functions
from math import sqrt, ceil
print(sqrt(25)) # 5.0
print(ceil(4.2)) # 5

Modules
A module is a .py file containing Python definitions and statements. Import it to use its functions anywhere.

# [Link]
def greet(name):
return f"Hello, {name}!"
# [Link]
import mymodule
print([Link]("Alice")) # Hello, Alice!

■ Tip: Explore Python's built-in libraries (math, os, datetime, json) and use modules to keep your code
organised.

5. box Packages
Packages are collections of modules organised in a directory hierarchy. They help structure large projects.

# Package structure:
mypackage/
__init__.py
[Link]
[Link]
# Importing from a package
from mypackage import module1
from mypackage.module2 import some_function
# Installing third-party packages via pip
# pip install requests numpy pandas
import requests
r = [Link]("[Link]
print(r.status_code) # 200

■ Tip: Use packages to logically organise your codebase for large projects. Use pip to install community
packages.

Follow @CodeWithSiree on Instagram | Happy Coding! rocket


CodeWithSiree | Python: Beginner to Advanced Page 5

6. puzzle Methods
Methods are functions associated with objects. They operate on the data inside the object. Python's built-in
types have many useful methods.

# String methods
text = "hello world"
print([Link]()) # HELLO WORLD
print([Link]()) # Hello World
print([Link]("world","Python")) # hello Python
print([Link]()) # ["hello", "world"]
print([Link]()) # removes leading/trailing spaces
# List methods
nums = [3, 1, 4, 1, 5, 9]
[Link](2) # add to end
[Link]() # sort in place
[Link]() # reverse in place
print([Link](1)) # count occurrences: 2
# Dictionary methods
d = {"a": 1, "b": 2}
print([Link]()) # dict_keys(['a','b'])
print([Link]()) # dict_values([1, 2])
print([Link]('c', 0)) # safe access: 0

■ Tip: Learn common methods for strings, lists, and dictionaries — they will save you hundreds of lines of
code.

7. wrench Refactoring
Refactoring improves the structure of existing code without changing its external behaviour. It makes code
cleaner and easier to maintain.

# BEFORE refactoring — repeated logic


result1 = (x + y) * z
result2 = (a + b) * z
result3 = (p + q) * z
# AFTER refactoring — extract method
def sum_and_multiply(p, q, factor):
return (p + q) * factor
result1 = sum_and_multiply(x, y, z)
result2 = sum_and_multiply(a, b, z)
# Rename variable for clarity
d = 86400 # bad: unclear
seconds_per_day = 86400 # good: self-documenting

■ Tip: Regularly refactor your code for better readability and maintainability. Follow the DRY principle: Don't
Repeat Yourself.

Follow @CodeWithSiree on Instagram | Happy Coding! rocket


CodeWithSiree | Python: Beginner to Advanced Page 6

8. cookie Enumerations
Enums are symbolic names for a set of fixed values. They make your code more readable and prevent magic
numbers/strings.

from enum import Enum, auto


class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
# Access enum members
print([Link]) # [Link]
print([Link]) # 1
print([Link]) # RED
# Use in conditionals
my_color = [Link]
if my_color == [Link]:
print("Go!") # Go!
# auto() assigns values automatically
class Direction(Enum):
NORTH = auto() # 1
SOUTH = auto() # 2
EAST = auto() # 3
WEST = auto() # 4

■ Tip: Use Enums to handle fixed sets of values. They prevent invalid states and make comparisons explicit.

9. package Tuples, Dictionaries & Sets


Tuples — Immutable Ordered Collections

point = (10, 20)


x, y = point # unpacking: x=10, y=20
print(point[0]) # 10
# point[0] = 99 # TypeError: immutable!
# Named tuple for readable code
from collections import namedtuple
Color = namedtuple("Color", ["r","g","b"])
c = Color(255, 128, 0)
print(c.r) # 255

Dictionaries — Key-Value Pairs

student = {"name": "Alice", "age": 25, "grade": "A"}


print(student["name"]) # Alice
student['email'] = 'a@[Link]' # add key
del student['grade'] # remove key
for k, v in [Link]():
print(f"{k}: {v}")
# Dict comprehension
squares = {n: n**2 for n in range(1, 6)}

Follow @CodeWithSiree on Instagram | Happy Coding! rocket


CodeWithSiree | Python: Beginner to Advanced Page 7

Sets — Unordered Unique Elements

unique = {1, 2, 3, 4, 5}
[Link](6); [Link](3)
a = {1,2,3,4}; b = {3,4,5,6}
print(a | b) # Union: {1,2,3,4,5,6}
print(a & b) # Intersection: {3, 4}
print(a - b) # Difference: {1, 2}

■ Tip: Use tuples for fixed data, dicts for key-value mapping, and sets for unique collections.

Follow @CodeWithSiree on Instagram | Happy Coding! rocket


CodeWithSiree | Python: Beginner to Advanced Page 8

10. recycle Map, Filter & Reduce


map() — Transform Every Item

numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # [1, 4, 9, 16, 25]
# Convert Celsius to Fahrenheit
temps_c = [0, 20, 37, 100]
temps_f = list(map(lambda c: c*9/5+32, temps_c))
print(temps_f) # [32.0, 68.0, 98.6, 212.0]

filter() — Keep Items Matching a Condition

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6, 8, 10]
words = ['cat','python','dog','java','go']
long_ones = list(filter(lambda w: len(w)>4, words))
print(long_ones) # ['python', 'java']

reduce() — Collapse to a Single Value

from functools import reduce


numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
print(total) # 15
# Chain map + filter + reduce
data = [1, 2, 3, 4, 5, 6]
result = reduce(lambda x,y: x+y,
list(map(lambda n: n**2,
filter(lambda n: n%2==0, data))))
print(result) # 4+16+36 = 56

■ Tip: Use map, filter, reduce for efficient, readable data processing pipelines.

11. bricks Classes & Objects


Python is object-oriented. Classes are blueprints for creating objects that bundle data (attributes) and
behaviour (methods).

Follow @CodeWithSiree on Instagram | Happy Coding! rocket


CodeWithSiree | Python: Beginner to Advanced Page 9

class Car:
wheels = 4 # class attribute
def __init__(self, brand, model, year):
[Link] = brand
[Link] = model
[Link] = year
[Link] = 0
def accelerate(self, amount):
[Link] += amount
return f"{[Link]} now at {[Link]} km/h"
def drive(self):
return f"The {[Link]} {[Link]} is driving."
my_car = Car("Toyota", "Corolla", 2022)
print(my_car.drive()) # The 2022 Toyota is driving.
print(my_car.accelerate(50)) # Toyota now at 50 km/h
# Inheritance
class ElectricCar(Car):
def __init__(self, brand, model, year, battery):
super().__init__(brand, model, year)
[Link] = battery
def charge_info(self):
return f"Battery: {[Link]} kWh"
tesla = ElectricCar("Tesla","Model 3",2023, 82)
print([Link]()) # inherited method
print(tesla.charge_info()) # Battery: 82 kWh

■ Tip: Use classes to encapsulate data and behaviour. Use inheritance to reuse and extend existing classes.

Follow @CodeWithSiree on Instagram | Happy Coding! rocket


CodeWithSiree | Python: Beginner to Advanced Page 10

12. ambulance Exceptions


Exceptions handle runtime errors using try-except blocks, preventing your program from crashing
unexpectedly.

# Basic try-except
try:
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
# Multiple exceptions + else + finally
try:
num = int(input("Enter a number: "))
result = 100 / num
except ValueError:
print("Invalid input — not a number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print(f"Result: {result}") # runs if no exception
finally:
print("Always runs — cleanup here")
# Raise a custom exception
class InsufficientFundsError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError("Not enough funds!")
return balance - amount

■ Tip: Use exceptions to handle errors gracefully. Always clean up resources in finally.

13. gear Overloading


Method overloading allows defining multiple behaviours for the same method. Python achieves this via
default parameters and operator overloading.

Follow @CodeWithSiree on Instagram | Happy Coding! rocket


CodeWithSiree | Python: Beginner to Advanced Page 11

# Method overloading via default parameters


class Calculator:
def add(self, a, b, c=None):
if c is not None:
return a + b + c
return a + b
calc = Calculator()
print([Link](5, 10)) # 15
print([Link](5, 10, 15)) # 30
# Operator overloading
class Vector:
def __init__(self, x, y):
self.x = x; self.y = y
def __add__(self, other):
return Vector(self.x+other.x, self.y+other.y)
def __str__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(1, 2); v2 = Vector(3, 4)
print(v1 + v2) # Vector(4, 6)

■ Tip: Use operator overloading (__add__, __eq__, __lt__) to make custom classes feel native and intuitive.

Follow @CodeWithSiree on Instagram | Happy Coding! rocket


CodeWithSiree | Python: Beginner to Advanced Page 12

14. recycle Iterators


An iterator allows you to traverse through all elements of a collection one by one. Any object with __iter__
and __next__ is an iterator.

# Using built-in iter()


numbers = [1, 2, 3]
iterator = iter(numbers)
print(next(iterator)) # 1
print(next(iterator)) # 2
print(next(iterator)) # 3
# next() on exhausted iterator raises StopIteration
# Custom iterator class
class CountDown:
def __init__(self, start):
[Link] = start
def __iter__(self):
return self
def __next__(self):
if [Link] <= 0:
raise StopIteration
[Link] -= 1
return [Link] + 1
for n in CountDown(3):
print(n) # 3, 2, 1

■ Tip: Use for loops to iterate over iterables — they call iter() and next() automatically behind the scenes.

15. gear Generators


Generators yield items one at a time using the yield keyword, making them memory-efficient for large
datasets.

# Generator function
def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1
counter = count_up_to(5)
for number in counter:
print(number) # 1, 2, 3, 4, 5
# Generator expression (like list comp but lazy)
squares_gen = (x**2 for x in range(1_000_000))
print(next(squares_gen)) # 0 — fetches only one item
# Reading a huge file line by line
def read_lines(filepath):
with open(filepath) as f:
for line in f:
yield [Link]()

Follow @CodeWithSiree on Instagram | Happy Coding! rocket


CodeWithSiree | Python: Beginner to Advanced Page 13

■ Tip: Use generators for large datasets to optimise memory usage — they produce values on demand, not all
at once.

Follow @CodeWithSiree on Instagram | Happy Coding! rocket


CodeWithSiree | Python: Beginner to Advanced Page 14

16. memo List Comprehensions


List comprehensions provide a concise, readable way to create lists. They replace multi-line loops with a
single expressive line.

# Basic list comprehension


squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# With condition (filter)
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# Nested list comprehension (flatten 2D list)
matrix = [[1,2,3],[4,5,6],[7,8,9]]
flat = [n for row in matrix for n in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Dict and set comprehensions
word_len = {w: len(w) for w in ['python','java','go']}
# {'python': 6, 'java': 4, 'go': 2}
unique_sq = {x**2 for x in [-2,-1,0,1,2]}
# {0, 1, 4}

■ Tip: Use list comprehensions for cleaner and more concise code. Prefer them over map/filter when
readability matters.

17. magnifier Regular Expressions


Regular expressions (regex) are used for string matching, searching, and manipulation using a pattern
syntax.

import re
# Search for a pattern
text = "The rain in Spain"
match = [Link](r"\bS\w+", text) # word starting with S
print([Link]()) # Spain
# Find all matches
emails = "alice@[Link] and bob@[Link]"
found = [Link](r"[\w.]+@[\w.]+", emails)
print(found) # ['alice@[Link]', 'bob@[Link]']
# Replace / substitute
result = [Link](r"\d+", "NUM", "I have 3 cats and 10 dogs")
print(result) # I have NUM cats and NUM dogs
# Validate email format
def is_valid_email(email):
pattern = r'^[\w.-]+@[\w.-]+\.\w{2,}$'
return bool([Link](pattern, email))
print(is_valid_email("alice@[Link]")) # True
print(is_valid_email("not-an-email")) # False

Follow @CodeWithSiree on Instagram | Happy Coding! rocket


CodeWithSiree | Python: Beginner to Advanced Page 15

■ Tip: Keep regex patterns simple for better readability. Use raw strings (r'...') to avoid double-escaping
backslashes.

Follow @CodeWithSiree on Instagram | Happy Coding! rocket


CodeWithSiree | Python: Beginner to Advanced Page 16

18. recycle Serialization


Serialization converts an object into a format that can be saved to disk or transmitted over a network. JSON
is the most common format.

import json
# Python dict → JSON string
data = {"name": "Alice", "age": 25, "skills": ["Python","SQL"]}
json_str = [Link](data, indent=2)
print(json_str)
# JSON string → Python dict
loaded = [Link](json_str)
print(loaded["name"]) # Alice
# Save to file
with open("[Link]", "w") as f:
[Link](data, f, indent=2)
# Load from file
with open("[Link]") as f:
loaded_from_file = [Link](f)
# Pickle for Python-only serialization
import pickle
with open("[Link]","wb") as f:
[Link](data, f)

■ Tip: Use JSON for human-readable, cross-language serialization. Use pickle only for Python-specific
objects.

19. grid Partial Functions


Partial functions let you fix some arguments of a function and create a new, simpler function from it.

from functools import partial


def multiply(x, y):
return x * y
# Fix x=2 → create a 'double' function
double = partial(multiply, 2)
triple = partial(multiply, 3)
print(double(5)) # 10
print(triple(5)) # 15
# Practical: power function
import math
log2 = partial([Link], base=2)
log10 = partial([Link], base=10)
print(log2(8)) # 3.0
print(log10(100)) # 2.0
# Use with map
numbers = [1, 2, 3, 4, 5]
doubled = list(map(partial(multiply, 2), numbers))
print(doubled) # [2, 4, 6, 8, 10]

Follow @CodeWithSiree on Instagram | Happy Coding! rocket


CodeWithSiree | Python: Beginner to Advanced Page 17

■ Tip: Use partial functions to simplify frequently used functions by pre-filling common arguments.

Follow @CodeWithSiree on Instagram | Happy Coding! rocket


CodeWithSiree | Python: Beginner to Advanced Page 18

20. lock Closures


A closure is a function that remembers variables from its enclosing scope even after that scope has finished
executing.

# Basic closure
def outer_function(msg):
def inner_function():
print(msg) # remembers 'msg' from outer
return inner_function
greet = outer_function("Hello")
greet() # Output: Hello
# Counter closure — stateful function
def make_counter(start=0):
count = [start] # list so it's mutable in closure
def increment():
count[0] += 1
return count[0]
return increment
counter = make_counter()
print(counter()) # 1
print(counter()) # 2
print(counter()) # 3
# Each call creates independent closure
c1 = make_counter(10)
c2 = make_counter(100)
print(c1(), c2()) # 11 101

■ Tip: Use closures to create functions with preserved state — a lightweight alternative to a full class.

21. cookie Decorators


Decorators modify the behaviour of a function or class without changing its source code. They use the @
syntax.

Follow @CodeWithSiree on Instagram | Happy Coding! rocket


CodeWithSiree | Python: Beginner to Advanced Page 19

# Basic decorator
def my_decorator(func):
def wrapper():
print("Before the function.")
func()
print("After the function.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
# Before the function.
# Hello!
# After the function.
# Practical decorator: measure execution time
import time
from functools import wraps
def timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = [Link]()
result = func(*args, **kwargs)
end = [Link]()
print(f"{func.__name__} took {end-start:.4f}s")
return result
return wrapper
@timer
def slow_function():
[Link](0.5)
slow_function() # slow_function took 0.5001s

■ Tip: Use decorators to add reusable functionality (logging, timing, auth) without modifying the original
function.

Follow @CodeWithSiree on Instagram | Happy Coding! rocket


CodeWithSiree | Python: Beginner to Advanced Page 20

Happy Coding! rocket


This comprehensive guide covers all essential Python concepts from
beginner to advanced level with real-world examples.

Follow for more content

@CodeWithSiree | Instagram

Follow @CodeWithSiree on Instagram | Happy Coding! rocket

You might also like