Learn Python Basics in 30 Minutes: A Fast-Track Introduction

This is a rapid-fire introduction to Python. No filler, no lengthy explanations, just the core concepts you need to start writing useful code. Each section gives you a brief explanation followed by a code example. Read it, type it, and move on. By the end, you will understand the fundamental building blocks of Python and be ready to tackle real projects.

You will need Python installed on your computer. Download it from python.org, open a terminal or command prompt, and type python to start the interactive interpreter. Alternatively, use an online environment like Google Colab or Replit and skip the installation entirely.

Variables and Types

A variable is a name that refers to a value. You create one by assigning a value with the equals sign. Python figures out the type automatically, so you do not need to declare it.

name = "Alice"          # str (text)
age = 30                # int (whole number)
salary = 75000.50       # float (decimal number)
is_active = True        # bool (True or False)

print(name)             # Alice
print(type(age))        # <class 'int'>

Python has four basic types you will use constantly: strings for text, integers for whole numbers, floats for decimals, and booleans for true/false values.

Strings

Strings are sequences of characters enclosed in quotes. You can use single quotes or double quotes, they are identical. Python provides powerful built-in methods for manipulating strings.

greeting = "Hello, World!"

# Basic operations
print(len(greeting))            # 13 (length)
print(greeting.upper())         # HELLO, WORLD!
print(greeting.lower())         # hello, world!
print(greeting.replace("World", "Python"))  # Hello, Python!

# String concatenation
first = "Jane"
last = "Doe"
full = first + " " + last       # "Jane Doe"

# f-strings (the modern way to format strings)
age = 28
message = f"{first} is {age} years old"
print(message)                  # Jane is 28 years old

# Slicing
print(greeting[0])              # H (first character)
print(greeting[0:5])            # Hello (characters 0 through 4)
print(greeting[-1])             # ! (last character)

F-strings, created by putting an f before the opening quote, are the cleanest way to embed variables inside strings. Use them everywhere.

Lists

A list is an ordered, mutable collection of items. Lists are one of the most frequently used data structures in Python.

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

# Accessing elements
print(fruits[0])            # apple (first item)
print(fruits[-1])           # cherry (last item)

# Modifying
fruits.append("date")       # Add to end: ["apple", "banana", "cherry", "date"]
fruits.insert(1, "avocado") # Insert at index 1
fruits.remove("banana")     # Remove by value
popped = fruits.pop()       # Remove and return last item

# Length and membership
print(len(fruits))          # Number of items
print("apple" in fruits)   # True (membership test)

# Slicing
numbers = [10, 20, 30, 40, 50]
print(numbers[1:3])         # [20, 30]
print(numbers[:3])          # [10, 20, 30]

# Sorting
numbers.sort()              # Sort in place
sorted_nums = sorted(numbers, reverse=True)  # Returns new sorted list

Lists can hold any type of data, including other lists. They are your go-to data structure for ordered collections.

Dictionaries

A dictionary stores key-value pairs. It lets you look up values by their key, like a real dictionary lets you look up definitions by word.

person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

# Accessing values
print(person["name"])           # Alice
print(person.get("age"))       # 30
print(person.get("phone", "N/A"))  # N/A (default if key missing)

# Modifying
person["email"] = "alice@example.com"  # Add new key
person["age"] = 31                     # Update existing key
del person["city"]                     # Delete a key

# Useful methods
print(person.keys())           # dict_keys(['name', 'age', 'email'])
print(person.values())         # dict_values(['Alice', 31, 'alice@example.com'])
print(person.items())          # Key-value pairs as tuples

# Check if key exists
if "name" in person:
    print("Name found")

Dictionaries are everywhere in Python. They are the natural choice whenever you need to associate pieces of data with labels.

If/Else (Conditional Logic)

Conditional statements let your code make decisions. Python uses indentation (spaces or tabs) to define code blocks, not curly braces like many other languages.

age = 20

if age >= 21:
    print("Can drink alcohol")
elif age >= 18:
    print("Adult, but cannot drink")
else:
    print("Minor")

