0% found this document useful (0 votes)
1 views33 pages

Python_Notes_Basic_to_Advanced

This document provides comprehensive notes on Python programming, covering topics from basic to advanced levels. It includes installation instructions, data types, control structures, functions, and more, making it suitable for both beginners and advanced learners. The content is structured in a clear manner, with practical examples to facilitate understanding.

Uploaded by

rthakur200412
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)
1 views33 pages

Python_Notes_Basic_to_Advanced

This document provides comprehensive notes on Python programming, covering topics from basic to advanced levels. It includes installation instructions, data types, control structures, functions, and more, making it suitable for both beginners and advanced learners. The content is structured in a clear manner, with practical examples to facilitate understanding.

Uploaded by

rthakur200412
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 PROGRAMMING

Complete Notes: Basic to Advanced

Written in Simple, Easy-to-Understand Language

For Beginners → Advanced Learners


Table of Contents

1. Introduction to Python

2. Installing Python and Setup

3. Variables and Data Types

4. Operators

5. Strings in Detail

6. Lists

7. Tuples

8. Sets

9. Dictionaries

10. Conditional Statements (if/elif/else)

11. Loops (for, while)

12. Functions

13. Lambda Functions & map/filter/reduce

14. Comprehensions

15. String Formatting

16. File Handling

17. Exception Handling

18. Object-Oriented Programming (OOP)

19. Modules and Packages

20. Iterators and Generators

21. Decorators

22. Regular Expressions

23. Working with Dates and Time

24. *args and **kwargs

25. Context Managers (with statement)

26. Working with JSON

27. Multithreading and Multiprocessing (Intro)

28. Virtual Environments and pip

29. Python Best Practices (PEP 8)

30. Mini Project: Putting It All Together


1. Introduction to Python

What is Python?

Python is a simple, readable, and powerful programming language created by Guido van Rossum and released in 1991. It is called a "high-level" language
because it is written in a way that is close to human language, instead of complicated machine instructions.

Think of Python like giving instructions to a very obedient friend, one step at a time, in plain English-like sentences. That is exactly what a Python program looks
like.

Why Learn Python?

Easy to Read and Write: Python's syntax looks almost like English.
Beginner Friendly: It is one of the best first languages to learn.
Extremely Versatile: Used in web development, data science, artificial intelligence, automation, game development, and more.
Huge Community: Millions of developers, endless tutorials, and free libraries.
Free and Open Source: Anyone can download and use it without paying anything.

Where is Python Used?

Field Example Use

Web Development Django, Flask frameworks

Data Science Pandas, NumPy, Matplotlib

Artificial Intelligence TensorFlow, PyTorch

Automation / Scripting Automating repetitive tasks

Game Development Pygame

Cybersecurity Penetration testing scripts

Simple Analogy: If programming languages were vehicles, Python would be a bicycle - easy to learn, easy to ride, but can still take you very far.

Features of Python

Interpreted: Code runs line by line, which makes it easier to test and debug.
Dynamically Typed: You don't need to declare the data type of a variable.
Object-Oriented: Supports classes and objects.
Cross-Platform: Works on Windows, macOS, and Linux.
2. Installing Python and Setup

Step 1: Download Python

Go to the official website [Link] and download the latest version for your operating system (Windows, Mac, or Linux).

Step 2: Install It

Run the installer. On Windows, make sure to check the box that says "Add Python to PATH" before clicking install. This lets you run Python from anywhere in
the command line.

Step 3: Verify Installation

Open your terminal (Command Prompt, PowerShell, or Terminal) and type:

python --version

Output: Python 3.12.0

Step 4: Choose a Code Editor

You can write Python code in any text editor, but these are popular choices for beginners:

VS Code - free, lightweight, very popular


PyCharm - full-featured, great for larger projects
Jupyter Notebook - great for data science and step-by-step experiments

Your First Python Program

Create a file called [Link] and write:

print("Hello, World!")

Run it in the terminal:

python [Link]

Output: Hello, World!

Congratulations - you just wrote and ran your first Python program!

Python Interactive Shell (REPL)

