Welcome to Python
Namaste and welcome to Python programming!
This tutorial helps you learn Python step by step,
from your first program to real-world applications.
Python is a high-level, general-purpose programming
language known for readable syntax and a rich
ecosystem of libraries.
Learning approach:
Understand the concept, study an example, run the
code, and solve a practical problem.
Why Learn Python?
Python is widely used in software development,
data analytics, automation, artificial intelligence,
and web applications.
Data Analytics
Analyze datasets using Pandas, NumPy, and visualization libraries.
Automation
Automate Excel reports, file processing, and repetitive tasks.
Web Development
Build websites and APIs using Flask, Django, and FastAPI.
Machine Learning
Develop predictive models using scikit-learn and other libraries.
Installation & Environment Setup
Before writing Python programs, install Python
and configure your development environment.
Step 1: Install Python
Download Python from the
official Python website
.
On Windows, make sure Python is accessible
from your terminal.
Step 2: Verify Installation
python --version
On some systems, use python3 --version.
Step 3: Install VS Code
Install
Visual Studio Code
and its Python extension.
Step 4: Create a Virtual Environment
python -m venv .venv
Activate on Windows PowerShell
.venv\Scripts\Activate.ps1
Activate on Windows Command Prompt
.venv\Scripts\activate.bat
Activate on macOS or Linux
source .venv/bin/activate
Step 5: Install Packages
python -m pip install pandas numpy
Tip: Use a separate virtual
environment for each project.
Getting Started with Python
Create a file named main.py
and write your first program.
Hello World
print("Hello, World!")
print("Welcome to Python Programming")
Output
Hello, World!
Welcome to Python Programming
The print() function displays output.
Comments
# This is a single-line comment
print("Learning Python") # Display a message
Indentation
Python uses indentation to define code blocks.
age = 25
if age >= 18:
print("Eligible to vote")
Variables in Python
Variables are names that refer to values.
Python determines the type from the assigned value.
customer_name = "Rahul"
age = 28
premium = 25000.50
is_active = True
print(customer_name)
print(age)
print(premium)
print(is_active)
Variable Naming Rules
- Names can contain letters, numbers, and underscores.
- Names cannot start with a number.
- Variable names are case-sensitive.
- Python keywords cannot be used as variable names.
Formatted Strings
name = "Amit"
premium = 15000
print(f"{name} paid a premium of {premium}")
Output
Amit paid a premium of 15000
Python Data Types
Python provides built-in types for numbers,
text, collections, and other values.
| Data Type |
Description |
Example |
| int | Whole numbers | 100 |
| float | Decimal numbers | 99.50 |
| str | Text | "Python" |
| bool | Boolean | True |
| list | Mutable sequence | [1, 2, 3] |
| tuple | Immutable sequence | (1, 2) |
| set | Unique elements | {1, 2} |
| dict | Key-value mapping | {"a": 1} |
| NoneType | Absence of a value | None |
Check Data Types
value = 100
name = "Python"
print(type(value))
print(type(name))
Type Conversion
amount = "25000"
premium = int(amount)
print(premium + 5000)
Python Operators
Operators perform calculations, comparisons,
and logical operations.
Arithmetic Operators
a = 20
b = 6
print(a + b) # Addition
print(a - b) # Subtraction
print(a * b) # Multiplication
print(a / b) # Division
print(a // b) # Floor division
print(a % b) # Remainder
print(a ** b) # Exponentiation
Comparison Operators
premium = 25000
print(premium > 20000)
print(premium == 25000)
print(premium != 10000)
Logical Operators
age = 30
salary = 50000
if age >= 18 and salary >= 30000:
print("Eligible")
Conditional Statements
Conditional statements execute different code
depending on whether a condition is true.
if, elif, else
premium = 35000
if premium >= 50000:
print("High Premium")
elif premium >= 20000:
print("Medium Premium")
else:
print("Low Premium")
Output
Medium Premium
Conditional Expression
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)
Loops in Python
Loops repeat a block of code without
writing the same instructions multiple times.
for Loop
customers = ["Rahul", "Amit", "Neha"]
for customer in customers:
print(customer)
range()
for number in range(1, 6):
print(number)
while Loop
count = 1
while count <= 5:
print(count)
count += 1
enumerate()
names = ["Amit", "Neha", "Ravi"]
for index, name in enumerate(names, start=1):
print(index, name)
Output
1 Amit
2 Neha
3 Ravi
break and continue
for number in range(1, 10):
if number == 3:
continue
if number == 7:
break
print(number)
String Manipulation
Strings represent text and provide methods
for cleaning and transforming data.
name = " rahul kumar "
print(name.strip())
print(name.upper())
print(name.lower())
print(name.title())
Replace Text
message = "I am learning Java"
updated = message.replace("Java", "Python")
print(updated)
String Slicing
text = "Python Programming"
print(text[0:6])
print(text[-11:])
print(text[::-1])
split() and join()
data = "Amit,Neha,Ravi"
names = data.split(",")
print(names)
result = " | ".join(names)
print(result)
Lists in Python
Lists store ordered collections of values.
They are mutable, meaning their contents can change.
premiums = [12000, 25000, 18000, 40000]
print(premiums[0])
print(len(premiums))
print(sum(premiums))
print(max(premiums))
List Methods
names = ["Amit", "Rahul"]
names.append("Neha")
names.insert(1, "Ravi")
names.remove("Amit")
print(names)
List Comprehension
premiums = [10000, 25000, 40000, 15000]
high_premiums = [
premium
for premium in premiums
if premium > 20000
]
print(high_premiums)
Tuples
Tuples are ordered collections that cannot
be modified after creation.
customer = ("Rahul", 28, "Mumbai")
print(customer[0])
print(customer[1])
Tuple Unpacking
name, age, city = customer
print(name)
print(age)
print(city)
Sets
A set is an unordered collection of unique elements.
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(sorted(unique_numbers))
Set Operations
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # Union
print(a & b) # Intersection
print(a - b) # Difference
Dictionaries
Dictionaries store information as key-value pairs.
customer = {
"name": "Rahul",
"age": 30,
"premium": 25000,
"status": "Active"
}
print(customer["name"])
print(customer.get("premium"))
Loop Through a Dictionary
for key, value in customer.items():
print(key, value)
Real-World Example
employees = {
"Amit": 45000,
"Neha": 65000,
"Ravi": 75000
}
for name, salary in employees.items():
if salary > 50000:
print(name, salary)
Functions
Functions organize reusable code into independent blocks.
Defining a Function
def greet(name):
return f"Hello, {name}"
print(greet("Rahul"))
Function Parameters
def calculate_total(premiums):
return sum(premiums)
values = [10000, 20000, 30000]
total = calculate_total(values)
print(total)
Default Arguments
def greet(name="Guest"):
print(f"Welcome, {name}")
greet()
greet("Amit")
Lambda Functions
square = lambda number: number ** 2
print(square(5))
File Handling
Python can create, read, update, and process files.
Write a Text File
with open("customers.txt", "w", encoding="utf-8") as file:
file.write("Rahul\n")
file.write("Amit\n")
file.write("Neha\n")
Read a Text File
with open("customers.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip())
Read CSV Files
import csv
with open("sales.csv", "r", newline="", encoding="utf-8") as file:
reader = csv.DictReader(file)
for row in reader:
print(row)
Write JSON Files
import json
customer = {
"name": "Amit",
"premium": 25000
}
with open("customer.json", "w", encoding="utf-8") as file:
json.dump(customer, file, indent=4)
Exception Handling
Exception handling allows programs to respond
to runtime errors without unexpectedly terminating.
try and except
try:
age = int(input("Enter your age: "))
print(f"Your age is {age}")
except ValueError:
print("Please enter a valid number")
Multiple Exceptions
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print(a / b)
except ValueError:
print("Invalid number")
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Execution completed")
Object-Oriented Programming
Object-Oriented Programming organizes
software around classes and objects.
Classes and Objects
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def display(self):
print(self.name, self.salary)
emp1 = Employee("Rahul", 50000)
emp1.display()
Inheritance
class Person:
def greet(self):
print("Hello")
class Employee(Person):
def work(self):
print("Employee is working")
emp = Employee()
emp.greet()
emp.work()
Encapsulation
class BankAccount:
def __init__(self, balance):
self.__balance = balance
def get_balance(self):
return self.__balance
def deposit(self, amount):
if amount > 0:
self.__balance += amount
account = BankAccount(10000)
account.deposit(5000)
print(account.get_balance())
Note:
Python's double-underscore attributes use name mangling.
This discourages accidental access but does not
provide strict security protection.
Modules and Packages
Modules organize reusable code into files.
Packages organize related modules.
Built-in Modules
import math
import random
from datetime import date
print(math.sqrt(64))
print(random.randint(1, 100))
print(date.today())
Installing External Libraries
python -m pip install pandas
Importing Libraries
import pandas as pd
print(pd.__version__)
Advanced Python Concepts
Advanced Python features help developers
write efficient, reusable, and maintainable code.
Dictionary Comprehension
numbers = [1, 2, 3, 4]
squares = {
number: number ** 2
for number in numbers
}
print(squares)
Generators
def generate_numbers():
for number in range(1, 6):
yield number
for value in generate_numbers():
print(value)
Decorators
from functools import wraps
def logger(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("Function started")
result = func(*args, **kwargs)
print("Function finished")
return result
return wrapper
@logger
def greet():
print("Hello Python")
greet()
Python for Data Analytics
Python is used to import, clean, analyze,
and visualize business data.
Pandas DataFrame
import pandas as pd
data = {
"Customer": ["Rahul", "Amit", "Neha"],
"Premium": [25000, 15000, 40000]
}
df = pd.DataFrame(data)
print(df)
Filter Data
high_premium = df[df["Premium"] > 20000]
print(high_premium)
Aggregate Data
print(df["Premium"].sum())
print(df["Premium"].mean())
print(df["Premium"].max())
Read Excel Data
# Install pandas and openpyxl first.
import pandas as pd
df = pd.read_excel("insurance_data.xlsx")
print(df.head())
print(df.info())
Data Cleaning
df = df.drop_duplicates()
df["Customer"] = (
df["Customer"]
.astype("string")
.str.strip()
.str.title()
)
df["Premium"] = pd.to_numeric(
df["Premium"],
errors="coerce"
)
print(df.isnull().sum())
Important:
Always inspect missing values and invalid records
before removing or replacing them.
Practice Projects
Apply your Python knowledge by building
small, practical projects.
01. Expense Tracker
Record expenses, calculate totals,
and export results to CSV.
Beginner
02. Customer Data Cleaner
Clean customer names, remove duplicates,
and validate missing fields.
Beginner
03. Insurance Premium Analyzer
Analyze active policies, premium totals,
and customer-level summaries.
Intermediate
04. Excel Report Automation
Combine multiple Excel files and
generate automated reports.
Intermediate
05. REST API with Flask
Create endpoints to add, retrieve,
update, and delete customer records.
Advanced
06. Sales Data Analysis
Use Pandas to analyze revenue,
products, and monthly performance.
Intermediate
Continue Your Python Journey
You have explored the essential concepts of
Python programming. Continue practicing,
build projects, and gradually work toward
more advanced applications.