Python Basics

Installation

Linux (Ubuntu/Debian)

sudo apt update
sudo apt install python3 python3-pip python3-venv

macOS

# Using Homebrew
brew install python

Windows

Download from python.org and check "Add to PATH" during install.

Verify Installation

python3 --version    # Should show 3.10+
pip3 --version       # Package manager

The REPL

Python's interactive shell for quick experimentation:

$ python3
>>> 2 + 2
4
>>> print("Hello")
Hello
>>> exit()

Useful REPL features:

  • _ holds the last result
  • help(something) shows documentation
  • dir(something) lists attributes

Running Python

Interactive Mode

python3

Run a Script

python3 script.py

Run a Module

python3 -m module_name

One-liner

python3 -c "print('Hello')"

Basic Syntax

Comments

# Single line comment

"""
Multi-line string used as
a block comment or docstring
"""

Variables

No declaration needed. Type is inferred:

name = "Alice"      # str
age = 30            # int
price = 19.99       # float
active = True       # bool
nothing = None      # NoneType

Naming Conventions

# Variables and functions: snake_case
user_name = "bob"
def calculate_total():
    pass

# Classes: PascalCase
class UserAccount:
    pass

# Constants: SCREAMING_SNAKE_CASE
MAX_CONNECTIONS = 100
API_KEY = "secret"

# Private (convention): leading underscore
_internal_value = 42

# Name mangling: double underscore
__really_private = "hidden"

Indentation

Python uses indentation (4 spaces) instead of braces:

if condition:
    # This is inside the if
    do_something()
    # Still inside
else:
    # Inside else
    do_other()

# Back outside

Never mix tabs and spaces. Configure your editor for 4 spaces.

Printing

print("Hello, World!")

# Multiple values
print("Name:", name, "Age:", age)

# Formatted strings (f-strings) - preferred
print(f"Name: {name}, Age: {age}")

# Format specifiers
pi = 3.14159
print(f"Pi is {pi:.2f}")       # Pi is 3.14
print(f"Count: {42:05d}")      # Count: 00042

# Print without newline
print("Hello", end=" ")
print("World")  # Hello World

# Print to stderr
import sys
print("Error!", file=sys.stderr)

Input

name = input("Enter your name: ")
print(f"Hello, {name}!")

# Input is always a string - convert if needed
age = int(input("Enter your age: "))
price = float(input("Enter price: "))

Operators

Arithmetic

OperatorDescriptionExample
+Addition5 + 38
-Subtraction5 - 32
*Multiplication5 * 315
/Division (float)5 / 31.666...
//Floor division5 // 31
%Modulo5 % 32
**Exponent5 ** 3125

Comparison

OperatorDescription
==Equal
!=Not equal
<Less than
>Greater than
<=Less or equal
>=Greater or equal

Logical

OperatorDescription
andBoth true
orEither true
notNegation
# Short-circuit evaluation
x = None
result = x and x.value    # Safe - won't access x.value if x is falsy
result = x or "default"   # Common pattern for defaults

Identity and Membership

# Identity (same object in memory)
a is b
a is not b

# Membership
"a" in "abc"           # True
5 in [1, 2, 3, 4, 5]   # True
"key" in {"key": 1}    # True (checks keys)

Assignment Operators

x = 10
x += 5    # x = x + 5
x -= 3    # x = x - 3
x *= 2    # x = x * 2
x /= 4    # x = x / 4
x //= 2   # x = x // 2
x **= 2   # x = x ** 2
x %= 3    # x = x % 3

Walrus Operator (3.8+)

Assign and return a value in one expression:

# Without walrus
line = input()
while line != "quit":
    print(line)
    line = input()

# With walrus
while (line := input()) != "quit":
    print(line)

# Useful in comprehensions
results = [y for x in data if (y := expensive(x)) > 0]

Type Hints

Optional but recommended for larger projects:

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

age: int = 30
prices: list[float] = [19.99, 29.99]
user: dict[str, str] = {"name": "Alice"}

# Optional values
from typing import Optional
def find_user(id: int) -> Optional[str]:
    return None  # or a string

Type hints don't enforce types at runtime - use mypy for static checking:

pip install mypy
mypy script.py

Script Structure

Basic Script

#!/usr/bin/env python3
"""Module docstring describing what this script does."""


def main():
    """Main entry point."""
    print("Hello, World!")


if __name__ == "__main__":
    main()

The if __name__ == "__main__": block only runs when the script is executed directly, not when imported as a module.

With Arguments

#!/usr/bin/env python3
"""Script that accepts command line arguments."""

import sys


def main():
    if len(sys.argv) < 2:
        print("Usage: script.py <name>")
        sys.exit(1)

    name = sys.argv[1]
    print(f"Hello, {name}!")


if __name__ == "__main__":
    main()

For complex arguments, use argparse:

import argparse

parser = argparse.ArgumentParser(description="Greet someone")
parser.add_argument("name", help="Name to greet")
parser.add_argument("-c", "--count", type=int, default=1, help="Times to greet")

args = parser.parse_args()
for _ in range(args.count):
    print(f"Hello, {args.name}!")

Practice

# 1. Variables and f-strings
name = "Python"
version = 3.12
print(f"Learning {name} {version}")

# 2. Simple calculation
width = 10
height = 5
area = width * height
print(f"Area: {area}")

# 3. User input
user = input("What's your name? ")
print(f"Nice to meet you, {user}!")

# 4. Type conversion
age_str = "25"
age = int(age_str)
next_year = age + 1
print(f"Next year you'll be {next_year}")