You can also type Python code directly and see results instantly. Just type python in the terminal and start typing commands one at a time. This is great for
quick testing.
3. Variables and Data Types

What is a Variable?

A variable is like a labeled box where you store information. You give the box a name, and you can put a value inside it, and change that value later.

name = "Ravi"
age = 25
height = 5.9
is_student = True

In Python, you don't need to say what type of data a variable will hold - Python figures it out automatically. This is called dynamic typing.

Rules for Naming Variables

Must start with a letter or underscore (not a number)


Can contain letters, numbers, and underscores
Case-sensitive: age and Age are different variables
Cannot use Python keywords like if , for , class as variable names

Basic Data Types

Type Description Example

int Whole numbers 10, -5, 2024

float Decimal numbers 3.14, -0.5

str Text (string) "Hello"

bool True or False True, False

list Ordered, changeable collection [1, 2, 3]

tuple Ordered, unchangeable collection (1, 2, 3)

dict Key-value pairs {"a": 1}

set Unordered, unique items {1, 2, 3}

Checking the Type

x = 10
print(type(x))

Output: <class 'int'>

Type Conversion

You can convert between types using built-in functions:

a = "10"
b = int(a) # converts string to integer
c = float(b) # converts integer to float
d = str(c) # converts float back to string
print(b, c, d)

Output: 10 10.0 10.0

Easy Tip: Think of int() , float() , and str() as "converter machines" - you feed a value in, and it comes out in the new type.
4. Operators

Arithmetic Operators

Operator Meaning Example Result

+ Addition 5+3 8

- Subtraction 5-3 2

* Multiplication 5*3 15

/ Division (always returns float) 5/2 2.5

// Floor Division (drops decimal) 5 // 2 2

% Modulus (remainder) 5%2 1

** Exponent (power) 5 ** 2 25

Comparison Operators

These compare two values and return True or False .

print(5 > 3) # True


print(5 == 5) # True
print(5 != 3) # True
print(5 <= 4) # False

Logical Operators

Operator Meaning Example

and True if both conditions are true (5 > 3) and (2 > 1) → True

or True if at least one condition is true (5 > 3) or (1 > 2) → True

not Reverses the result not(5 > 3) → False

Assignment Operators

x = 10
x += 5 # same as x = x + 5, now x = 15
x -= 3 # x = 12
x *= 2 # x = 24
x //= 5 # x = 4

Practice: Try predicting the output of 17 % 5 and 17 // 5 before running the code. This helps you understand the difference between modulus and floor division.
5. Strings in Detail

What is a String?

A string is simply text, written inside single quotes '...' or double quotes "..." .

greeting = "Hello, Python!"


name = 'Ravi'

String Indexing and Slicing

Every character in a string has a position (index), starting from 0.

word = "PYTHON"
print(word[0]) # P
print(word[-1]) # N (last character)
print(word[0:3]) # PYT (slicing: start to end-1)
print(word[::-1]) # NOHTYP (reversed string)

Common String Methods

Method Description Example

.upper() Converts to uppercase "hi".upper() → HI

.lower() Converts to lowercase "HI".lower() → hi

.strip() Removes extra spaces " hi ".strip() → "hi"

.replace() Replaces text "hi".replace("h","b") → "bi"

.split() Splits into a list "a,b,c".split(",") → ['a','b','c']

.join() Joins a list into a string ",".join(['a','b']) → "a,b"

.find() Finds position of text "hello".find("l") → 2

len() Length of the string len("hello") → 5

Easy Way to Remember: Strings in Python are like a row of connected beads. Each bead has a position number, and you can pick, cut, or rearrange them using indexing
and slicing.
6. Lists

What is a List?

A list is an ordered collection of items that can be changed (mutable) after creation. Lists can hold different types of data together.

fruits = ["apple", "banana", "cherry"]


mixed = [1, "hello", 3.5, True]

Accessing List Items

print(fruits[0]) # apple
print(fruits[-1]) # cherry
print(fruits[1:3]) # ['banana', 'cherry']

Common List Operations

[Link]("mango") # adds item at the end


