0% found this document useful (0 votes)
5 views15 pages

Python Training PDF

The document is a comprehensive Python training presentation covering topics from basics to advanced concepts, including syntax, data structures, object-oriented programming, and file handling. It emphasizes hands-on exercises and real-world applications, showcasing Python's versatility in areas like data science, web development, and automation. The presentation also includes best practices and resources for further learning.

Uploaded by

Madhana Gopal P
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)
5 views15 pages

Python Training PDF

The document is a comprehensive Python training presentation covering topics from basics to advanced concepts, including syntax, data structures, object-oriented programming, and file handling. It emphasizes hands-on exercises and real-world applications, showcasing Python's versatility in areas like data science, web development, and automation. The presentation also includes best practices and resources for further learning.

Uploaded by

Madhana Gopal P
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 Training Presentation

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

Made with Genspark


Table of Contents
1 Introduction & Overview 8 File Handling & Exceptions

2 Python Basics & Syntax 9 Popular Libraries Overview

3 Variables & Data Types 10 Web Development Frameworks

4 Control Flow 11 Development Tools & Environment

5 Functions & Modules 12 Practical Coding Examples

6 Data Structures 13 Best Practices & Code Style

7 Object-Oriented Programming 14 Testing & Debugging

15 Next Steps & Resources

Made with Genspark


Introduction & Overview

What is Python? Where Python Shines


A high-level, interpreted programming language created by Guido van Rossum in 1991

Emphasizes code readability with its notable use of significant whitespace


📊 Data Science & Analytics
NumPy, Pandas, Matplotlib

Multi-paradigm: supports object-oriented, imperative, functional and procedural programming

🧠 AI & Machine Learning

Key Features TensorFlow, PyTorch, scikit-learn

🌐
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

Python in Action Scripting, testing, deployment

# Simple Python example


print("Hello, Python World!") Python is the #1
Most popular programming language in 2025

# Quick calculation — TIOBE Index & GitHub Octoverse

result = sum(range(1, 101))


print(f"Sum of numbers 1-100: {result}")

Made with Genspark


Python Basics & Syntax

Clean & Readable Syntax Python Comments


Python code reads like English with minimal syntax symbols
# This is a single-line comment
No semicolons or curly braces required to define code blocks
"""
Statements typically written one per line (although multiple statements per line are possible)
This is a multi-line comment
or docstring that can span
Indentation Rules multiple lines
"""
# Python uses indentation to define blocks
if x > 0:
print("x is positive") # 4 spaces indentation Basic Syntax Rules

📝
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)

Standard practice is 4 spaces per indentation level

Inconsistent indentation causes IndentationError


🔍 Line Continuation
Use \ or parentheses () for long lines

Hello World Example


🚫 Keywords
Cannot use reserved words like if, for, class as
# The simplest Python program
identifiers
print("Hello, World!")

# A more interactive version


name = input("Enter your name: ")
🔠 Naming Convention
Use snake_case for variables and functions
print(f"Hello, {name}!")

Made with Genspark


Variables & Data Types

Python Variables Type Conversion


Variables are dynamically typed - no need to declare type Convert between data types using built-in
functions:
Created when you first assign a value

Can change type during program execution String to Number

# Variable assignment s = "42"


name = "Python" # str x = int(s) # x = 42
age = 32 # int y = float(s) # y = 42.0
height = 1.65 # float
is_awesome = True # bool Number to String

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

Float # Check variable type


Numbers with decimal points or scientific notation
x = 42
Examples: 3.14, -0.001, 2e5
print(type(x)) #

String (str) # Check if instance of type


Text enclosed in single, double, or triple quotes isinstance(x, int) # True
Examples: "hello", 'Python', """Multiline""" isinstance(x, str) # False

Boolean (bool)
True or False values, used for logical operations
Examples: True, False

Made with Genspark


Control Flow (if/else, loops)

Conditional Statements Advanced Flow Control


if - Executes a block when condition is True

elif - Checks another condition if previous conditions were False


🔄 Nested Loops
Creating loops within loops for multi-dimensional data
processing
else - Executes when all conditions are False
for i in range(3):
# Example of conditional statements for j in range(2):
print(f"({i},{j})")
x = 10

if x > 20:
print("x is greater than 20")
🔁 Loop with else

elif x > 5: Run a block when loop condition becomes False

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}")

# While loop example


Hands-on Exercise
count = 0
Write a program that prints numbers from 1 to 20,
while count < 5: but:
print(f"Count: {count}")
For multiples of 3, print "Fizz" instead
count += 1 For multiples of 5, print "Buzz" instead
For multiples of both 3 and 5, print "FizzBuzz"

Control Keywords
break - Exit the current loop completely

continue - Skip the current iteration and move to next

pass - Null operation, placeholder for future code


Made with Genspark
Functions & Modules

Defining Functions Working with Modules


