Python Programming Tutorial
What is a Variable?
In Python, a variable is like a labeled storage box in memory. You can store values in it and retrieve or update them whenever needed.
Creating Your Own Variables
In Python, you can create a variable simply by assigning a value to a name:
my_age = 25
user_name = "Ravi"
user_height = 5.9
Understanding Data Types
- Integer (int): Whole numbers like 7, -42
- Float (float): Numbers with decimals, e.g., 3.1415, 0.5
- String (str): Text enclosed in quotes, e.g., "Python", "Ravi"
- Boolean (bool): Logical values: True or False
How Python Stores Variables
When you create a variable, Python reserves a spot in memory and links the name to that location:
| Variable | Memory Address | Stored Value |
|---|---|---|
| score | 0x7ffd1234 | 42 |
Changing Variable Values
Python allows you to update a variable anytime, even changing its type:
score = 10 # Initially an integer
score = "Ten" # Now it's a string
Variable Scope in Python
Variables can either be global (accessible everywhere) or local (only inside a function):
level = 1 # Global variable
def show_level():
stage = 5 # Local variable
print(stage)
print(level) # Works
show_level() # Works
print(stage) # Error! 'stage' is local
Defining Constants
Constants are variables meant to stay the same. By convention, we write them in uppercase:
GRAVITY = 9.8
Python won't stop you from changing them, but treating them as fixed values is best practice.
Python Data Types
Different data types define what kind of values a variable can hold and how they behave.
| Type | Description | Example |
|---|---|---|
| Integer | Whole numbers | 7, -12 |
| Float | Decimal numbers | 3.5, -0.75 |
| String | Textual data | "Ravi" |
| Boolean | True or False | True, False |
| List | Ordered collection of items | [10, 20, 30] |
| Dictionary | Key-value pairs | {"name": "Ravi"} |
Python Keywords
Keywords are reserved words with special meaning in Python, defining the program's structure and control flow.
Python Literals
Literals represent fixed values directly assigned to variables. They come in several types, including numbers, strings, and booleans.
num_items = 42 # Integer literalpi_value = 3.1415 # Float literalgreeting = "Namaste" # String literalis_active = False # Boolean literalunset_value = None # None literalPython Operators
Operators perform actions on variables and values. They include arithmetic, comparison, logical, assignment, and more.
- Arithmetic Operators: +, -, *, /, %, //, **
- Comparison Operators: ==, !=, >, <, >=, <=
- Logical Operators: and, or, not
- Assignment Operators: =, +=, -=, *=
Python Comments
Comments are annotations in code ignored by the interpreter. Use them to explain complex parts of code.
# This is a single-line comment
"""
This is a multi-line comment
Describing the purpose of the following function
"""
Python If-Else Statement
The if-else statement is a control flow structure that allows code to make decisions based on conditions. It’s like setting rules: if a condition is met, do one thing; otherwise, do another.
user_age = 20
if user_age >= 18:
print("You can vote.")
else:
print("You cannot vote yet.")
Python Loops
Loops help us repeat a block of code multiple times. Python supports two main types of loops: for loop and while loop.
Python For Loop
A for loop is perfect for iterating over a sequence of items, such as a list or a string. Each item in the sequence is processed one at a time.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("Fruit:", fruit)
Python While Loop
The while loop repeats a block of code as long as a specified condition is True. It’s especially useful when we don't know beforehand how many times we want to repeat an action.
counter = 1
while counter <= 3:
print("Counter:", counter)
counter += 1
Python Break Statement
The break statement allows us to exit a loop prematurely, regardless of the loop’s condition. This is helpful when we want to stop the loop based on a certain event or condition.
numbers = [7, 9, 12, 15, 18]
for num in numbers:
if num % 3 == 0:
print("First number divisible by 3:", num)
break
Python Continue Statement
The continue statement skips the current iteration of the loop and moves to the next one. It’s useful when we want to ignore certain items in a loop.
for number in range(1, 12):
if number % 4 == 0:
continue # skip numbers divisible by 4
print(number)
Python Pass
The pass statement acts as a placeholder in Python. It allows you to define blocks of code that you’ll implement later, without causing errors. Often used in loops, functions, or classes under development.
def upcoming_feature():
pass # To be implemented later
for idx in range(6):
if idx < 2:
pass # temporarily do nothing
else:
print("Current index:", idx)
Python Strings
Strings are sequences of characters used for textual data in Python. They are immutable, meaning they cannot be changed once created. Python provides numerous built-in string methods for manipulation.
message = "Welcome to Python Programming!"
# Convert to lowercase
print(message.lower())
# Convert to uppercase
print(message.upper())
# Replace a substring
print(message.replace("Python", "Coding"))
Python String Functions
In Python, strings are a sequence of characters, and they come with a variety of built-in methods to perform common operations. These string functions are incredibly useful for handling and manipulating textual data.
Let's explore some commonly used string functions:
- upper(): Converts all characters in the string to uppercase.
- lower(): Converts all characters in the string to lowercase.
- strip(): Removes leading and trailing whitespace characters from the string.
- replace(): Replaces a specified substring with another substring.
- split(): Splits the string into a list based on a delimiter (default is space).
- find(): Searches for a substring within the string and returns the index of its first occurrence.
- join(): Joins the elements of an iterable into a single string with a specified delimiter.
Example Code:
# Custom examples of Python String Functions
greeting = " Hello, Pythonistas! "
# Convert to uppercase
print(greeting.upper())
# Output: " HELLO, PYTHONISTAS! "
# Convert to lowercase
print(greeting.lower())
# Output: " hello, pythonistas! "
# Strip leading and trailing spaces
print(greeting.strip())
# Output: "Hello, Pythonistas!"
# Replace a substring
print(greeting.replace("Pythonistas", "Developers"))
# Output: " Hello, Developers! "
# Split the string into a list
words = greeting.split()
print(words)
# Output: ['Hello,', 'Pythonistas!']
# Find the position of a substring
print(greeting.find("Pythonistas"))
# Output: 8
# Join elements of a list into a string
tech_words = ['Python', 'Rocks']
print(" ".join(tech_words))
# Output: "Python Rocks"
Python Lists
Lists are mutable, ordered collections that can contain elements of any data type. They are dynamic and allow various operations such as adding, removing, and modifying elements.
snacks = ["chips", "cookies", "nuts"]
snacks.append("granola bar") # Add new item
print(snacks[1]) # Access second item
snacks.remove("cookies") # Remove specific item
print(snacks)
Python Tuples
Tuples are immutable collections, used to store data that should not change. They are useful for read-only data, ensuring that no accidental modifications occur.
shapes = ("circle", "square", "triangle")
print(shapes[0]) # Access first element
# Attempting to modify will cause an error
# shapes[0] = "rectangle" # Error: Tuples are immutable
Python List Vs Tuple
Lists are mutable and allow changes after creation, while tuples are immutable. Use lists when data needs modification and tuples for static data.
# Mutable list example my_items = [10, 20, 30] my_items[1] = 99 # List can be changed print(my_items) # Immutable tuple example my_coords = (5, 10, 15) # my_coords[1] = 50 # Error: Tuple cannot be changed print(my_coords)
Python Sets
Sets are unordered collections with no duplicate values, useful for mathematical operations like unions and intersections.
unique_numbers = {1, 2, 3, 3, 4}
print(unique_numbers) # Output: {1, 2, 3, 4}
unique_numbers.add(7) # Add new number
print(unique_numbers)
Python Dictionary
Dictionaries are collections of key-value pairs, enabling fast retrieval by key.
student = {"name": "Bob", "age": 21}
print(student["name"]) # Access value by key
student["age"] = 22 # Update age
print(student)
Python Functions
Functions are reusable blocks of code that encapsulate specific logic. They help in making the code modular and readable.
def welcome_user(user_name):
return f"Hey there, {user_name}! Welcome aboard."
print(welcome_user("Bob"))
Python Lambda Functions
Lambda functions are anonymous, single-expression functions used for short, simple operations.
power = lambda base, exponent: base ** exponent print(power(3, 4)) # 3^4 = 81
Python Built-in Functions
Python comes with a set of built-in functions that you can use without needing to import any additional libraries. These functions provide essential utilities for working with data, performing mathematical operations, interacting with the environment, and more.
Some of the most commonly used built-in functions in Python are:
- print(): Prints the specified message to the console or other standard output device.
- len(): Returns the length (the number of items) of an object.
- type(): Returns the type of the specified object.
- int(), float(), str(): Converts a given value to an integer, float, or string respectively.
- range(): Generates a sequence of numbers, often used in loops.
- max(), min(): Returns the largest and smallest item in an iterable or among two or more arguments.
- sum(): Returns the sum of all items in an iterable (e.g., a list).
- sorted(): Returns a sorted list of the specified iterable’s elements.
- input(): Reads a line of text input from the user.
Example Code:
# Example of Python Built-in Functions
# Print message to console
print("Python is awesome!")
# Length of a string
phrase = "Python coding rocks"
print(len(phrase)) # Output: 18
# Check data type
value = 42
print(type(value)) # Output:
# Type conversion
num_str = "99"
print(int(num_str)) # Output: 99
# Generate range
for i in range(3):
print(i) # Output: 0 1 2
# Max and min in a list
vals = [7, 2, 9, 4]
print(max(vals)) # 9
print(min(vals)) # 2
# Sum of list
print(sum(vals)) # 22
# Sort a list
print(sorted(vals)) # [2, 4, 7, 9]
# Take input from user
username = input("Enter your username: ")
print("Welcome, " + username)
Python Files I/O
File I/O allows reading and writing files, enabling persistent storage of data.
with open("demo_file.txt", "w") as f:
f.write("Hello from Python!")
with open("demo_file.txt", "r") as f:
content = f.read()
print(content)
Python Modules
Modules are files containing Python code that you can import and use in other programs.
import random print(random.randint(1, 10)) # Random integer between 1 and 10
Python Exceptions
Exceptions are errors that can be handled with try-except blocks, allowing programs to manage unexpected conditions.
try:
result = 10 / 0
except ZeroDivisionError:
print("Oops! Division by zero is not allowed.")
Python Date
The datetime module provides classes to manipulate date and time in Python.
from datetime import datetime
current_time = datetime.now()
print(current_time.strftime("%d-%m-%Y %H:%M:%S"))
Python Regex
Regular expressions are sequences of characters that define search patterns, useful for pattern matching and string validation.
import re
pattern = re.compile(r"\bPython\b")
match = pattern.search("Learning Python is fun!")
print(match.group() if match else "No match found")
Python OOPs
Object-Oriented Programming (OOP) in Python is a programming paradigm that structures code into reusable objects. Objects are instances of classes, which can have properties (attributes) and methods (functions). OOP makes code modular, easier to debug, and allows complex software to be more manageable.
Python OOP Concepts
Python’s OOP includes four main concepts: Encapsulation (bundling data and methods), Inheritance (reusing and extending existing code), Polymorphism (using a single interface in different forms), and Abstraction (hiding complexity to make interfaces simpler).
Python Object Class
A class is a blueprint for creating objects. It defines a set of attributes and methods that the objects created from the class will have. When an instance of a class is created, it is called an object.
# My own version of a class
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
def info(self):
return f"{self.make} - {self.model}"
car = Vehicle("Honda", "Civic")
print(car.info()) # Outputs: Honda - Civic
Python Constructors
A constructor in Python is defined by the __init__ method and is called automatically when an object is created.
It initializes the object’s properties and sets up its initial state.
class User:
def __init__(self, username, age):
self.username = username
self.age = age
def introduce(self):
return f"Hi, I am {self.username} and I am {self.age} years old."
u1 = User("Bob", 25)
print(u1.introduce()) # Hi, I am Bob and I am 25 years old.
Python Inheritance
Inheritance allows a class (child class) to inherit attributes and methods from another class (parent class). This helps in code reusability and hierarchy building.
# Parent class
class Creature:
def __init__(self, name):
self.name = name
def make_sound(self):
return "Generic sound"
# Child class
class Cat(Creature):
def make_sound(self):
return "Meow"
my_cat = Cat("Whiskers")
print(my_cat.name) # Whiskers
print(my_cat.make_sound()) # Meow
Abstraction in Python
Abstraction means exposing only the relevant information to the outside world and hiding the internal implementation details.
In Python, abstraction is achieved using abstract classes and interfaces from the abc module.
from abc import ABC, abstractmethod
class Polygon(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Polygon):
def __init__(self, w, h):
self.w = w
self.h = h
def area(self):
return self.w * self.h
rect = Rectangle(4, 6)
print(rect.area()) # 24
Encapsulation in Python
Encapsulation is the concept of bundling data and methods within a class and restricting direct access to some attributes. In Python, we can create private attributes using a single or double underscore before the variable name.
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.__balance = balance
def deposit(self, amount):
self.__balance += amount
def withdraw(self, amount):
if amount <= self.__balance:
self.__balance -= amount
else:
print("Not enough balance!")
def show_balance(self):
return self.__balance
acct = BankAccount("Eve", 500)
acct.deposit(300)
acct.withdraw(200)
print(acct.show_balance()) # 600
Polymorphism in Python
Polymorphism allows us to define methods in child classes that have the same name as methods in the parent class. This allows the same method to operate on different objects in a unique way.
class VehicleBase:
def move(self):
return "Moving somehow"
class Bike(VehicleBase):
def move(self):
return "Pedaling the bike"
class Car(VehicleBase):
def move(self):
return "Driving the car"
def operate(vehicle):
print(vehicle.move())
bike = Bike()
car = Car()
operate(bike) # Pedaling the bike
operate(car) # Driving the car
Python Database
Python MySQL
MySQL is a widely used relational database system for managing structured data. Python can connect to MySQL using the mysql-connector library.
Install the connector with pip install mysql-connector-python. After installation, you can perform queries and manage data in MySQL.
Example Code:
import mysql.connector
# Establish connection
conn = mysql.connector.connect(
host="localhost",
user="root",
password="mypassword",
database="testdb"
)
# Create cursor
cur = conn.cursor()
# Execute a query
cur.execute("SELECT * FROM employees")
# Fetch and print results
for record in cur.fetchall():
print(record)
# Close connection
conn.close()
Python MongoDB
MongoDB is a NoSQL database storing data in flexible, JSON-like documents. Python can interface with it via the pymongo library.
Install using pip install pymongo. This allows creation, retrieval, and manipulation of MongoDB documents.
Example Code:
from pymongo import MongoClient
# Connect to MongoDB server
client = MongoClient("mongodb://localhost:27017/")
# Access database
db = client.testdb
# Access collection
users = db.users
# Insert a document
users.insert_one({"name": "Alice", "age": 28})
# Query documents
for u in users.find():
print(u)
# Close connection
client.close()
Python SQLite
SQLite is a lightweight, serverless SQL database. Python's built-in sqlite3 library allows interaction with SQLite databases.
Ideal for small applications, embedded systems, or local data storage.
Example Code:
import sqlite3
# Connect (or create) SQLite database
conn = sqlite3.connect("testdb.sqlite")
# Create cursor
cur = conn.cursor()
# Create table if not exists
cur.execute("""
CREATE TABLE IF NOT EXISTS employees (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER
)
""")
# Insert data
cur.execute("INSERT INTO employees (name, age) VALUES (?, ?)", ("Bob", 35))
# Commit changes
conn.commit()
# Query table
cur.execute("SELECT * FROM employees")
for row in cur.fetchall():
print(row)
# Close connection
conn.close()
🎉 Hurray! 🎉
Congratulations on mastering Python's interaction with databases! You now have the knowledge to connect Python with MySQL, MongoDB, and SQLite. You're one step closer to becoming a proficient Python developer!
Ready to dive deeper? Explore more advanced database techniques, frameworks like Django for web development, and other powerful Python libraries!