[Link](1, "orange") # inserts at a specific position
[Link]("banana") # removes a specific item
[Link]() # removes the last item
[Link]() # sorts the list
[Link]() # reverses the list
print(len(fruits)) # number of items

Looping Through a List

for fruit in fruits:


print(fruit)

Remember: Lists are mutable, meaning you can add, remove, or change items after the list is created. Use square brackets [ ] for lists.
7. Tuples

What is a Tuple?

A tuple is just like a list, but it is immutable - once created, you cannot change, add, or remove items. Tuples use round brackets ( ) .

coordinates = (10, 20)


colors = ("red", "green", "blue")

Why Use a Tuple Instead of a List?

Faster than lists


Protects data from accidental changes
Useful for fixed collections, like coordinates or RGB color values

print(coordinates[0]) # 10
x, y = coordinates # unpacking a tuple
print(x, y) # 10 20

Easy Analogy: A list is like a whiteboard - you can erase and rewrite. A tuple is like a printed page - once written, it stays the same.
8. Sets

What is a Set?

A set is an unordered collection of unique items. Duplicate values are automatically removed.

numbers = {1, 2, 2, 3, 3, 3}
print(numbers) # {1, 2, 3}

Common Set Operations

a = {1, 2, 3}
b = {2, 3, 4}

print([Link](b)) # {1, 2, 3, 4}
print([Link](b)) # {2, 3}
print([Link](b)) # {1}
[Link](5) # add an item
[Link](1) # remove an item

Real-Life Use: Sets are perfect when you want to remove duplicate entries, like getting a list of unique visitors to a website.
9. Dictionaries

What is a Dictionary?

A dictionary stores data as key-value pairs. Instead of accessing items by position (like lists), you access them by their key - similar to looking up a word in a
real dictionary.

student = {
"name": "Ravi",
"age": 25,
"course": "Computer Science"
}

Accessing and Modifying Values

print(student["name"]) # Ravi
student["age"] = 26 # update value
student["grade"] = "A" # add new key-value pair
del student["course"] # remove a key

Useful Dictionary Methods

print([Link]()) # all keys


print([Link]()) # all values
print([Link]()) # all key-value pairs

for key, value in [Link]():


print(key, ":", value)

Easy Analogy: Think of a dictionary as a phone contact list - you look up a name (key) to find the phone number (value), not the other way around.
10. Conditional Statements

If, Elif, Else

Conditional statements let your program make decisions, just like a human would.

age = 20

if age < 13:


print("Child")
elif age < 20:
print("Teenager")
else:
print("Adult")

Output: Adult

Indentation Matters!

Unlike many languages that use curly braces { } , Python uses indentation (spaces) to define blocks of code. This is not optional - incorrect indentation causes
errors.

Rule of Thumb: Always use 4 spaces for each level of indentation, and be consistent throughout your code.

Nested Conditions and Ternary Expressions

# Short-hand if-else (ternary operator)


age = 18
status = "Adult" if age >= 18 else "Minor"
print(status)
11. Loops

The for Loop

Used to repeat an action for each item in a sequence (list, string, range, etc.)

for i in range(5):
print(i)

Output: 0 1 2 3 4

fruits = ["apple", "banana", "cherry"]


for fruit in fruits:
print(fruit)

The while Loop

Repeats a block of code as long as a condition remains true.

count = 0
while count < 5:
print(count)
count += 1

Loop Control Statements

Keyword Purpose

break Stops the loop completely

continue Skips the current iteration and moves to the next

pass Does nothing - used as a placeholder

for i in range(10):
if i == 5:
break # stop loop when i is 5
if i % 2 == 0:
continue # skip even numbers
print(i)

Easy Analogy: A for loop is like reading every page of a book one by one. A while loop is like reading pages until you get tired (condition becomes false).
12. Functions

What is a Function?

A function is a reusable block of code that performs a specific task. Instead of writing the same code again and again, you write it once inside a function and call it
whenever needed.

def greet(name):
print("Hello, " + name + "!")

greet("Ravi")
greet("Anita")

Output: Hello, Ravi! Hello, Anita!

Return Values

def add(a, b):


return a + b

result = add(5, 3)
print(result) # 8