Functions are defined using the def keyword followed by the function name and parameters

Function body is indented, with an optional docstring to document the function


📦 Import Modules
import math
from datetime import datetime
Return values are specified with the return statement (default return is None )

Function Arguments 🏷️ Aliasing


import numpy as np
Positional Arguments Keyword Arguments from pandas import DataFrame as DF
Regular arguments passed by position Arguments passed by name

Default Arguments
Parameters with default values
*args, **kwargs
Variable-length argument lists
🔍 Using Module Functions
[Link](16) # 4.0
[Link]()
Function Example

# Function with default argument Creating Your Own Module


def greet(name, greeting="Hello"):
"""Return a greeting message""" # Save as [Link]
def add(a, b):
return f"{greeting}, {name}!"
return a + b

# Calling the function def multiply(a, b):


print(greet("Alice")) # Hello, Alice! return a * b
print(greet("Bob", "Welcome")) # Welcome, Bob!
# In another file
import mymodule
result = [Link](5, 3) # 8

Python Standard Library


100+ built-in modules
math, os, sys, datetime, json, random...

Made with Genspark


Data Structures (Lists, Dictionaries, Tuples, Sets)

Lists Practical Examples


Ordered, mutable collections of items List Operations
Created with square brackets [] or list()
fruits = ['apple', 'banana', 'cherry']
Common methods: append(), insert(), remove(), pop(), sort() [Link]('orange') # Add to end
Indexing starts at 0, supports slicing [start:end:step] [Link](1, 'mango') # Insert at position
popped = [Link]() # Remove & return last item
[Link]() # Sort in-place
Dictionaries print(fruits[0]) # First item
print(fruits[-1]) # Last item
Unordered key-value pairs (hash maps)
print(fruits[1:3]) # Slicing
Created with curly braces {} or dict()

Access, add or modify by key: dict[key] = value


Dictionary Operations
Common methods: keys(), values(), items(), get(), update()
student = {
'name': 'John',
Tuples Sets 'age': 21,
Ordered, immutable sequences Unordered collections of unique items 'courses': ['Math', 'CS']
}
Created with parentheses () or tuple() Created with set() or {x, y, z} print(student['name']) # Access by key
Faster than lists, useful for fixed data Methods: add(), remove(), union(), student['phone'] = '555-5555' # Add new key-value
Methods: count(), index() intersection() courses = [Link]('courses', []) # Safe access
Useful for removing duplicates and set for key, value in [Link]():
operations print(f"{key}: {value}")

Comprehensions When to Use Each Structure

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

name_ages = {'Alice': 25, 'Bob': 30, 'Charlie': 35} Tuples


name_to_years = {name: age*365 for name, age in name_ages.items()} For immutable data like coordinates or database records

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).

Made with Genspark


Object-Oriented Programming

Classes & Objects OOP Concepts


Class: Blueprint for creating objects with shared attributes and methods

Object: Instance of a class, containing real data and behavior


🔄 Inheritance
Creating a new class that inherits attributes and
methods from an existing class

Methods & Attributes class Labrador(Dog):


def __init__(self, name, age, color):
Attributes: Variables that store data within a class super().__init__(name, age)
[Link] = color
Methods: Functions defined within a class that describe behaviors

Self: Reference to the instance of the class, used to access variables


🔒 Encapsulation
Restricting access to methods and variables by
Class Example
enclosing them within a single unit

# Define a simple class class BankAccount:


def __init__(self, balance):
class Dog: self.__balance = balance # Private
# Class variable shared by all instances
def deposit(self, amount):
species = "Canis familiaris" self.__balance += amount

# 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

Keep classes focused and specialized

Made with Genspark


File Handling & Exceptions

File Operations Exception Handling


Python provides built-in functions for creating, reading, updating, and Exceptions are runtime errors that disrupt normal program flow
deleting files
Python's try-except blocks gracefully handle errors
File modes: 'r' (read), 'w' (write), 'a' (append), 'b' (binary)
Specific exception types can be caught and handled differently
Always close files to prevent resource leaks

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")

with open('[Link]', 'r') as f:


# Read all content
Common Exceptions
content = [Link]()
FileNotFoundError TypeError
# Or read line by line When a file doesn't exist Invalid operation for type

[Link](0)
ValueError KeyError
for line in f: Invalid value for operation Non-existent dictionary key
print([Link]())

Made with Genspark


Popular Libraries Overview

Data Science Ecosystem Essential Libraries


TensorFlow / PyTorch
NumPy Pandas Deep learning frameworks for neural networks
Fundamental package for scientific computing Data analysis and manipulation tool
Scikit-learn
import numpy as np import pandas as pd Machine learning algorithms and tools

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

Why Python Libraries Matter


Matplotlib Requests
Comprehensive visualization library HTTP library for API calls • Avoid reinventing the wheel

• Access optimized, tested implementations


import [Link] as plt import requests
• Benefit from community contributions