# Comparison operators: ==, !=, <, >, <=, >=
# Logical operators: and, or, not

temperature = 72
is_sunny = True

if temperature > 70 and is_sunny:
    print("Great day for a walk")

if not is_sunny:
    print("Bring an umbrella")

# Checking for empty/None values
name = ""
if not name:
    print("Name is empty")

Indentation is not optional in Python. It is how the language knows which code belongs inside a block. Use four spaces per level, which is the standard convention.

For Loops

For loops iterate over sequences like lists, strings, ranges, and other iterable objects.

# Loop over a list
colors = ["red", "green", "blue"]
for color in colors:
    print(color)

# Loop over a range of numbers
for i in range(5):           # 0, 1, 2, 3, 4
    print(i)

for i in range(2, 8):        # 2, 3, 4, 5, 6, 7
    print(i)

for i in range(0, 10, 2):    # 0, 2, 4, 6, 8 (step of 2)
    print(i)

# Loop over a dictionary
person = {"name": "Alice", "age": 30}
for key, value in person.items():
    print(f"{key}: {value}")

# enumerate gives you the index and value
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

The range() function is your tool for looping a specific number of times. Remember that it stops before the end number, so range(5) gives you 0 through 4.

While Loops

While loops repeat as long as a condition is true. They are useful when you do not know in advance how many iterations you need.

count = 0
while count < 5:
    print(count)
    count += 1          # 0, 1, 2, 3, 4

# break exits the loop immediately
while True:
    user_input = input("Enter 'quit' to exit: ")
    if user_input == "quit":
        break
    print(f"You typed: {user_input}")

# continue skips to the next iteration
for i in range(10):
    if i % 2 == 0:
        continue        # Skip even numbers
    print(i)            # 1, 3, 5, 7, 9

Be careful with while loops. If the condition never becomes false, the loop runs forever. Always make sure something inside the loop moves you toward the exit condition.

Functions

Functions are reusable blocks of code. They take inputs (parameters), do something, and optionally return a result. Functions are how you organize your code and avoid repetition.

# Basic function
def greet(name):
    return f"Hello, {name}!"

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

# Default parameters
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("Bob"))              # Hello, Bob!
print(greet("Bob", "Hey"))       # Hey, Bob!

# Multiple return values
def get_stats(numbers):
    return min(numbers), max(numbers), sum(numbers) / len(numbers)

lowest, highest, average = get_stats([10, 20, 30, 40])
print(f"Low: {lowest}, High: {highest}, Avg: {average}")