Default Parameters

def greet(name="Guest"):
print("Hello, " + name)

greet() # Hello, Guest


greet("Ravi") # Hello, Ravi

Keyword Arguments

def student_info(name, age):


print(name, "is", age, "years old")

student_info(age=20, name="Ravi") # order doesn't matter

Why Use Functions? Functions make your code organized, reusable, and easier to debug. Instead of repeating code, you write it once and call it many times.
13. Lambda Functions & map/filter/reduce

Lambda Functions

A lambda function is a small, anonymous (unnamed) function written in a single line. It is useful for short, simple operations.

square = lambda x: x * x
print(square(5)) # 25

add = lambda a, b: a + b
print(add(3, 4)) # 7

map() - Apply a Function to Every Item

numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x * x, numbers))
print(squared) # [1, 4, 9, 16]

filter() - Keep Only Items That Match a Condition

numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6]

reduce() - Combine All Items Into One Value

from functools import reduce

numbers = [1, 2, 3, 4]
total = reduce(lambda a, b: a + b, numbers)
print(total) # 10

Easy Analogy: map transforms every item, filter picks only the items you want, and reduce squashes everything into one final answer.
14. Comprehensions

List Comprehension

A short and elegant way to create a list in a single line.

# Normal way
squares = []
for x in range(5):
[Link](x * x)

# Using list comprehension


squares = [x * x for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]

With a Condition

evens = [x for x in range(10) if x % 2 == 0]


print(evens) # [0, 2, 4, 6, 8]

Dictionary Comprehension

squares_dict = {x: x*x for x in range(5)}


print(squares_dict) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Set Comprehension

unique_squares = {x*x for x in [1, -1, 2, -2]}


print(unique_squares) # {1, 4}

Practice: Rewrite this loop as a list comprehension: result = []; for x in range(20): if x % 3 == 0: [Link](x)
15. String Formatting

f-strings (Recommended - Modern Way)

name = "Ravi"
age = 25
print(f"My name is {name} and I am {age} years old.")

Output: My name is Ravi and I am 25 years old.

Formatting Numbers

price = 49.99999
print(f"Price: {price:.2f}") # Price: 50.00

number = 1000000
print(f"{number:,}") # 1,000,000

Older Methods (Good to Know)

# .format() method
print("My name is {} and I am {} years old.".format(name, age))

# % operator (old style)


print("My name is %s and I am %d years old." % (name, age))

Best Practice: Always prefer f-strings in modern Python - they are faster, cleaner, and easiest to read.
16. File Handling

Opening and Reading a File

file = open("[Link]", "r") # r = read mode


content = [Link]()
print(content)
[Link]()

The Better Way: Using "with"

Using with automatically closes the file for you, even if an error occurs. This is the recommended way.

with open("[Link]", "r") as file:


content = [Link]()
print(content)
# file is automatically closed here

File Modes

Mode Meaning

"r" Read (default) - file must exist

"w" Write - creates new file or overwrites existing

"a" Append - adds to the end of file

"r+" Read and write

Writing to a File

with open("[Link]", "w") as file:


[Link]("Hello, this is my first file write!\n")
[Link]("Python makes file handling easy.")

Reading Line by Line

with open("[Link]", "r") as file:


for line in file:
print([Link]())

Tip: Always use with open(...) instead of manually calling open() and close() . It prevents accidental file corruption or memory leaks.
17. Exception Handling

Why Handle Exceptions?

Sometimes your program runs into unexpected problems, like dividing by zero or trying to open a file that doesn't exist. Instead of crashing, we can "catch" these
errors gracefully.

try, except, else, finally

try:
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print("Division successful:", result)
finally:
print("This always runs, no matter what.")

Output: You can't divide by zero! This always runs, no matter what.

Catching Multiple Exceptions

try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("That's not a valid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")

Raising Your Own Exceptions

def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative!")
return age

check_age(-5) # This will raise an error

Easy Analogy: Think of try/except like wearing a seatbelt - you hope you never need it, but if something goes wrong, it protects your program from crashing.
18. Object-Oriented Programming (OOP)

What is OOP?