# Create simple plot # Make HTTP request • Faster development cycles


[Link]([1, 2, 3, 4], [1, 4, 9, 16]) response = [Link](
• Industry-standard tools and practices
[Link]('X axis') '[Link]
[Link]('Y axis') data = [Link]()
[Link]('Sample Plot') print(f"Status: {response.status_code}")
PyPI Statistics

350,000+
Machine Learning Python packages available in 2025

from sklearn.model_selection import train_test_split


from [Link] import RandomForestClassifier

# Train a simple model


X_train, X_test, y_train, y_test = train_test_split(X, y)
model = RandomForestClassifier()
[Link](X_train, y_train)
accuracy = [Link](X_test, y_test)

Made with Genspark


Web Development Frameworks

Popular Python Web Frameworks Framework Comparison


Python offers a variety of web frameworks to suit different project needs, from complex full-stack Performance
applications to lightweight APIs.
FASTAPI Fastest

Django Est. 2005 • Full-stack framework FLASK Medium

Tagline: "The web framework for perfectionists with deadlines"


DJANGO Standard
Batteries-included approach ORM for database operations

Admin interface built-in MTV architecture pattern

Ideal Use Cases

Flask Est. 2010 • Micro-framework Django


• Content-heavy sites
Tagline: "Web development, one drop at a time" • Admin-heavy applications
• Complex database operations
Lightweight and flexible Extensible with add-ons
• Enterprise applications
Werkzeug and Jinja2 based Simple routing system

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

Built on Starlette & Pydantic Auto-generated docs (Swagger)

Native async support Data validation & serialization FastAPI


• RESTful APIs
• High-performance applications
• Microservices architecture
• Real-time applications

Made with Genspark


Development Tools & Environment

Python IDEs Comparison Package Management

Feature PyCharm VS Code


pip Python Default

Setup Full-featured out-of-box Requires extensions Python-specific package manager

Simple syntax: pip install package


Performance Heavier, more resources Lighter, faster startup
Uses [Link] for dependencies

Debugging Advanced, built-in Good with extensions

Intellisense Excellent, context-aware Very good with extensions conda Cross-platform

Cost Pro: Paid, Community: Free Free, open-source Language-agnostic package manager

Better for data science packages

Built-in environment management


PyCharm VS Code
Best for: dedicated Python development, larger Best for: multi-language development, flexibility
projects
Git Integration
Both PyCharm and VS Code offer excellent Git integration:
Virtual Environments
Isolate dependencies for different projects Commit & Push Branch Management
Visual interface for Git Create, switch, merge

# Creating virtual environments operations branches

# 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

Project Isolation Reproducibility


Prevents dependency conflicts Share consistent environments

Made with Genspark


Practical Coding Examples Python Training

Hands-on Python Challenges

 Data Structures Challenge  Functions Challenge

Problem: Reverse the keys and values in a dictionary Problem: Create a function that counts words in a sentence

ascii_dict = {'A': 65, 'B': 66, 'C': 67} def word_counter(sentence):


# Your task: Create a new dict with values as keys # Your code here
# Expected output: {65: 'A', 66: 'B', 67: 'C'} pass

# Test with:
text = "Python is amazing and powerful"
# Expected output: 5

 OOP Challenge  File I/O Challenge

Problem: Create a simple Bank Account class Problem: Read a file and count lines, words, chars

class BankAccount: def file_stats(filename):


# Your code here # Your code here
pass pass

# Should support: # Expected output: (lines, words, chars)


# - Initialize with balance # For "[Link]" containing:
# - deposit() and withdraw() methods # Hello world
# - get_balance() method # Python is fun
# Result: (2, 5, 20)

Try these exercises to reinforce your Python skills!


More examples available at [Link] Made with Genspark
Best Practices, Testing & Next Steps

Python Best Practices Your Python Learning Path


Follow PEP 8 style guide for clean, readable code Master the Fundamentals
1
Use meaningful variable and function names Syntax, data structures, functions, modules

Write docstrings for functions and classes 2 Build Projects


Apply knowledge to real-world problems
Leverage virtual environments for project isolation
3 Specialize
Data science, web dev, automation, etc.
# Good practice example
def calculate_area(radius):
4 Contribute
"""
Join open source, teach others
Calculate the area of a circle.

Args: Recommended Resources


radius (float): The radius of the circle
[Link] Documentation
Returns: Official language reference & tutorials
float: The area of the circle
"""
Real Python
import math
In-depth tutorials & courses
return [Link] * radius ** 2

Python Discord Community


Connect with other learners
Testing & Debugging
GitHub Repositories
Unit Testing Debugging Practice with real-world code
pytest, unittest pdb, IDE debuggers

Code Quality Type Checking


flake8, pylint mypy, type hints

"Code without tests is broken by design." — Jacob Kaplan-Moss


Made with Genspark

You might also like