Python Programming Tutorial


What is a Variable?

In Python, a variable is a container that holds data. Think of it as a label or a name assigned to a value in your program's memory, allowing you to refer to that value later.

Declaring Variables in Python

The syntax to declare a variable in Python is:

variable_name = value
  

Example:

age = 23
name = "Alice"
height = 5.7

Types of Values (Data Types)

Memory Representation of Variables

When you declare a variable, Python:

  1. Allocates memory for that variable in the computer's memory.
  2. Associates the variable name with this memory address.

Example memory representation:

Variable Name Memory Address Value
x 0x7ff9b370 10

Updating Variables

Variables in Python are dynamically typed and can be reassigned to a new value, even of a different type:

x = 5  # x is an integer
x = "five" # Now, x is a string

Scope of Variables

Python has two main variable scopes:

x = 10  # Global variable

def my_function():
y = 5 # Local variable
print(y)

print(x) # Works
my_function() # Works
print(y) # Error, y is not accessible here

Constants in Python

In Python, constants are typically written in uppercase to distinguish them from regular variables. For example:

PI = 3.14159

While Python doesn’t enforce immutability for constants, by convention we treat them as unchangeable.

Python Data Types

Data types classify the kind of data a variable holds, determining how it can be used.

Type Description Example
Integer Whole numbers 10, -3
Float Decimal numbers 3.14, -1.5
String Sequence of characters "Hello"
Boolean True or False True, False
List Ordered, mutable collection [1, 2, 3]
Dictionary Collection of key-value pairs {"{'name': 'Alice'}"}

Python Keywords

Keywords are reserved words with special meaning in Python, defining the program's structure and control flow.

and as assert break class continue def elif else False for global if import in not or return True while

Python Literals

Literals represent fixed values directly assigned to variables. They come in several types, including numbers, strings, and booleans.

x = 10 # Integer literal

y = 3.14 # Float literal

text = "Hello" # String literal

is_valid = True # Boolean literal

not_assigned = None # None literal

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

# Single-line comment

"""
Multi-line comment
Explains the function below
"""

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.

age = 18

if age >= 18:
    print("You are eligible to vote.")
else:
    print("You are not eligible to vote.")

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.

numbers = [1, 2, 3, 4, 5]

for number in numbers:
    print("Number:", number)

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.

number = 1

while number <= 5:
    print("Number:", number)
    number += 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 = [1, 3, 5, 8, 10]

