Week 01 – Python
Programming Basics
Disclaimer
The content is curated from
online/offline resources and used for
educational purpose only
Meet Your Instructor – Vignesh Muthuvelan
Job Role: Master Trainer
Experience: 5+ Years in Tech Training & Curriculum Development
Professional Summary
• Conducts engaging sessions on Front-End Web Development: HTML, CSS,
JavaScript, Bootstrap, ReactJs.
• Facilitator of programs in IBM Cloud, Python, AI, ML, DL, R Programming,
UI/UX, Gen AI
• Experienced in teaching diverse audiences: Arts & Engineering students,
faculty members, and working professionals.
• Delivers training in both online and offline formats
• Strong emphasis on hands-on learning, conceptual clarity, and career
alignment [Link]
/vignesh-muthuvelan
Welcome to Py thon
Programming
Your journey into the world of programming starts here. Python is one of the most
beginner-friendly and powerful languages you'll ever learn.
What We'll Explore Together
Python Setup & Basics Core Programming Concepts
Get Python running on your computer and write your first lines of code Master data types, variables, conditionals, and loops
Functions & Modules Hands-On Practice
Organize code efficiently and reuse powerful tools Apply what you've learned with real-world coding exercises
What We'll Explore Together
File Handling Fundamentals Working with TXT Files Mastering CSV Files
Understanding how Python reads and writes Reading, writing, and appending plain text Processing structured data with rows and
data columns
Handling JSON Data Hands-On Practice
Working with API responses and nested data Build your own data logging script
Introduction to Python
Created by Guido van Rossum in 1989, Python is a high-level, interpreted, and
object-oriented language celebrated for its readability and broad applicability.
It's the language of choice for tech giants like Google, NASA, and YouTube,
powering essential systems and innovative projects.
From Artificial Intelligence and Natural Language Processing to Neural
Networks, Python is at the forefront of advanced computer science, shaping the
future of technology.
Why Python? It Powers the World
Universal & Versatile
Python runs everywhere—from web servers to AI research labs.
Companies like Google, Netflix, and NASA rely on Python daily.
Perfect for beginners: Python reads almost like English, making
it easier to learn than most programming languages.
Career boost: Python developers are in high demand across
industries including data science, web development, automation,
and machine learning.
Setting Up Your Python Environment
Choose Your Code Editor
Download Python
Install VS Code (recommended for beginners) or PyCharm
Visit [Link] and download Python 3.11 or later. Make sure to Community Edition. These editors make coding much easier with
check "Add Python to PATH" during installation! helpful features.
Write "Hello, World!"
Verify Installation
Create a new file called [Link] and run your first program.
Open your terminal or command prompt and type: python -- You're officially a Python programmer!
version. You should see your Python version displayed.
Your First Python Program
print("Hello, World!")
print("Welcome to Python programming!")
# This is a comment - Python ignores this line
# Comments help you explain your code
Try it yourself: Type this code in your editor, save it as [Link], and
run it. That's all it takes to become a programmer!
Understanding Python Statements & Comments
Python Statements: The Building Blocks Python Comments: Explaining Your Code
Statements are instructions that the Python interpreter executes. They A comment is text within your code that the Python interpreter
can be simple actions like assigning a value, or complex structures ignores. Its sole purpose is to make your code more understandable
that control the program's flow. Types include assignment, for humans, whether that's you in six months or another developer on
conditional, and looping statements. your team.
# This is a single-line comment.
x = 10 # Assignment statement # Use comments to explain complex logic.
if x > 5: # Conditional statement
print("x is greater than 5") result = x * 2 # This is an inline comment.
# More complex statements follow specific syntax rules. # Comments improve code readability and maintainability.
Variables: Storing Your Data
A variable is a named location used to store data in the memory. It is helpful to think of
variables as a container that holds data which can be changed later throughout
programming.
# Assigning values to variable
sage = 30
name = "Alice"
is_student = True
Remember: Variables are flexible! You can change their values as your
program runs.
Variables Scope
Global Scope Local Scope Nested Scope
Variables declared outside of any Variables defined within a function or Python supports nested scopes, enabling
function or class have global scope, code block possess local scope, limiting inner functions to access variables from
making them accessible throughout the their accessibility strictly to that specific their enclosing (outer) function's scope.
entire program. context.
Variable Naming Rules
Understanding these fundamental rules ensures your Python code is both functional and readable.
Start with Letter or No Numbers at Start Alphanumeric &
Underscore A variable name cannot start with a
Underscores Only
Variable names must begin with a letter number (0-9). Names can only contain alpha-numeric
(A-z) or an underscore (_). characters and underscores (A-z, 0-9,
and _).
Case-Sensitive Avoid Keywords
Python treats age, Age, and AGE as Variable names cannot be any of
three distinct variables. Python's reserved keywords (e.g., if,
for, while).
Understanding Data Types
Data types in Python are a way to classify data items. They represent the kind of value, which determines what operations can be performed on that data. Since everything
is an object in Python programming, Python data types are classes and variables are instances (objects) of these classes.
Numeric Types Sequence Types Mapping Type
Represent numerical values. Includes: Ordered collections of items. Includes: Collections of key-value pairs.
• int: Whole numbers • str: Immutable sequence of characters • dict: Mutable unordered collection with
• float: Decimal numbers unique keys
• complex: Numbers with real and imaginary • list: Mutable ordered collection
parts • tuple: Immutable ordered collection
Set Types Boolean Type
Unordered collections of unique items. Includes: Logical values.
• set: Mutable unordered collection of unique elements • bool: Represents truth values, True or False
• frozenset: Immutable version of a set
Real-World Example: Student Data
# Storing student information
name = "Jordan Martinez"
student_id = 20240315
major = "Computer Science"
credits_completed = 45
graduation_year = 2026
# Calculating progress
total_credits_needed = 120
credits_remaining = total_credits_needed – credits_completed
print(f"{name} has {credits_remaining} credits left to graduate!")
# Output: Jordan Martinez has 75 credits left to graduate!
Making Decisions with Conditionals
Conditionals let your program make choices based on conditions. They're like a flowchart in your code.
The IF Statement Comparison Operators
• == equal to
grade = 85
• != not equal to
• > greater than
if grade >= 90:
print("A - Excellent!") • < less than
elif grade >= 80:
• >= greater than or equal
print("B - Great job!")
• <= less than or equal
elif grade >= 70:
print("C - Good work")
else: print("Keep studying!") Watch out: Use == to compare, not =. Single = assigns
values!
# Output: B - Great job!
Loops: Repeating Actions
FOR Loops WHILE Loops
Repeat a specific number of times or iterate through a collection. Keep repeating as long as a condition is true.
# Print numbers 1 to 5 # Count down from 5
for i in range(1, 6): count = 5
print(i) while count > 0:
print(count)
# Loop through a list count -= 1
courses = ["Math", "English", "Python"] print("Blast off!")
for course in courses:
print(f"Enrolled in {course}")
Activity Time: Grade Calculator
Your First Coding Challenge
Task: Write a program that calculates the average of three test scores and displays a letter grade.
# Starter code
score1 = 85
score2 = 92
score3 = 78
# TODO: Calculate the average
# TODO: Use if/elif/else to assign a letter grade
# TODO: Print the result
# Hint: average = (score1 + score2 + score3) / 3
Bonus Challenge: Can you modify the program to handle any number of scores using a list and a loop?
Working with Lists & Collections
Lists: Ordered Collections Dictionaries: Key-Value Pairs
# Creating a list # Creating a dictionary
students = ["Alex", "Jordan", "Sam"] student = { "name": "Alex", "age": 19, "major": "CS", "gpa": 3.75}
# Adding items # Accessing values
[Link]("Taylor") print(student["name"])
# Accessing items (0-indexed!) # Adding/updating
first_student = students[0] student["year"] = "Sophomore"
# Looping through
for student in students:
print(f"Hello, {student}!")
Introduction to Functions
Functions are reusable blocks of code that perform specific tasks. They help you organize code and avoid repetition.
Define the Function Call the Function Reuse Anywhere
def greet_student(name): message = result = greet_student("Alex") greet_student("Jordan")
f"Hello, {name}!" return message print(result) greet_student("Sam")
greet_student("Taylor")
# Output: Hello, Alex!
Building Practical Functions
Function with Multiple Parameters Function with Default Values
def calculate_final_grade(midterm, final, homework): def register_course(course_name, credits=3, semester="Fall"):
# Weighted average print(f"Registered for {course_name}")
grade = (midterm * 0.3 + print(f"Credits: {credits}")
final * 0.5 + print(f"Semester: {semester}")
homework * 0.2)
return grade # Using defaults
register_course("Python 101")
# Using the function
student_grade = calculate_final_grade(85, 92, 88) # Overriding defaults
print(f"Final grade: {student_grade}") register_course("Data Science", 4, "Spring")
Working with Modules
Modules are Python files containing functions and variables you can reuse. They're like toolboxes full of helpful tools.
Built-in Modules External Packages Your Own Modules
Python comes with powerful modules ready to Install additional tools using pip. Create reusable code in separate files.
use.
pip install pandas # [Link] my_function(): pass
import math pip install requests
import random
import datetime
Common Errors & How to Fix Them
IndentationError NameError TypeError
Problem: Inconsistent spacing in your Problem: Using a variable before defining Problem: Mixing incompatible data types
code it
Fix: Use 4 spaces (or one tab) Fix: Make sure variables are created Fix: Convert types or use compatible
consistently. Python is sensitive to before you use them operations
indentation!
# Wrong # Wrong
# Wrong print(name) age = "19"
def greet(): next_year = age + 1
print("Hi") # Right
name = "Alex" # Right
# Right print(name) age = int("19")
def greet(): next_year = age + 1
print("Hi")
Python File Handling
Master the essentials of working with CSV, JSON, and TXT files in Python
Why File Handling Matters
File handling is a fundamental skill for any programmer. Whether you're
analyzing student grades, processing research data, or building web applications,
you'll constantly work with external files.
Understanding these three file formats unlocks powerful capabilities: reading
datasets, storing configuration, logging events, and communicating with APIs.
The Three Essential File Types
TXT Files CSV Files JSON Files
Plain text format Comma-separated values JavaScript Object Notation
Perfect for logs, notes, and simple data Ideal for tabular data like spreadsheets Great for nested data, APIs, and
storage and databases configuration files
File Handling Basics: Opening Files
Python uses the open() function to work with files. You must always
# Always use 'with' statement
specify a file mode that tells Python what you want to do.
with open('[Link]', 'r') as file:
content = [Link]()
Key modes to remember: print(content)
• 'r' - Read (default mode)
# File closes automatically!
• 'w' - Write (overwrites existing content)
• 'a' - Append (adds to existing content)
• 'r+' - Read and write
Pro Tip: The with statement automatically closes files, preventing memory leaks and data corruption.
Working with TXT Files
Text files are the simplest file format. They store unformatted data that humans can
easily read and write. Let's explore the three main operations.
TXT File Operations
Reading Writing Appending
Use read(), readline(), or readlines() to Use write() with mode 'w' to create or Use mode 'a' to add content without
extract content overwrite files deleting existing data
# Reading # Writing # Appending
with open('[Link]', 'r') as f: with open('[Link]', 'w') as f: with open('[Link]', 'a') as f:
data = [Link]() [Link]('Event logged\n') [Link]('New entry\n')
print(data)
Real-World Example: Event Logger
Let's build a simple logging system that tracks user activities. This pattern is used everywhere—from web servers to mobile apps.
from datetime import datetime
def log_event(event_type, message):
timestamp = [Link]().strftime('%Y-%m-%d %H:%M:%S')
log_entry = f"[{timestamp}] {event_type}: {message}\n"
with open('activity_log.txt', 'a') as log_file:
log_file.write(log_entry)
print(f"Logged: {log_entry.strip()}")
# Usage examples
log_event("INFO", "User logged in")
log_event("ERROR", "Failed to load profile")
log_event("WARNING", "Low disk space")
Common Error: Forgetting the \n character means all entries appear on one line. Always add line breaks!
Understanding CSV Files
CSV (Comma-Separated Values) files organize data in rows and columns, just
like a spreadsheet. They're incredibly common for datasets, exports, and data
analysis.
Python's csv module makes working with these files straightforward. It handles
commas in data, quotes, and other formatting challenges automatically.
Perfect for: Student records, sales data, sensor readings, survey results
Reading CSV Files: Student Grades Example
Let's read a CSV file containing student information and calculate average grades.
Sample CSV: [Link] Python Code
Name,Student_ID,Grade,MajorAlice Johnson,1001,92,Computer import csv
Science
Bob Smith,1002,87,Mathematics with open('[Link]', 'r') as file:
Carol White,1003,95,Physics csv_reader = [Link](file)
David Lee,1004,88,Engineering
total_grade = 0
count = 0
for row in csv_reader:
print(f"{row['Name']}: {row['Grade']}")
total_grade += int(row['Grade'])
count += 1
avg = total_grade / count
print(f"\nClass Average: {avg:.1f}")
Writing CSV Files
Creating CSV files is equally simple. Use [Link]() or [Link]() depending on your data structure.
import csv
# Student data to write
students = [
{'Name': 'Emma Davis', 'Student_ID': '1005', 'Grade': '91', 'Major': 'Biology'},
{'Name': 'Frank Miller', 'Student_ID': '1006', 'Grade': '89', 'Major': 'Chemistry'},
{'Name': 'Grace Chen', 'Student_ID': '1007', 'Grade': '94', 'Major': 'Computer Science'}
]
# Write to CSV
with open('new_students.csv', 'w', newline='') as file:
fieldnames = ['Name', 'Student_ID', 'Grade', 'Major']
writer = [Link](file, fieldnames=fieldnames)
[Link]() # Write column headers
[Link](students) # Write all rows
print("CSV file created successfully!")
Important: Always include newline='' when writing CSV files to avoid extra blank lines on Windows!
JSON: The Web's Data
Format
JSON (JavaScript Object Notation) is the standard format for web APIs and
configuration files. It supports nested structures, making it perfect for complex data.
JSON Structure and Syntax
Objects (Dictionaries) Arrays (Lists)
Wrapped in curly braces { } Wrapped in square brackets [ ]
{"name": "John", "age": 20} ["Python", "Java", "C++"]
Data Types Nested Structures
Strings, numbers, booleans, null, objects, arrays Objects and arrays can contain other objects and arrays
"text", 42, true, null
{"courses": [{"name": "CS101"}]}
Reading JSON: API Response Example
Imagine you're fetching weather data from an API. Here's how to parse the JSON response.
weather_data.json Python Code
{ import json
"city": "San Francisco",
"temperature": 72, with open('weather_data.json', 'r') as file:
"conditions": "Partly Cloudy", data = [Link](file)
"forecast": [
{"day": "Monday", "high": 75}, print(f"City: {data['city']}")
{"day": "Tuesday", "high": 73}, print(f"Current: {data['temperature']}°F")
{"day": "Wednesday", "high": 70} print(f"{data['conditions']}\n")
]
} print("3-Day Forecast:")
for day in data['forecast']:
print(f" {day['day']}: {day['high']}°F")
Writing JSON Files
Use [Link]() to write Python dictionaries and lists to JSON files. The indent parameter makes output human-readable.
import json
# Student profile data
student_profile = {
"student_id": "1008",
"name": "Hannah Park",
"major": "Data Science",
"gpa": 3.85,
"courses": [
{"code": "CS101", "name": "Intro to Programming", "grade": "A"},
{"code": "MATH201", "name": "Statistics", "grade": "A-"},
{"code": "CS205", "name": "Data Structures", "grade": "B+"}
],
"contact": {
"email": "[Link]@[Link]",
"phone": "555-0123"
}
}
# Write to JSON file with pretty formatting
with open('student_profile.json', 'w') as file:
[Link](student_profile, file, indent=4)
print("Student profile saved!")
Common Errors and How to Fix Them
FileNotFoundError PermissionError
Problem: File doesn't exist or wrong path Problem: No permission to read/write file
Solution: Check spelling, use absolute paths, or verify the file Solution: Check file permissions, close the file in other
exists with [Link]() programs, or run with proper access rights
JSONDecodeError UnicodeDecodeError
Problem: Invalid JSON syntax Problem: Wrong character encoding
Solution: Validate JSON structure, check for trailing commas, Solution: Specify encoding: open(file, 'r', encoding='utf-8')
ensure proper quotes
Quick Reference Guide
Ease of Use Data Complexity
TXT files are simplest but limited in structure. CSV files handle tabular data well. JSON excels at complex, nested data structures.
Practice Activity: Build a Data Logger
Challenge: Create a multi-format data logging system that records events to TXT, CSV, and JSON files simultaneously.
Activity Instructions
Plan Your Logger Implement TXT Logging Add CSV Export
Design a function that takes event type, Write timestamped events to a text file. Create a CSV file with columns:
message, and user ID. Decide what Format: [timestamp] type: message timestamp, event_type, user_id, message
information to capture.
Include JSON Storage Test Your Logger
Build a JSON structure with nested event objects. Update an array Log 5 different events and verify all three files are created
of events. correctly
Bonus Challenge: Add a function to read and display logs from any of the three formats!
Final Activity: Build a Student Manager
Capstone Challenge
Create a mini program that manages student information:
1 Create a function that adds students 2 Store students in a list
Function should accept name, ID, and GPA as parameters Use a list of dictionaries to keep all student data organized
3 Write a function to display all students 4 Add a function to find honor students
Loop through the list and print each student's information Filter and display students with GPA above 3.5
Bonus: Can you save the student data to a JSON file and load it back later?
Key Takeaways
Always Use Context Managers Choose the Right Format
The with statement ensures files close properly, preventing data TXT for simplicity, CSV for tables, JSON for nested data and
corruption and memory leaks APIs
Handle Errors Gracefully Practice Makes Perfect
Use try-except blocks and check file existence before operations Build real projects: loggers, data analyzers, configuration
managers, and API clients
File handling is a fundamental skill that you'll use throughout your programming journey. Master these basics, and you'll be ready to tackle real-
world data challenges with confidence!
You're Now a Python Programmer!
What You've Learned Next Steps
• Python setup & basics • Practice coding daily
• Variables & data types • Build small projects
• Conditionals & loops • Explore Python libraries
• Functions & modules • Join coding communities
• Working with real data • Never stop learning!
Resources
• [Link]/docs
• Real Python tutorials
• LeetCode for practice
• Stack Overflow
• GitHub projects
Remember: Every expert programmer started exactly where you are today. Keep coding, stay curious,
and enjoy the journey!
Quiz Time
1. Which keyword is used to define a function in Python?
a) func
b) define
c) def
d) function
Ans: c) def
2. What is the correct way to print "Hello World" in Python?
a) echo("Hello World")
b) print("Hello World")
c) printf("Hello World")
d) disp("Hello World")
Ans: b) print("Hello World")
3. Which of the following is a valid variable name in Python?
a) 2name
b) first_name
c) first-name
d) first name
Ans: b) first_name
4. What is the output of: `type(3.14)`?
a) int
b) float
c) str
d) complex
Ans: b) float
5. Which symbol is used for comments in Python?
a) //
b) #
c) /* */
d) --
Ans: b) #
Thank You