Object-Oriented Programming is a way of organizing code around objects (real-world things) instead of just functions and logic. Each object is created from a
class, which acts like a blueprint.

Classes and Objects

class Dog:
def __init__(self, name, breed):
[Link] = name
[Link] = breed

def bark(self):
print(f"{[Link]} says Woof!")

# Creating objects (instances) of the class


dog1 = Dog("Rex", "Labrador")
[Link]()

Output: Rex says Woof!

__init__ is a special method called a constructor - it runs automatically when a new object is created, to set up its initial values. self refers to the current
object itself.

The Four Pillars of OOP

1. Encapsulation

Bundling data and methods together inside a class, and restricting direct access to some details.

class BankAccount:
def __init__(self, balance):
self.__balance = balance # double underscore = private variable

def deposit(self, amount):


self.__balance += amount

def get_balance(self):
return self.__balance

account = BankAccount(1000)
[Link](500)
print(account.get_balance()) # 1500

2. Inheritance

Allows a class to inherit properties and methods from another class, avoiding repeated code.

class Animal:
def __init__(self, name):
[Link] = name
def speak(self):
print(f"{[Link]} makes a sound.")

class Cat(Animal): # Cat inherits from Animal


def speak(self):
print(f"{[Link]} says Meow!")

c = Cat("Whiskers")
[Link]() # Whiskers says Meow!

3. Polymorphism

Different classes can define the same method name, but each behaves differently.

class Dog:
def speak(self):
print("Woof!")

class Cat:
def speak(self):
print("Meow!")
for animal in [Dog(), Cat()]:
[Link]() # each object responds in its own way

4. Abstraction

Hiding complex implementation details and showing only the essential features.

from abc import ABC, abstractmethod

class Shape(ABC):
@abstractmethod
def area(self):
pass

class Circle(Shape):
def __init__(self, radius):
[Link] = radius
def area(self):
return 3.14 * [Link] ** 2

c = Circle(5)
print([Link]()) # 78.5

Easy Analogy: A class is like a cookie cutter, and objects are the cookies made from it. Each cookie (object) can have its own toppings (data), but they all share the same
shape (structure) from the cutter (class).
19. Modules and Packages

What is a Module?

A module is simply a Python file (.py) containing code - functions, classes, or variables - that you can reuse in other programs.

Using Built-in Modules

import math

print([Link](16)) # 4.0
print([Link]) # 3.14159...

import random
print([Link](1, 10)) # random number between 1 and 10

Importing Specific Items

from math import sqrt, pi


print(sqrt(25)) # 5.0

# import with alias


import numpy as np

Creating Your Own Module

Save this as [Link] :

# [Link]
def add(a, b):
return a + b

Then use it in another file:

import mymath
print([Link](3, 4)) # 7

What is a Package?

A package is simply a folder containing multiple related modules, along with a special __init__.py file. It helps organize large projects.
20. Iterators and Generators

What is an Iterator?

An iterator is an object that lets you go through a collection of items one at a time, using next() .

numbers = [1, 2, 3]
it = iter(numbers)
print(next(it)) # 1
print(next(it)) # 2
print(next(it)) # 3

What is a Generator?

A generator is a special type of function that produces values one at a time, instead of returning them all at once. It uses yield instead of return , which makes
it very memory-efficient for large data.

def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1

for num in count_up_to(5):


print(num)

Output: 1 2 3 4 5

Easy Analogy: A regular function is like handing someone a full basket of fruit all at once. A generator is like handing them one fruit at a time, only when they ask for it -
saving memory and effort.

Generator Expressions

squares = (x*x for x in range(5)) # notice the round brackets


for s in squares:
print(s)
21. Decorators

What is a Decorator?

A decorator is a function that "wraps" another function to add extra functionality, without changing the original function's code.

def my_decorator(func):
def wrapper():
print("Something happens before the function runs.")
func()
print("Something happens after the function runs.")
return wrapper

@my_decorator
def say_hello():
print("Hello!")

say_hello()

Output: Something happens before the function runs. Hello! Something happens after the function runs.

A Practical Example: Timing a Function

import time