# Functions with *args and **kwargs
def summarize(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

summarize(name="Alice", age=30, city="NYC")

If you find yourself copying and pasting code, that is a signal to write a function instead. Name your functions with verbs that describe what they do: calculate_total, send_email, get_user.

Basic File I/O

Reading and writing files is one of the most common tasks in Python. The with statement ensures files are properly closed after use.

# Writing to a file
with open("output.txt", "w") as f:
    f.write("First line\n")
    f.write("Second line\n")

# Reading an entire file
with open("output.txt", "r") as f:
    content = f.read()
    print(content)

# Reading line by line
with open("output.txt", "r") as f:
    for line in f:
        print(line.strip())    # strip() removes the trailing newline

# Appending to a file
with open("output.txt", "a") as f:
    f.write("Third line\n")

# Reading into a list of lines
with open("output.txt", "r") as f:
    lines = f.readlines()
    print(lines)               # ['First line\n', 'Second line\n', 'Third line\n']

The mode parameter controls what you can do: "r" for reading, "w" for writing (overwrites existing content), and "a" for appending. Always use the with statement, it handles closing the file for you even if an error occurs.

Importing Modules

Python's power comes from its vast ecosystem of modules and packages. Importing them gives you access to pre-built functionality.

# Import an entire module
import math
print(math.sqrt(16))       # 4.0
print(math.pi)             # 3.141592653589793

# Import specific functions
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d"))   # 2026-03-14

# Import with an alias
import statistics as stats
data = [10, 20, 30, 40, 50]
print(stats.mean(data))     # 30
print(stats.median(data))   # 30

# Common built-in modules
import os               # Operating system interface
import json             # JSON parsing and creation
import csv              # CSV file reading and writing
import random           # Random number generation

print(random.randint(1, 100))     # Random integer between 1 and 100
print(os.getcwd())                # Current working directory

Python comes with a "batteries included" standard library that covers file handling, networking, data parsing, math, and much more. Before writing something from scratch, check if a module already exists for it.

List Comprehensions

List comprehensions are a concise way to create lists. They are one of Python's most distinctive and powerful features.

# Traditional approach
squares = []
for x in range(10):
    squares.append(x ** 2)

# List comprehension (same result, one line)
squares = [x ** 2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# With a condition (filtering)
even_squares = [x ** 2 for x in range(10) if x % 2 == 0]
# [0, 4, 16, 36, 64]

# Transforming strings
names = ["alice", "bob", "charlie"]
capitalized = [name.capitalize() for name in names]
# ['Alice', 'Bob', 'Charlie']

# Dictionary comprehension
prices = {"apple": 1.50, "banana": 0.75, "cherry": 2.00}
expensive = {k: v for k, v in prices.items() if v > 1.00}
# {'apple': 1.5, 'cherry': 2.0}

List comprehensions are not just shorter. They are more readable once you are familiar with the pattern. The format is always: [expression for item in iterable if condition].

Error Handling

Errors happen. Python's try/except blocks let you handle them gracefully instead of crashing.

# Basic error handling
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

# Handling multiple error types
try:
    number = int(input("Enter a number: "))
    result = 100 / number
except ValueError:
    print("That is not a valid number")
except ZeroDivisionError:
    print("Cannot divide by zero")

# Catch-all with the error message
try:
    data = open("nonexistent.txt")
except FileNotFoundError as e:
    print(f"Error: {e}")

# try/except/finally
try:
    f = open("data.txt", "r")
    content = f.read()
except FileNotFoundError:
    print("File not found")
finally:
    print("This runs no matter what")

Do not catch every possible exception with a bare except:. Be specific about the errors you expect, and let unexpected errors surface so you can fix the underlying problem.

Putting It All Together

Here is a short script that combines several concepts you just learned. It reads a CSV-like file, processes the data, and writes a summary.

def analyze_sales(filename):
    """Read sales data and return summary statistics."""
    totals = {}

    with open(filename, "r") as f:
        for line in f:
            product, amount = line.strip().split(",")
            amount = float(amount)
            totals[product] = totals.get(product, 0) + amount

    return totals

def write_report(totals, output_file):
    """Write a sales summary report."""
    with open(output_file, "w") as f:
        f.write("Sales Summary\n")
        f.write("=" * 30 + "\n")
        for product, total in sorted(totals.items()):
            f.write(f"{product}: ${total:,.2f}\n")
        f.write(f"\nGrand Total: ${sum(totals.values()):,.2f}\n")

# Run the analysis
try:
    results = analyze_sales("sales.csv")
    write_report(results, "report.txt")
    print("Report generated successfully")
except FileNotFoundError:
    print("Sales file not found")

This script uses functions, file I/O, dictionaries, string formatting, loops, and error handling. If you understand every line, you have a solid grasp of Python basics.

What to Learn Next

You now have the vocabulary and mental model to read and write basic Python. Here is where to go from here.

Object-oriented programming. Learn how to create classes and objects. This lets you organize larger programs and model real-world entities in your code.

Third-party packages. Learn to install packages with pip and explore the ecosystem. Start with requests for web APIs, pandas for data analysis, or flask for web applications.

Virtual environments. Learn to use venv to create isolated Python environments for different projects. This prevents package conflicts and is a professional best practice.

Testing. Learn to write tests with pytest. Testing your code is how you gain confidence that it works correctly and continues to work as you make changes.

Version control. Learn Git to track changes to your code, collaborate with others, and maintain a history of your work.

The fundamentals you learned in this guide are the foundation for everything else. Every advanced Python topic builds on variables, data structures, control flow, functions, and file I/O. Master these, and the rest follows naturally.

Continue learning with our free Python for Business Beginners textbook.