Skip to main content

Python for Beginners: A Complete Getting Started Guide

Learn Python from scratch. This beginner-friendly guide covers installation, core concepts, data types, control flow, functions, file handling, and your first real project — all with practical examples.

14 min readUpdated March 29, 2026

Overviewsection

Python is the most popular programming language in the world for a reason — it reads like English, runs on every platform, and can do almost anything: automate tedious tasks, analyse data, build websites, or write security tools.

This guide is for people who have never written code before. By the end, you will understand the core building blocks of Python and be able to write useful scripts on your own.

Part 1: Setting Up Pythonsection

Install Pythonsection

Windowssection

  1. Go to python.org/downloads
  2. Download the latest Python 3.x installer
  3. Important: Check the box that says "Add python.exe to PATH" during installation
  4. Click Install Now

Verify it worked by opening Command Prompt (or PowerShell) and typing:

bash
python --version

You should see something like Python 3.14.x.

macOSsection

macOS often has Python pre-installed, but it may be an old version. Install the latest with Homebrew:

bash
brew install python
python3 --version

Linuxsection

Most Linux distributions include Python. Verify with:

bash
python3 --version

If missing: sudo apt install python3 (Ubuntu/Debian) or sudo dnf install python3 (Fedora).

Choose an Editorsection

You need a text editor to write Python code. Here are the best free options:

EditorBest ForDownload
VS CodeMost people (lightweight, powerful, free)code.visualstudio.com
PyCharm CommunityDedicated Python developmentjetbrains.com/pycharm
ThonnyAbsolute beginners (simplest interface)thonny.org

If you use VS Code, install the Python extension from the Extensions marketplace after opening it.

Your First Programsection

Create a file called hello.py and add:

python
print("Hello, World!")

Run it from the terminal:

bash
python hello.py

You should see Hello, World! printed to the screen. Congratulations — you just wrote your first Python program.


Part 2: Python Building Blockssection

Variables — Storing Informationsection

A variable is a name that holds a value. You do not need to declare a type — Python figures it out.

python
name = "Alex"
age = 30
height = 5.11
is_admin = True

print(name)    # Alex
print(age)     # 30

Rules for variable names:

  • Must start with a letter or underscore (_)
  • Cannot contain spaces (use underscores: user_name, not user name)
  • Case-sensitive (Name and name are different variables)
  • Use descriptive names (total_price is better than x)

Data Types — The Kinds of Values Python Understandssection

TypeWhat It IsExample
strText (a "string")"Hello" or 'Hello'
intWhole number42
floatDecimal number3.14
boolTrue or FalseTrue, False
listOrdered collection[1, 2, 3]
dictKey-value pairs{"name": "Alex", "age": 30}
NoneNo valueNone

You can check a value's type with:

python
print(type("Hello"))  # <class 'str'>
print(type(42))       # <class 'int'>
print(type(3.14))     # <class 'float'>

Strings — Working with Textsection