def timer(func):
def wrapper(*args, **kwargs):
start = [Link]()
result = func(*args, **kwargs)
end = [Link]()
print(f"{func.__name__} took {end - start:.4f} seconds")
return result
return wrapper

@timer
def slow_function():
[Link](1)

slow_function()

Easy Analogy: A decorator is like a gift wrapper - it doesn't change what's inside the box (the function), but it adds something extra around it (new behavior).
22. Regular Expressions

What is a Regular Expression?

A regular expression (regex) is a pattern used to search, match, or manipulate text. Python's re module handles this.

import re

text = "My phone number is 987-654-3210"


pattern = r"\d{3}-\d{3}-\d{4}"

match = [Link](pattern, text)


if match:
print("Found:", [Link]())

Output: Found: 987-654-3210

Common Regex Symbols

Symbol Meaning

\d Any digit (0-9)

\w Any word character (letters, digits, underscore)

\s Any whitespace

+ One or more repetitions

* Zero or more repetitions

? Zero or one occurrence

^ Start of string

$ End of string

Useful Functions

[Link](r"\d+", "I have 2 cats and 3 dogs") # ['2', '3']


[Link](r"cats", "kittens", "I love cats") # "I love kittens"
[Link](r"Hello", "Hello World") # matches at start
23. Working with Dates and Time

The datetime Module

from datetime import datetime

now = [Link]()
print(now) # current date & time
print([Link], [Link], [Link]) # individual parts

Formatting Dates

formatted = [Link]("%d-%m-%Y %H:%M:%S")


print(formatted) # e.g. 27-07-2026 14:30:00

Common Format Codes

Code Meaning

%Y 4-digit year

%m Month (01-12)

%d Day (01-31)

%H Hour (24-hour format)

%M Minutes

%S Seconds

Calculating Time Differences

from datetime import timedelta

future = now + timedelta(days=10)


print(future) # 10 days from now
24. *args and **kwargs

*args - Accept Any Number of Positional Arguments

def add_all(*args):
return sum(args)

print(add_all(1, 2, 3)) # 6
print(add_all(1, 2, 3, 4, 5)) # 15

**kwargs - Accept Any Number of Keyword Arguments

