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.
Overview
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 Python
Install Python
Windows
- Go to python.org/downloads
- Download the latest Python 3.x installer
- Important: Check the box that says "Add python.exe to PATH" during installation
- Click Install Now
Verify it worked by opening Command Prompt (or PowerShell) and typing:
python --version
You should see something like Python 3.14.x.
macOS
macOS often has Python pre-installed, but it may be an old version. Install the latest with Homebrew:
brew install python
python3 --version
Linux
Most Linux distributions include Python. Verify with:
python3 --version
If missing: sudo apt install python3 (Ubuntu/Debian) or sudo dnf install python3 (Fedora).
Choose an Editor
You need a text editor to write Python code. Here are the best free options:
| Editor | Best For | Download |
|---|---|---|
| VS Code | Most people (lightweight, powerful, free) | code.visualstudio.com |
| PyCharm Community | Dedicated Python development | jetbrains.com/pycharm |
| Thonny | Absolute beginners (simplest interface) | thonny.org |
If you use VS Code, install the Python extension from the Extensions marketplace after opening it.
Your First Program
Create a file called hello.py and add:
print("Hello, World!")
Run it from the terminal:
python hello.py
You should see Hello, World! printed to the screen. Congratulations — you just wrote your first Python program.
Part 2: Python Building Blocks
Variables — Storing Information
A variable is a name that holds a value. You do not need to declare a type — Python figures it out.
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, notuser name) - Case-sensitive (
Nameandnameare different variables) - Use descriptive names (
total_priceis better thanx)
Data Types — The Kinds of Values Python Understands
| Type | What It Is | Example |
|---|---|---|
str | Text (a "string") | "Hello" or 'Hello' |
int | Whole number | 42 |
float | Decimal number | 3.14 |
bool | True or False | True, False |
list | Ordered collection | [1, 2, 3] |
dict | Key-value pairs | {"name": "Alex", "age": 30} |
None | No value | None |
You can check a value's type with:
print(type("Hello")) # <class 'str'>
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
Strings — Working with Text
Strings are text wrapped in quotes. You can use single (') or double (") quotes — they are equivalent.
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 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
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 Collections
A list holds multiple values in order. Lists are one of the most useful things in 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 Pairs
A dictionary maps keys to values — like a real dictionary maps words to definitions.
# Create a dictionary
user = {
"name": "Alex",
"email": "[email protected]",
"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 Things
If / Elif / Else — Conditional Logic
age = 25
if age < 13:
print("Child")
elif age < 18:
print("Teenager")
elif age < 65:
print("Adult")
else:
print("Senior")
# Output: Adult
Comparison operators:
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
< | Less than |
> | Greater than |
<= | Less than or equal |
>= | Greater than or equal |
Combining conditions:
age = 25
has_id = True
if age >= 18 and has_id:
print("Access granted")
if age < 18 or not has_id:
print("Access denied")
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 Collection
# 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 Changes
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 Shortcut
A compact way to create lists from loops:
# 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 Code
Functions let you write a block of code once and use it many times.
# 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 Values
def add(a, b):
return a + b
result = add(10, 20)
print(result) # 30
Default Parameters
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Alex") # Hello, Alex!
greet("Alex", "Good morning") # Good morning, Alex!
Multiple Return Values
def get_user():
return "Alex", "[email protected]", 30
name, email, age = get_user()
print(name) # Alex
print(email) # [email protected]
Practical Example — A Temperature Converter
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 Files
Reading a Text File
# 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 File
# 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 File
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 File
import csv
people = [
{"name": "Alex", "email": "[email protected]", "age": 30},
{"name": "Sarah", "email": "[email protected]", "age": 25},
]
with open("output.csv", "w", newline="") as file:
writer = csv.DictWriter(file, fieldnames=["name", "email", "age"])
writer.writeheader()
writer.writerows(people)
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 Handling
Errors happen. Instead of your program crashing, you can catch errors and handle them gracefully.
# 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 Types
| Error | When It Happens | Example |
|---|---|---|
SyntaxError | Your code has a typo or formatting error | Missing colon after if |
NameError | You used a variable that does not exist | Typo in variable name |
TypeError | Wrong type for an operation | "5" + 3 (string + int) |
ValueError | Right type, wrong value | int("hello") |
IndexError | List index out of range | my_list[99] on a 3-item list |
KeyError | Dictionary key does not exist | my_dict["missing_key"] |
FileNotFoundError | File does not exist | open("nonexistent.txt") |
ZeroDivisionError | Dividing by zero | 10 / 0 |
Part 7: Installing Packages
Python has a massive ecosystem of third-party packages. Install them with pip:
# 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
Popular Packages Worth Knowing
| Package | What It Does |
|---|---|
requests | Make HTTP requests (call APIs, download pages) — httpx is a modern alternative with async support |
pandas | Data analysis and manipulation (tables, CSV, Excel) |
openpyxl | Read and write Excel files |
flask | Build simple web applications |
beautifulsoup4 | Scrape data from web pages |
python-dotenv | Load environment variables from .env files |
pytest | Write and run tests |
Part 8: Your First Real Project — A Contact Manager
Let's put everything together. This project reads and writes contacts to a JSON file.
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:
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 Sheet
Variables and Types
name = "Alex" # str
age = 30 # int
price = 9.99 # float
is_active = True # bool
items = [1, 2, 3] # list
user = {"name": "Alex"} # dict
Common Operations
# 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 Flow
# If/else
if condition:
...
elif other_condition:
...
else:
...
# For loop
for item in collection:
...
# While loop
while condition:
...
Functions
def function_name(param1, param2="default"):
"""Description of what this function does."""
return result
Next Steps
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
Related Articles
Was this article helpful?