Strings are text wrapped in quotes. You can use single (') or double (") quotes — they are equivalent.

python
first_name = "Jane"
last_name = "Smith"

# Combine strings (concatenation)
full_name = first_name + " " + last_name
print(full_name)  # Jane Smith

# f-strings (the modern, preferred way to insert variables into text)
greeting = f"Hello, {first_name}! You are {30} years old."
print(greeting)  # Hello, Jane! You are 30 years old.

# Useful string methods
message = "  Hello, World!  "
print(message.strip())       # "Hello, World!" (removes whitespace)
print(message.lower())       # "  hello, world!  "
print(message.upper())       # "  HELLO, WORLD!  "
print(message.replace("World", "Python"))  # "  Hello, Python!  "

# Check length
print(len("Hello"))  # 5

# Check if text contains something
print("World" in message)  # True

Numbers — Maths in Pythonsection

python
# Basic arithmetic
print(10 + 3)   # 13 (addition)
print(10 - 3)   # 7 (subtraction)
print(10 * 3)   # 30 (multiplication)
print(10 / 3)   # 3.333... (division — always returns a float)
print(10 // 3)  # 3 (integer division — rounds down)
print(10 % 3)   # 1 (modulo — the remainder)
print(10 ** 3)  # 1000 (exponent — 10 to the power of 3)

# Converting between types
price = "49.99"
price_number = float(price)  # Convert string to decimal number
quantity = int("5")          # Convert string to whole number
label = str(100)             # Convert number to string
Tip

When you read input from a user or a file, it comes in as a string — even if it looks like a number. You need to convert it with int() or float() before doing maths with it.

Lists — Ordered Collectionssection

A list holds multiple values in order. Lists are one of the most useful things in Python.

python
# Create a list
fruits = ["apple", "banana", "cherry"]
numbers = [10, 20, 30, 40, 50]
mixed = ["hello", 42, True, 3.14]  # lists can hold different types

# Access items by position (index starts at 0)
print(fruits[0])   # "apple" (first item)
print(fruits[1])   # "banana" (second item)
print(fruits[-1])  # "cherry" (last item)

# Modify a list
fruits.append("date")         # Add to the end
fruits.insert(1, "avocado")   # Insert at position 1
fruits.remove("banana")       # Remove by value
popped = fruits.pop()         # Remove and return the last item

# Check length
print(len(fruits))  # Number of items

# Check if something is in the list
print("apple" in fruits)  # True

# Sort a list
numbers.sort()               # Sort in place (ascending)
numbers.sort(reverse=True)   # Sort descending

# Slice a list (get a sub-list)
print(numbers[1:3])   # Items at index 1 and 2
print(numbers[:3])    # First 3 items
print(numbers[2:])    # Everything from index 2 onwards

Dictionaries — Key-Value Pairssection

A dictionary maps keys to values — like a real dictionary maps words to definitions.

python
# Create a dictionary
user = {
    "name": "Alex",
    "email": "alex@example.com",
    "age": 30,
    "is_admin": True,
}

# Access values by key
print(user["name"])          # "Alex"
print(user.get("phone"))    # None (no error if key missing)
print(user.get("phone", "N/A"))  # "N/A" (default if missing)

# Add or update
user["phone"] = "555-1234"  # Add new key
user["age"] = 31            # Update existing key

# Remove
del user["is_admin"]

# Loop through a dictionary
for key, value in user.items():
    print(f"{key}: {value}")

# Check if a key exists
print("email" in user)  # True

Part 3: Control Flow — Making Decisions and Repeating Thingssection

If / Elif / Else — Conditional Logicsection

python
age = 25

if age < 13:
    print("Child")
elif age < 18:
    print("Teenager")
elif age < 65:
    print("Adult")
else:
    print("Senior")
# Output: Adult

Comparison operators:

OperatorMeaning
==Equal to
!=Not equal to
<Less than
>Greater than
<=Less than or equal
>=Greater than or equal

Combining conditions:

python
age = 25
has_id = True

if age >= 18 and has_id:
    print("Access granted")

if age < 18 or not has_id:
    print("Access denied")
Warning

A common mistake is using = (assignment) instead of == (comparison) in if statements. if x = 5 is an error — you need if x == 5.

For Loops — Repeating Over a Collectionsection

python
# Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

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

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

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

# Loop through a dictionary
user = {"name": "Alex", "age": 30}
for key, value in user.items():
    print(f"{key} = {value}")

# Loop with index
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")
# 0: apple
# 1: banana
# 2: cherry

While Loops — Repeating Until a Condition Changessection

python
count = 0
while count < 5:
    print(f"Count is {count}")
    count += 1  # This is shorthand for count = count + 1

# Breaking out of a loop
while True:
    user_input = input("Type 'quit' to exit: ")
    if user_input == "quit":
        break
    print(f"You typed: {user_input}")

List Comprehensions — A Python Shortcutsection

A compact way to create lists from loops:

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

# List comprehension (same result, one line)
squares = [x ** 2 for x in range(10)]

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

Part 4: Functions — Reusable Blocks of Codesection

Functions let you write a block of code once and use it many times.

python
# Define a function
def greet(name):
    """Say hello to someone."""
    print(f"Hello, {name}!")

# Call it
greet("Alex")   # Hello, Alex!
greet("Sarah")  # Hello, Sarah!

Functions That Return Valuessection

python
def add(a, b):
    return a + b

result = add(10, 20)
print(result)  # 30

Default Parameterssection

python
def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

greet("Alex")              # Hello, Alex!
greet("Alex", "Good morning")  # Good morning, Alex!

Multiple Return Valuessection

python
def get_user():
    return "Alex", "alex@example.com", 30

name, email, age = get_user()
print(name)   # Alex
print(email)  # alex@example.com

Practical Example — A Temperature Convertersection

python
def celsius_to_fahrenheit(celsius):
    """Convert Celsius to Fahrenheit."""
    return (celsius * 9/5) + 32

def fahrenheit_to_celsius(fahrenheit):
    """Convert Fahrenheit to Celsius."""
    return (fahrenheit - 32) * 5/9

# Use them
print(celsius_to_fahrenheit(100))  # 212.0
print(fahrenheit_to_celsius(72))   # 22.22...

Part 5: Working with Filessection

Reading a Text Filesection

python
# Read the entire file at once
with open("data.txt", "r") as file:
    content = file.read()
    print(content)

# Read line by line (better for large files)
with open("data.txt", "r") as file:
    for line in file:
        print(line.strip())  # .strip() removes trailing newline

Writing to a Filesection

python
# Write (creates file or overwrites existing)
with open("output.txt", "w") as file:
    file.write("Line 1\n")
    file.write("Line 2\n")

# Append (adds to end of existing file)
with open("output.txt", "a") as file:
    file.write("Line 3\n")

Reading a CSV Filesection

python
import csv

with open("people.csv", "r") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(f"{row['name']} - {row['email']}")

Writing a CSV Filesection

python
import csv

people = [
    {"name": "Alex", "email": "alex@example.com", "age": 30},
    {"name": "Sarah", "email": "sarah@example.com", "age": 25},
]

with open("output.csv", "w", newline="") as file:
    writer = csv.DictWriter(file, fieldnames=["name", "email", "age"])
    writer.writeheader()
    writer.writerows(people)
Tip

Always use with open(...) instead of open() alone. The with block automatically closes the file when done, even if an error occurs. This prevents data corruption and resource leaks.


Part 6: Error Handlingsection

Errors happen. Instead of your program crashing, you can catch errors and handle them gracefully.

python
# Basic try/except
try:
    number = int(input("Enter a number: "))
    result = 100 / number
    print(f"Result: {result}")
except ValueError:
    print("That's not a valid number.")
except ZeroDivisionError:
    print("You can't divide by zero.")
except Exception as e:
    print(f"Something went wrong: {e}")

Common Error Typessection

ErrorWhen It HappensExample
SyntaxErrorYour code has a typo or formatting errorMissing colon after if
NameErrorYou used a variable that does not existTypo in variable name
TypeErrorWrong type for an operation"5" + 3 (string + int)
ValueErrorRight type, wrong valueint("hello")
IndexErrorList index out of rangemy_list[99] on a 3-item list
KeyErrorDictionary key does not existmy_dict["missing_key"]
FileNotFoundErrorFile does not existopen("nonexistent.txt")
ZeroDivisionErrorDividing by zero10 / 0

Part 7: Installing Packagessection

Python has a massive ecosystem of third-party packages. Install them with pip:

bash
# Install a package
pip install requests

# Install a specific version
pip install pandas==2.2.0

# Install multiple packages from a file
pip install -r requirements.txt

# List installed packages
pip list

# Uninstall a package
pip uninstall requests
PackageWhat It Does
requestsMake HTTP requests (call APIs, download pages) — httpx is a modern alternative with async support
pandasData analysis and manipulation (tables, CSV, Excel)
openpyxlRead and write Excel files
flaskBuild simple web applications
beautifulsoup4Scrape data from web pages
python-dotenvLoad environment variables from .env files
pytestWrite and run tests

Part 8: Your First Real Project — A Contact Managersection

Let's put everything together. This project reads and writes contacts to a JSON file.

python
import json
import os

CONTACTS_FILE = "contacts.json"


def load_contacts():
    """Load contacts from the JSON file."""
    if not os.path.exists(CONTACTS_FILE):
        return []
    with open(CONTACTS_FILE, "r") as f:
        return json.load(f)


def save_contacts(contacts):
    """Save contacts to the JSON file."""
    with open(CONTACTS_FILE, "w") as f:
        json.dump(contacts, f, indent=2)


def add_contact(contacts):
    """Add a new contact."""
    name = input("Name: ").strip()
    email = input("Email: ").strip()
    phone = input("Phone: ").strip()

    if not name:
        print("Name is required.")
        return

    contacts.append({"name": name, "email": email, "phone": phone})
    save_contacts(contacts)
    print(f"Added {name}.")


def search_contacts(contacts):
    """Search contacts by name."""
    query = input("Search: ").strip().lower()
    results = [c for c in contacts if query in c["name"].lower()]

    if not results:
        print("No contacts found.")
        return

    for c in results:
        print(f"  {c['name']} | {c['email']} | {c['phone']}")


def list_contacts(contacts):
    """List all contacts."""
    if not contacts:
        print("No contacts yet.")
        return

    print(f"\n{'Name':<20} {'Email':<30} {'Phone':<15}")
    print("-" * 65)
    for c in contacts:
        print(f"{c['name']:<20} {c['email']:<30} {c['phone']:<15}")


def main():
    """Main menu loop."""
    contacts = load_contacts()
    print("Contact Manager")
    print("Commands: add, search, list, quit\n")

    while True:
        command = input("> ").strip().lower()

        if command == "add":
            add_contact(contacts)
        elif command == "search":
            search_contacts(contacts)
        elif command == "list":
            list_contacts(contacts)
        elif command == "quit":
            print("Goodbye!")
            break
        else:
            print("Unknown command. Try: add, search, list, quit")


if __name__ == "__main__":
    main()

Save this as contact_manager.py and run it:

bash
python contact_manager.py

This project uses variables, functions, lists, dictionaries, loops, conditionals, file I/O, string formatting, and user input — everything from this guide.


Quick Reference Cheat Sheetsection

Variables and Typessection

python
name = "Alex"          # str
age = 30               # int
price = 9.99           # float
is_active = True       # bool
items = [1, 2, 3]      # list
user = {"name": "Alex"}  # dict

Common Operationssection

python
# String formatting
f"Hello, {name}!"

# List operations
items.append(4)        # Add to end
items.pop()            # Remove last
len(items)             # Length
item in items          # Check membership

# Dictionary operations
user["key"]            # Get value (error if missing)
user.get("key", None)  # Get value (default if missing)
user["key"] = "value"  # Set value
del user["key"]        # Delete key

Control Flowsection

python
# If/else
if condition:
    ...
elif other_condition:
    ...
else:
    ...

# For loop
for item in collection:
    ...

# While loop
while condition:
    ...

Functionssection

python
def function_name(param1, param2="default"):
    """Description of what this function does."""
    return result

Next Stepssection

Now that you know the basics:

  • Practice daily — even 15 minutes of coding builds skill fast
  • Read our Python for Excel guide to automate spreadsheet tasks
  • Pick a project that solves a real problem for you — automating a repetitive task is the best way to learn
  • Explore the Python docs at docs.python.org — the official tutorial is excellent
  • Use AI assistants to explain error messages when you get stuck
PythonBeginnersProgrammingLearning

Was this article helpful?