Headingmessage

python logo

1. Getting Started with Python

Verifying Installation

Open your terminal or command prompt and type:

python --version
# or
python3 --version

You should see a version number (e.g., Python 3.9.7).

Your First Script

Create a file named hello.py with the following content:

print("Hello, World!")

Run it from the terminal:

python hello.py

2. Basic Python Syntax

Variables and Data Types

Python is dynamically typed, meaning you don't need to declare variable types explicitly.

# Integer
age = 25

# Float
price = 19.99

# String
name = "Alice"

# Boolean
is_student = True

Comments

Use # for single-line comments.

# This is a comment and will be ignored by the interpreter

3. Data Structures

Python has four built-in data structures: List, Tuple, Set, and Dictionary.

Lists

Ordered, mutable collections.

fruits = ["apple", "banana", "cherry"]
fruits.append("date")  # Add an item
print(fruits[0])       # Access first item: "apple"

Tuples

Ordered, immutable collections.

coordinates = (10.0, 20.0)
# coordinates[0] = 5.0  # This will cause an error!

Dictionaries

Key-value pairs.

person = {
    "name": "Bob",
    "age": 30,
    "is_employed": True
}
print(person["name"])  # Output: Bob

Sets

Unordered collections of unique elements.

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

4. Control Flow

If/Else Statements

x = 10

if x > 0:
    print("Positive")
elif x == 0:
    print("Zero")
else:
    print("Negative")

Loops

For Loop: Iterates over a sequence.

for i in range(5):
    print(i)  # Prints 0, 1, 2, 3, 4

While Loop: Repeats as long as a condition is true.

count = 0
while count < 5:
    print(count)
    count += 1

5. Functions

Functions allow you to reuse code. Use the def keyword.

def greet(name):
    """This function greets the person passed in as a parameter."""
    return f"Hello, {name}!"

message = greet("Alice")
print(message)  # Output: Hello, Alice!

6. File Input/Output (I/O)

Python provides built-in functions to read from and write to files. The key concept here is the Context Manager (with statement), which ensures files are properly closed after operations, even if an error occurs.

Writing to a File

Use the open() function with mode 'w' (write) or 'a' (append).

# Mode 'w' overwrites the file if it exists, or creates a new one
with open("example.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("This is a new line.")

print("File written successfully.")

Modes Reference: - 'w': Write mode (overwrites existing content). - 'a': Append mode (adds to the end of the file). - 'r': Read mode (default, raises error if file doesn't exist).

Reading from a File

Use mode 'r' to read content.

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

# Reading line by line (useful for large files)
with open("example.txt", "r") as file:
    for line in file:
        print(line.strip())  # .strip() removes the newline character

Handling Text vs. Binary Files

For most text files, the examples above work perfectly. However, if you are dealing with images, audio, or other non-text data, you must use binary mode by adding a b to the mode string (e.g., 'rb', 'wb').

# Example: Copying an image file
with open('source.jpg', 'rb') as f_source:
    with open('destination.jpg', 'wb') as f_dest:
        f_dest.write(f_source.read())

7. What is a Virtual Environment?

A virtual environment is a self-contained directory tree that includes a Python installation for a particular version of Python, plus a number of additional packages.

Why use them?

  1. Dependency Isolation: Different projects may require different versions of the same library (e.g., Project A needs pandas==1.3.0 and Project B needs pandas==2.0.0). Virtual environments prevent conflicts.
  2. Reproducibility: Ensures that your project runs the same way on other machines.
  3. Clean Global Site-Packages: Keeps your system-wide Python installation clean by not installing packages globally.

8. Creating and Managing Virtual Environments

Python includes a module called venv (since Python 3.3) to create virtual environments.

Step 1: Create a Virtual Environment

Navigate to your project directory in the terminal and run:

python -m venv venv

This creates a folder named venv in your current directory. You can name it anything you like (e.g., .venv, env).

Step 2: Activate the Virtual Environment

  • On macOS/Linux:

    source venv/bin/activate
    
  • On Windows (Command Prompt):

    venv\Scripts\activate.bat

- **On Windows (PowerShell):**
venv\Scripts\Activate.ps1
  
**Tip:** Once activated, you should see the name of your virtual environment (e.g., `(venv)`) at the beginning of your terminal prompt. Now, when you install packages using `pip`, they will be installed only into this virtual environment.
pip install requests
Run your Python scripts as usual:
python my_script.py
When you are done working in the virtual environment, you can exit it by typing:
deactivate
Your terminal prompt will return to normal. To share your project's dependencies with others, generate a `requirements.txt` file:
pip freeze > requirements.txt
Others can then recreate the environment using:
pip install -r requirements.txt