Python Training PDF
Python Training PDF
d
Comprehensive Python Programming: From Fundamentals to Advancedef hello_py
thon():
print("W
elcome t
Applications return "
Let's st
o Python
!")
art codi
ng"
# Begin
your Pyt
hon jour
Master Python programming through hands-on exercises, best practices, and real-world t = hello_p
r e s u l ney
ython()
examples
🌐
Simple & Readable Extensive Libraries
Clean syntax resembling English Rich standard library and third-party packages Web Development
Django, Flask, FastAPI
Cross-Platform Beginner-Friendly
Runs on Windows, macOS, Linux, etc. Ideal for learning programming
⚙️ Automation
📝
if y > 0:
print("y is also positive") # 8 spaces for nested block Case Sensitive
Variable name is different from Name
Indentation defines code blocks (no curly braces)
n = 3.14
# Same variable can change type
s = str(n) # s = "3.14"
x = 10 # x is an integer
x = "hello" # now x is a string
To Boolean
x = bool(1) # True
Core Data Types y = bool("") # False
z = bool(0) # False
Integer (int)
Whole numbers without decimal points
Examples: 42, -7, 0
Type Checking
Boolean (bool)
True or False values, used for logical operations
Examples: True, False
if x > 20:
print("x is greater than 20")
🔁 Loop with else
print("x is greater than 5 but not greater than 20") for n in range(2, 10):
else: for x in range(2, n):
if n % x == 0:
print("x is 5 or less") break
else:
# loop fell through
print(f"{n} is prime")
Loops
📋
For Loops While Loops
Iterate over sequences (lists, tuples, strings) Execute as long as a condition is True Practical Applications
Data processing and transformation
# For loop example Menu-driven programs
fruits = ["apple", "banana", "cherry"] Game development logic
for fruit in fruits: Algorithm implementation
print(f"I like {fruit}")
Control Keywords
break - Exit the current loop completely
Default Arguments
Parameters with default values
*args, **kwargs
Variable-length argument lists
🔍 Using Module Functions
[Link](16) # 4.0
[Link]()
Function Example
Lists
# List comprehension
When order matters and items might change
squares = [x**2 for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Dictionaries
# Dictionary comprehension When you need key-value mapping for fast lookups
Sets
# Set comprehension
When you need unique values or set operations
unique_letters = {letter for letter in 'mississippi'} # {'m', 'i', 's', 'p'}
💡 Performance Tip
For large collections, choosing the right data structure can
dramatically impact performance. Use dictionaries and sets for
lookups (O(1) complexity) instead of lists (O(n) complexity).
# Initializer / Constructor
def __init__(self, name, age):
# Instance variables unique to each instance
🔄 Polymorphism
Using a single type entity to represent different types
[Link] = name in different contexts
[Link] = age
def pet_speak(pet):
return [Link]() # Works with any class that h
# Instance method
def description(self):
return f"{[Link]} is {[Link]} years old"
Best Practice
# Create an object (instance) Use descriptive class and method names
buddy = Dog("Buddy", 5) Follow PEP 8 naming conventions
print([Link]()) # Output: Buddy is 5 years old
Implement proper encapsulation
Try-Except Structure
The 'with' Statement
try:
Automatically handles resource cleanup, even if exceptions occur:
# Code that might raise an exception
result = 10 / 0
# Recommended way to handle files
except ZeroDivisionError:
with open('[Link]', 'w') as file:
# Handle specific exception
[Link]('Hello, Python!')
print("Can't divide by zero!")
except Exception as e:
# File is automatically closed after the block
# Catch any other exceptions
print(f"Error occurred: {e}")
File Handling Example else:
# Runs if no exceptions occur
print("Division successful")
# Reading and writing files
finally:
with open('[Link]', 'w') as f:
# Always executes
[Link]('Line 1\nLine 2\nLine 3')
print("This always runs")
[Link](0)
ValueError KeyError
for line in f: Invalid value for operation Non-existent dictionary key
print([Link]())
Seaborn
# Create array and perform operations # Create and query DataFrame
Statistical data visualization based on matplotlib
arr = [Link]([1, 2, 3, 4, 5]) df = [Link]({'A': [1, 2, 3],
print([Link]()) # 3.0 'B': ['a', 'b', 'c']})
BeautifulSoup
print(arr * 2) # [2 4 6 8 10] print([Link]())
Web scraping and HTML parsing
Pillow (PIL)
Image processing capabilities
Visualization & Web
350,000+
Machine Learning Python packages available in 2025
Flask
• Small to medium apps
FastAPI Est. 2018 • Modern API framework • Microservices
• Prototyping
Tagline: "High performance, easy to learn, fast to code"
• Simple static websites
Cost Pro: Paid, Community: Free Free, open-source Language-agnostic package manager
# Built-in venv
python -m venv myenv Diff Viewer Resolve Conflicts
Visual file comparison Interactive conflict resolution
# Activating (Windows)
myenv\Scripts\activate
Development Best Practice
# Activating (macOS/Linux) Use Git for version control + virtual environments for dependencies
source myenv/bin/activate
Problem: Reverse the keys and values in a dictionary Problem: Create a function that counts words in a sentence
# Test with:
text = "Python is amazing and powerful"
# Expected output: 5
Problem: Create a simple Bank Account class Problem: Read a file and count lines, words, chars