for num in numbers:
    if num % 2 == 0:
        print("First even number:", 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 i in range(1, 10):
    if i % 3 == 0:
        continue
    print(i)

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 unfinished_function():
    pass  # TODO: Add function code later

for i in range(5):
    if i < 3:
        pass  
    else:
        print("Value is:", i)

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.

text = "Hello, Python World!"
# Convert to lowercase
print(text.lower())  

# Convert to uppercase
print(text.upper())  

# Replace substring
print(text.replace("World", "Universe"))  

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:

Example Code:

# Example of Python String Functions
text = "Hello, World!"

# Convert to uppercase
print(text.upper())

# Output: "HELLO, WORLD!"



# Convert to lowercase
print(text.lower()) 

# Output: "hello, world!"


# Strip leading and trailing spaces
print(text.strip())  

# Output: "Hello, World!"


# Replace a substring
print(text.replace("World", "Python"))  

# Output: "  Hello, Python!  "


# Split the string into a list
words = text.split()
print(words)  

# Output: ['Hello,', 'World!']



# Find the position of a substring
print(text.find("World"))  

# Output: 8



# Join elements of a list into a string
word_list = ['Hello', 'Python']
print(" ".join(word_list))  

# Output: "Hello Python"

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.

fruits = ["apple", "banana", "cherry"]

fruits.append("orange")  # Add element

print(fruits[1])  # Access second element


fruits.remove("banana")  # Remove element
print(fruits)

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.

colors = ("red", "green", "blue")

print(colors[0])  # Access first element

# Attempting to modify will cause an error
# colors[0] = "yellow"  # 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.

  # List Example
  my_list = [1, 2, 3]

  my_list[1] = 20  # List is mutable


  # Tuple Example
  my_tuple = (1, 2, 3)

  # my_tuple[1] = 20  # Error: Tuple is immutable

Python Sets

Sets are unordered collections with no duplicate values, useful for mathematical operations like unions and intersections.

numbers = {1, 2, 3, 3, 4}

print(numbers)  #Output: {1, 2, 3, 4}

numbers.add(5)  # Add an element


print(numbers)

Python Dictionary

Dictionaries are collections of key-value pairs, enabling fast retrieval by key.

person = {"name": "Alice", "age": 25}

print(person["name"])  # Access by key

person["age"] = 26  # Update value

print(person)

Python Functions

Functions are reusable blocks of code that encapsulate specific logic. They help in making the code modular and readable.

def greet(name):
        return f"Hello, {name}"

print(greet("Alice"))

Python Lambda Functions

Lambda functions are anonymous, single-expression functions used for short, simple operations.

multiply = lambda x, y: x * y

print(multiply(2, 3))

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:

Example Code:

# Example of Python Built-in Functions

# Using print to output to console
print("Hello, Python!")

# Getting the length of a string
text = "Hello, Python!"
print(len(text))  # Output: 14

# Checking the type of a variable
x = 10
print(type(x))  # Output: 

# Converting values between types
num = "10"
print(int(num))  # Output: 10

# Creating a range of numbers
for i in range(5):
    print(i)  # Output: 0 1 2 3 4

# Finding the max and min of a list
numbers = [1, 5, 3, 9]
print(max(numbers))  # Output: 9
print(min(numbers))  # Output: 1

# Summing a list of numbers
print(sum(numbers))  # Output: 18

# Sorting a list
print(sorted(numbers))  # Output: [1, 3, 5, 9]

# Taking input from user
name = input("Enter your name: ")
print("Hello, " + name)

Python Files I/O

File I/O allows reading and writing files, enabling persistent storage of data.

with open("example.txt", "w") as file:
        file.write("Hello, file!")


with open("example.txt", "r") as file:
        content = file.read()
        print(content)

Python Modules

Modules are files containing Python code that you can import and use in other programs.

import math
print(math.sqrt(16))

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("Cannot divide by zero")

Python Date

The datetime module provides classes to manipulate date and time in Python.

from datetime import datetime

now = datetime.now()

print(now.strftime("%Y-%m-%d %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("Hello, Python world!")


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.

# Define a class
class Car:
    def __init__(self, brand, model):
        self.brand = brand # Instance variable
        self.model = model # Instance variable

    def display_info(self):
        return f"{self.brand} {self.model}"

# Create an object of Car
car1 = Car("Toyota", "Corolla")

print(car1.display_info()) # Outputs: Toyota Corolla

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.

# Define a class with a constructor
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        return f"Hello, my name is {self.name} and I am {self.age} years old."

# Create a Person object
person1 = Person("Alice", 30)

print(person1.greet()) # Outputs: Hello, my name is Alice and I am 30 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.

# Base class
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return "Animal sounds"

# Derived class inheriting from Animal
class Dog(Animal):
    def speak(self):
        return "Bark!"

# Create an object of Dog
dog1 = Dog("Buddy")

print(dog1.name) # Outputs: Buddy
print(dog1.speak()) # Outputs: Bark!

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

# Abstract Base Class
class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

# Derived class implementing area method
class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.1415 * (self.radius ** 2)

# Create a Circle object
circle = Circle(5)

print(circle.area()) # Outputs: 78.5375

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 Account:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.__balance = balance # Private attribute

    def deposit(self, amount):
        self.__balance += amount

    def withdraw(self, amount):
        if amount <= self.__balance:
            self.__balance -= amount
        else:
            print("Insufficient funds")

    def get_balance(self):
        return self.__balance

# Create an Account object
acct = Account("Alice", 1000)

acct.deposit(500)
acct.withdraw(200)

print(acct.get_balance()) # Outputs: 1300

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 Bird:
    def sound(self):
        return "Some generic bird sound"

class Sparrow(Bird):
    def sound(self):
        return "Chirp Chirp"

class Eagle(Bird):
    def sound(self):
        return "Screech"

# Using polymorphism
def make_sound(bird):
    print(bird.sound())

sparrow = Sparrow()
eagle = Eagle()

make_sound(sparrow) # Outputs: Chirp Chirp
make_sound(eagle) # Outputs: Screech

Python Database

Python MySQL

MySQL is one of the most popular relational database management systems (RDBMS) used to manage structured data. Python can easily connect to MySQL using the mysql-connector library.

To connect to MySQL, you first need to install the MySQL connector using pip install mysql-connector-python. Once installed, you can use it to interact with the MySQL server.

Example Code:

import mysql.connector

# Connect to the MySQL server
connection = mysql.connector.connect(
  host="localhost",
  user="root",
  password="yourpassword",
  database="mydatabase"
)

# Create a cursor object
cursor = connection.cursor()

# Execute a query
cursor.execute("SELECT * FROM users")

# Fetch all rows from the last executed statement
result = cursor.fetchall()
for row in result:
  print(row)

# Close the connection
connection.close()

Python MongoDB

MongoDB is a NoSQL database that allows for flexible and scalable storage of data in a JSON-like format. Python can interact with MongoDB using the pymongo library.

To install pymongo, run pip install pymongo. Once installed, it allows you to interact with MongoDB databases.

Example Code:

from pymongo import MongoClient

# Connect to MongoDB
client = MongoClient("mongodb://localhost:27017/")

# Access a database
db = client.mydatabase

# Access a collection (like a table in SQL)
collection = db.users

# Insert a document
collection.insert_one({"name": "John", "age": 25})

# Query the collection
for user in collection.find():
  print(user)

# Close the connection
client.close()

Python SQLite

SQLite is a self-contained, serverless, zero-configuration SQL database engine. Python's built-in sqlite3 library allows for easy interaction with SQLite databases.

SQLite is a great choice for small to medium-sized applications and is commonly used for embedded systems and mobile apps.

Example Code:

import sqlite3

# Connect to the SQLite database (or create it if it doesn't exist)
connection = sqlite3.connect("mydatabase.db")

# Create a cursor object
cursor = connection.cursor()

# Create a table
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)")

# Insert data into the table
cursor.execute("INSERT INTO users (name, age) VALUES ('John', 25)")

# Commit the changes
connection.commit()

# Query the database
cursor.execute("SELECT * FROM users")
result = cursor.fetchall()
for row in result:
  print(row)

# Close the connection
connection.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!