def print_info(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")

print_info(name="Ravi", age=25, city="Delhi")

Output: name: Ravi age: 25 city: Delhi

Easy Analogy: *args is like a bag that collects extra plain items, and **kwargs is like a bag that collects extra labeled items (key-value pairs).
25. Context Managers (with statement)

Why Context Managers?

Context managers handle setup and cleanup automatically, such as opening and closing files, or connecting and disconnecting from a database. We've already
seen this with file handling.

Creating Your Own Context Manager

class MyContext:
def __enter__(self):
print("Entering the context")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Exiting the context")

with MyContext() as ctx:


print("Inside the block")

Output: Entering the context Inside the block Exiting the context

Using contextlib (Simpler Way)

from contextlib import contextmanager

@contextmanager
def my_context():
print("Start")
yield
print("End")

with my_context():
print("Doing work")
26. Working with JSON

What is JSON?

JSON (JavaScript Object Notation) is a lightweight format for storing and exchanging data. It looks very similar to Python dictionaries, which makes it easy to work
with.

Converting Python to JSON

import json

data = {"name": "Ravi", "age": 25, "skills": ["Python", "SQL"]}


json_string = [Link](data, indent=2)
print(json_string)

Output: { "name": "Ravi", "age": 25, "skills": ["Python", "SQL"] }

Converting JSON to Python

json_data = '{"name": "Ravi", "age": 25}'


python_dict = [Link](json_data)
print(python_dict["name"]) # Ravi

Reading and Writing JSON Files

# Writing
with open("[Link]", "w") as f:
[Link](data, f)

# Reading
with open("[Link]", "r") as f:
loaded_data = [Link](f)
27. Multithreading and Multiprocessing (Intro)

Why Do We Need This?

Normally, Python runs code line by line, one task at a time. Multithreading and multiprocessing let you run multiple tasks at (nearly) the same time - useful for
speeding up programs that wait a lot (like downloading files) or that do heavy computation.

Multithreading Example

Best for tasks that involve waiting, like network requests or file downloads.

import threading
import time

def print_numbers():
for i in range(5):
print(i)
[Link](1)

t1 = [Link](target=print_numbers)
[Link]()
[Link]() # wait for thread to finish

Multiprocessing Example

Best for CPU-heavy tasks, like large calculations, since it uses multiple CPU cores.

from multiprocessing import Process

def square(n):
print(n * n)

p1 = Process(target=square, args=(5,))
[Link]()
[Link]()

Simple Rule: Use threading for tasks that involve waiting (I/O-bound), and multiprocessing for tasks that involve heavy calculations (CPU-bound).
28. Virtual Environments and pip

What is pip?

pip is Python's package manager - it lets you install extra libraries that aren't built into Python.

pip install requests


pip install pandas
pip uninstall requests
pip list # see all installed packages

What is a Virtual Environment?

A virtual environment is an isolated space for a specific project, so that its packages don't conflict with other projects on your computer.

# Create a virtual environment


python -m venv myenv

# Activate it (Windows)
myenv\Scripts\activate

# Activate it (Mac/Linux)
source myenv/bin/activate

# Install packages inside the environment


pip install requests

# Deactivate when done


deactivate

Easy Analogy: A virtual environment is like having a separate toolbox for each project, so tools from one project never get mixed up with another.

[Link]

This file lists all the packages a project needs, so others can install them easily.

# Save current packages to a file


pip freeze > [Link]

# Install all packages from that file


pip install -r [Link]
29. Python Best Practices (PEP 8)

What is PEP 8?

PEP 8 is the official style guide for writing clean, readable Python code. Following it makes your code easier for others (and yourself) to understand.

Key Guidelines

Use 4 spaces per indentation level (not tabs)


Use snake_case for variable and function names: my_variable , not MyVariable
Use PascalCase for class names: class MyClass:
Use UPPER_CASE for constants: MAX_SIZE = 100
Keep lines under 79-99 characters when possible
Add spaces around operators: x = 5 + 3 , not x=5+3
Write meaningful variable names: total_price instead of tp
Add comments to explain "why", not just "what"

Good vs Bad Example

# Bad
def f(x,y):
return x+y

# Good
def add_numbers(first_number, second_number):
"""Returns the sum of two numbers."""
return first_number + second_number

Tip: Tools like black and flake8 can automatically check and format your code to follow PEP 8 standards.
30. Mini Project: Putting It All Together

A Simple Contact Book Program

This mini project uses variables, dictionaries, functions, loops, conditionals, file handling, and exception handling - combining everything you've learned.

import json

def load_contacts():
try:
with open("[Link]", "r") as f:
return [Link](f)
except FileNotFoundError:
return {}

def save_contacts(contacts):
with open("[Link]", "w") as f:
[Link](contacts, f, indent=2)

def add_contact(contacts):
name = input("Enter name: ")
phone = input("Enter phone number: ")
contacts[name] = phone
save_contacts(contacts)
print(f"{name} added successfully!")

def view_contacts(contacts):
if not contacts:
print("No contacts found.")
for name, phone in [Link]():
print(f"{name}: {phone}")

def main():
contacts = load_contacts()
while True:
print("\n1. Add Contact\n2. View Contacts\n3. Exit")
choice = input("Choose an option: ")

if choice == "1":
add_contact(contacts)
elif choice == "2":
view_contacts(contacts)
elif choice == "3":
print("Goodbye!")
break
else:
print("Invalid choice, try again.")

if __name__ == "__main__":
main()

What This Project Teaches: Functions for organization, dictionaries for data storage, JSON for saving data permanently, loops for repeated menus, conditionals for
decision-making, and the if __name__ == "__main__": pattern, which ensures code only runs when the file is executed directly (not when imported).

Congratulations!

You have now covered Python from the very basics all the way to advanced concepts like decorators, generators, and multithreading. The best way to truly learn
programming is by writing code yourself - so open your editor, and start building small projects using what you've learned here. Practice consistently, be patient
with mistakes, and enjoy the process!

You might also like