Python Programming

Python is a versatile, high-level programming language known for its readability and clean syntax. This guide is designed to help you understand the fundamental concepts of Python, starting from installation to intermediate topics like file handling and error management.


1. Installation and Setup

Installing Python

To run Python code, you need the Python interpreter installed on your system.
1. Visit the official website: python.org.
2. Download the latest stable version for your operating system (Windows, macOS, or Linux).
3. During installation on Windows, ensure you check the box that says "Add Python to PATH". This allows you to run Python from your command line.

Running Python

You can write and run Python code in several ways:

  • Interactive Shell (REPL): Open your terminal or command prompt, type python (or python3), and press Enter.
  • Scripting: Write your code in a text editor (such as VS Code, PyCharm, or Notepad++), save the file with a .py extension, and run it from the terminal:
    python myscript.py

Here is your first Python program:

print("Hello, World!")

2. Variables and Data Types

In Python, variables are used to store data values. You do not need to declare the type of a variable explicitly; Python infers it automatically.

Common Data Types

  • Integer (int): Whole numbers.
  • Float (float): Numbers with decimal points.
  • String (str): Text characters enclosed in single or double quotes.
  • Boolean (bool): Either True or False.
# Variable assignment
age = 25                 # Integer
price = 19.99            # Float
name = "Alice"           # String
is_active = True         # Boolean

# Checking data types
print(type(age))        # Output: <class 'int'>
print(type(price))      # Output: <class 'float'>

Type Conversion

You can convert one data type to another using built-in functions:

# Convert float to integer
x = int(3.14)  # x becomes 3

# Convert integer to string
y = str(100)   # y becomes "100"

# Convert string to float
z = float("5.5") # z becomes 5.5

3. Basic Operators

Operators allow you to perform calculations and make comparisons.

Arithmetic Operators

a = 10
b = 3

print(a + b)   # Addition (13)
print(a - b)   # Subtraction (7)
print(a * b)   # Multiplication (30)
print(a / b)   # Division (3.3333...)
print(a // b)  # Floor Division (removes decimals: 3)
print(a % b)   # Modulo (remainder of division: 1)
print(a ** b)  # Exponentiation (10 raised to the power of 3: 1000)

Comparison Operators

These return a boolean value (True or False).

x = 5
y = 10

print(x == y)  # Equal to (False)
print(x != y)  # Not equal to (True)
print(x > y)   # Greater than (False)
print(x < y)   # Less than (True)
print(x >= 5)  # Greater than or equal to (True)

Logical Operators

Used to combine conditional statements.

a = True
b = False

print(a and b) # False (both must be True)
print(a or b)  # True (at least one must be True)
print(not a)   # False (reverses the boolean)

4. Control Flow (Conditionals and Loops)

Control flow statements determine the order in which code execution occurs based on certain conditions.

If-Elif-Else Statement

Python uses indentation (four spaces is standard) instead of curly braces to define blocks of code.

score = 85

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: F")

For Loop

A for loop is used to iterate over a sequence (such as a list, string, or range of numbers).

# Iterating through a range of numbers (0 to 4)
for i in range(5):
    print(i)

# Iterating through a string
for char in "Python":
    print(char)

While Loop

A while loop runs as long as a specified condition remains True.

count = 0
while count < 3:
    print("Count is:", count)
    count += 1  # Equivalent to count = count + 1

5. Data Structures

Python offers built-in data structures to organize and manage collections of data.

Lists

Lists are ordered, mutable (changeable), and allow duplicate elements.

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

# Accessing elements (0-indexed)
print(fruits[0])  # Output: apple

# Modifying a list
fruits.append("orange")      # Adds to the end
fruits.remove("banana")      # Removes specific item
fruits[1] = "blueberry"      # Replaces item at index 1

print(fruits)  # Output: ['apple', 'blueberry', 'orange']

Tuples

Tuples are ordered but immutable (cannot be changed after creation). They are defined with parentheses.

coordinates = (10, 20)
# coordinates[0] = 15  # This will raise a TypeError
print(coordinates[0])  # Output: 10

Dictionaries

Dictionaries store data in key-value pairs. They are unordered, mutable, and keys must be unique.

user = {
    "name": "Sarah",
    "age": 30,
    "email": "[email protected]"
}

# Accessing values
print(user["name"])  # Output: Sarah

# Adding or updating pairs
user["age"] = 31             # Updates age
user["city"] = "New York"    # Adds new key-value pair

print(user)

Sets

Sets are unordered collections of unique elements. They are useful for removing duplicates.

unique_numbers = {1, 2, 3, 3, 4}
print(unique_numbers)  # Output: {1, 2, 3, 4} (duplicates are automatically removed)

6. Functions

Functions are blocks of reusable code designed to perform a single action.

# Defining a function
def greet(name="Guest"):
    return f"Hello, {name}!"

# Calling the function with an argument
message = greet("Alice")
print(message)  # Output: Hello, Alice!

# Calling the function with the default argument
default_message = greet()
print(default_message)  # Output: Hello, Guest!

7. File Handling

Python can read from and write to files on your computer. Using the with statement is recommended, as it automatically closes the file after the block of code finishes executing.

Writing to a File

# "w" mode overwrites the file. "a" mode appends to the file.
with open("sample.txt", "w") as file:
    file.write("This is a line of text.\n")
    file.write("This is the second line.")

Reading from a File

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

8. Error and Exception Handling

Errors can occur during program execution. To prevent your program from crashing, you can catch and handle exceptions using try and except blocks.

try:
    number = int(input("Enter a number: "))
    result = 10 / number
    print("The result is:", result)
except ZeroDivisionError:
    print("Error: You cannot divide by zero.")
except ValueError:
    print("Error: Please enter a valid numeric integer.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

9. Working with Modules and Libraries

Python comes with a large standard library of modules that you can import and use.

# Importing built-in modules
import math
import datetime

# Using functions from the math module
print(math.sqrt(16))  # Output: 4.0

# Using the datetime module
current_time = datetime.datetime.now()
print("Current date and time:", current_time)

Installing Third-Party Packages

You can expand Python's capabilities by installing packages created by the community. This is done using pip (Python's package installer) through your terminal:

pip install requests

Once installed, you can import and use the library in your code:

import requests

# Example of sending a simple GET request
# response = requests.get("https://api.github.com")
# print(response.status_code)

The guide was created in June 2026.