Python Programming Tutorial
Master Python from basics to advanced concepts with practical examples and real-world applications.
Table of Contents
Introduction to Python
Python is a high-level, interpreted programming language known for its simplicity and readability. It's widely used in web development, data science, automation, and artificial intelligence.
Why Learn Python?
- Easy to Learn: Simple syntax similar to English
- Versatile: Used in multiple domains
- Large Community: Extensive libraries and support
- High Demand: Popular in job market
- Open Source: Free to use and modify
Applications of Python
- Web Development (Django, Flask)
- Data Science & Analytics
- Machine Learning & AI
- Automation & Scripting
- Desktop Applications
- Game Development
Setup & Installation
Installing Python
# Download Python from python.org
# For Windows: Download .exe installer
# For Mac: Download .pkg installer
# For Linux: Use package manager
# Verify installation
python --version
# or
python3 --version
Python Interactive Shell
# Start Python shell
python
# Basic operations
>>> print("Hello, World!")
Hello, World!
>>> 2 + 3
5
>>> exit()
Your First Python Program
# hello.py
print("Hello, World!")
print("Welcome to Python Programming!")
# Run the program
python hello.py
Python Basics
Variables and Assignment
# Variables (no declaration needed)
name = "John Doe"
age = 25
height = 5.9
is_student = True
# Multiple assignment
x, y, z = 1, 2, 3
a = b = c = 0
# Variable naming rules
# - Start with letter or underscore
# - Can contain letters, numbers, underscores
# - Case-sensitive
# - Cannot use Python keywords
Comments
# Single line comment
"""
Multi-line comment
or docstring
"""
'''
Another way to write
multi-line comments
'''
Input and Output
# Output
print("Hello, World!")
print("Name:", name, "Age:", age)
print(f"Hello, {name}! You are {age} years old.")
# Input
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print(f"Hello, {name}!")
Data Types
Numeric Types
# Integer
age = 25
year = 2024
# Float
price = 19.99
pi = 3.14159
# Complex
complex_num = 3 + 4j
# Type checking
print(type(age)) #
print(type(price)) #
String Operations
# String creation
name = "Python"
message = 'Hello World'
multiline = """This is a
multi-line string"""
# String methods
print(name.upper()) # PYTHON
print(name.lower()) # python
print(name.replace('P', 'J')) # Jython
print(len(name)) # 6
print(name[0]) # P
print(name[1:4]) # yth
Lists (Arrays)
# List creation
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
# List operations
fruits.append("grape") # Add to end
fruits.insert(0, "mango") # Insert at index
fruits.remove("banana") # Remove by value
popped = fruits.pop() # Remove last
print(fruits[0]) # Access by index
print(fruits[-1]) # Last element
print(fruits[1:3]) # Slicing
Dictionaries
# Dictionary creation
student = {
"name": "John",
"age": 20,
"grade": "A"
}
# Dictionary operations
print(student["name"]) # Access value
student["email"] = "john@email.com" # Add key-value
student.update({"city": "New York"}) # Update multiple
del student["age"] # Delete key
print(student.keys()) # Get all keys
print(student.values()) # Get all values
print(student.items()) # Get key-value pairs
Control Flow
Conditional Statements
# If-elif-else
age = 18
if age >= 18:
print("You are an adult")
elif age >= 13:
print("You are a teenager")
else:
print("You are a child")
# Nested conditions
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
Loops
# For loop
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
# Range function
for i in range(5): # 0 to 4
print(i)
for i in range(1, 6): # 1 to 5
print(i)
# While loop
count = 0
while count < 5:
print(count)
count += 1
# Break and continue
for i in range(10):
if i == 3:
continue # Skip 3
if i == 7:
break # Stop at 7
print(i)
Functions
Function Definition and Calling
# Basic function
def greet():
print("Hello, World!")
greet() # Call function
# Function with parameters
def greet_person(name):
print(f"Hello, {name}!")
greet_person("Alice")
# Function with return value
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(result) # 8
Advanced Function Features
# Default parameters
def greet(name, message="Hello"):
print(f"{message}, {name}!")
greet("Bob") # Hello, Bob!
greet("Alice", "Hi") # Hi, Alice!
# Variable arguments
def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3, 4)) # 10
# Keyword arguments
def create_profile(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
create_profile(name="John", age=25, city="NYC")
Lambda Functions
# Lambda (anonymous) functions
square = lambda x: x ** 2
print(square(5)) # 25
# Using with built-in functions
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # [1, 4, 9, 16, 25]
# Filter function
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # [2, 4]
Object-Oriented Programming
Classes and Objects
# Class definition
class Student:
# Class variable
school = "SD Technology"
# Constructor
def __init__(self, name, age):
self.name = name # Instance variable
self.age = age
self.grades = []
# Instance method
def add_grade(self, grade):
self.grades.append(grade)
def get_average(self):
if self.grades:
return sum(self.grades) / len(self.grades)
return 0
# String representation
def __str__(self):
return f"Student: {self.name}, Age: {self.age}"
# Creating objects
student1 = Student("Alice", 20)
student2 = Student("Bob", 21)
# Using methods
student1.add_grade(85)
student1.add_grade(90)
print(student1.get_average()) # 87.5
Inheritance
# Parent class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"Hi, I'm {self.name}")
# Child class
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age) # Call parent constructor
self.student_id = student_id
def study(self):
print(f"{self.name} is studying")
# Using inheritance
student = Student("Alice", 20, "S001")
student.introduce() # From parent class
student.study() # From child class
File Handling
Reading and Writing Files
# Writing to file
with open("data.txt", "w") as file:
file.write("Hello, World!\n")
file.write("Python File Handling")
# Reading from file
with open("data.txt", "r") as file:
content = file.read()
print(content)
# Reading line by line
with open("data.txt", "r") as file:
for line in file:
print(line.strip())
# Appending to file
with open("data.txt", "a") as file:
file.write("\nNew line added")
# Working with CSV files
import csv
# Writing CSV
data = [["Name", "Age"], ["Alice", 25], ["Bob", 30]]
with open("people.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
# Reading CSV
with open("people.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Web Development with Flask
Basic Flask Application
# Install Flask: pip install flask
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, Flask!"
@app.route('/user/')
def user_profile(name):
return f"Welcome, {name}!"
@app.route('/form', methods=['GET', 'POST'])
def form_handler():
if request.method == 'POST':
username = request.form['username']
return f"Hello, {username}!"
return '''
'''
if __name__ == '__main__':
app.run(debug=True)
Data Science Basics
Working with Pandas
# Install: pip install pandas numpy matplotlib
import pandas as pd
import numpy as np
# Creating DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'Salary': [50000, 60000, 70000]
}
df = pd.DataFrame(data)
# Basic operations
print(df.head()) # First 5 rows
print(df.info()) # DataFrame info
print(df.describe()) # Statistical summary
# Filtering data
young_employees = df[df['Age'] < 30]
print(young_employees)
# Reading from CSV
df = pd.read_csv('data.csv')
# Basic statistics
average_age = df['Age'].mean()
max_salary = df['Salary'].max()
Data Visualization
import matplotlib.pyplot as plt
# Simple plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Line Plot')
plt.show()
# Bar chart
categories = ['A', 'B', 'C', 'D']
values = [23, 45, 56, 78]
plt.bar(categories, values)
plt.title('Bar Chart')
plt.show()
Practice Exercises
Beginner Exercises
- Calculate area of rectangle
- Check if number is even or odd
- Find largest number in list
- Count vowels in a string
- Create a simple calculator
Intermediate Exercises
- Build a student management system
- Create a web scraper
- Implement a simple game
- Build a REST API with Flask
- Analyze CSV data with Pandas
Master Python with Expert Guidance
Ready to take your Python skills to the next level? Join our comprehensive Python course with hands-on projects, mentorship, and job placement assistance.
View Python Course Back to Tutorials