Python for Complete Beginners: From Zero to Writing Real Code
Learn Python from scratch. This guide covers installation, core concepts, and builds up to a real project -- no prior programming experience needed.
Python is the most popular programming language in the world, and there's a good reason for it: the syntax reads almost like English, the ecosystem is massive, and you can use it for everything from web development to data science to automation. If you're going to learn one language first, Python is the right call.
This guide assumes you've never written a line of code. We'll start from installation, work through every core concept, and by the end you'll build a real mini-project that actually does something useful.
Installing Python
Windows
- Go to python.org/downloads
- Download the latest Python 3.x version
- Run the installer -- check "Add Python to PATH" (this is critical, don't skip it)
- Click "Install Now"
macOS
macOS comes with Python 2 pre-installed, but you need Python 3:
# If you have Homebrew:
brew install python
# Otherwise, download from python.org
Linux
Most Linux distros have Python 3 pre-installed. Check with:
python3 --version
Verify Installation
Open a terminal (Command Prompt on Windows, Terminal on macOS/Linux) and type:
python --version
# or
python3 --version
You should see something like Python 3.12.x. If you do, you're ready.
Your First Program
Open your terminal and type python (or python3). This opens the Python interactive interpreter -- you type code and see results immediately.
>>> print("Hello, world!")
Hello, world!
You just ran your first program. print() is a function that displays text on the screen. The text inside quotes is called a string.
To exit the interpreter, type exit() or press Ctrl+D (Ctrl+Z on Windows).
Writing Code in Files
The interactive interpreter is good for experimenting, but real programs live in files. Create a file called hello.py:
# hello.py
print("Hello, world!")
print("Welcome to Python!")
Run it from your terminal:
python hello.py
Lines starting with # are comments -- Python ignores them. Use comments to explain your code.
Variables and Data Types
Variables store data. In Python, you don't need to declare types -- Python figures it out.
name = "Alice" # String (text)
age = 28 # Integer (whole number)
height = 5.7 # Float (decimal number)
is_student = True # Boolean (True or False)
print(name)
print(age)
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
Strings
Strings are text. You can use single or double quotes.
greeting = "Hello"
name = 'World'
# Concatenation (joining strings)
message = greeting + ", " + name + "!"
print(message) # Hello, World!
# f-strings (the modern way -- use these)
message = f"{greeting}, {name}!"
print(message) # Hello, World!
# Useful string methods
text = " Hello, World! "
print(text.lower()) # " hello, world! "
print(text.upper()) # " HELLO, WORLD! "
print(text.strip()) # "Hello, World!" (removes whitespace)
print(text.replace("World", "Python")) # " Hello, Python! "
print(len(text)) # 17 (length including spaces)
Numbers
# Integers
x = 10
y = 3
print(x + y) # 13 (addition)
print(x - y) # 7 (subtraction)
print(x * y) # 30 (multiplication)
print(x / y) # 3.333... (division -- always returns float)
print(x // y) # 3 (floor division -- rounds down)
print(x % y) # 1 (modulo -- remainder)
print(x ** y) # 1000 (exponent)
Type Conversion
Sometimes you need to convert between types:
age = "28" # This is a string
age_number = int(age) # Now it's an integer
price = 19.99
price_string = str(price) # Now it's a string "19.99"
# This is why conversion matters:
print("I am " + str(28) + " years old") # Must convert int to str
print(f"I am {28} years old") # f-strings handle this automatically
Getting User Input
name = input("What's your name? ")
print(f"Hello, {name}!")
# input() always returns a string, so convert for numbers:
age = int(input("How old are you? "))
print(f"In 10 years, you'll be {age + 10}")
Control Flow: Making Decisions
if / elif / else
temperature = 35
if temperature > 30:
print("It's hot outside")
elif temperature > 20:
print("Nice weather")
elif temperature > 10:
print("It's cool")
else:
print("It's cold")
Important: Python uses indentation (4 spaces) to define code blocks, not curly braces like other languages. This is not optional -- it's part of the syntax.
Comparison Operators
x = 10
x == 10 # Equal to (True)
x != 5 # Not equal to (True)
x > 5 # Greater than (True)
x < 20 # Less than (True)
x >= 10 # Greater than or equal to (True)
x <= 10 # Less than or equal to (True)
Logical Operators
age = 25
has_license = True
if age >= 18 and has_license:
print("You can drive")
if age < 13 or age > 65:
print("Discounted ticket")
if not has_license:
print("Get a license first")
Loops: Doing Things Repeatedly
for Loops
# Loop through a range of numbers
for i in range(5):
print(i) # Prints 0, 1, 2, 3, 4
# Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
# Loop with index
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
while Loops
count = 0
while count < 5:
print(count)
count += 1 # Don't forget this, or you get an infinite loop!
# Practical example: input validation
while True:
answer = input("Enter 'yes' or 'no': ").lower()
if answer in ('yes', 'no'):
break # Exit the loop
print("Invalid input, try again")
break and continue
# break exits the loop entirely
for i in range(10):
if i == 5:
break
print(i) # Prints 0, 1, 2, 3, 4
# continue skips to the next iteration
for i in range(10):
if i % 2 == 0:
continue
print(i) # Prints 1, 3, 5, 7, 9
Functions: Reusable Code
Functions let you write code once and use it many times.
def greet(name):
"""Return a greeting message."""
return f"Hello, {name}!"
message = greet("Alice")
print(message) # Hello, Alice!
Parameters and Return Values
def calculate_area(length, width):
"""Calculate the area of a rectangle."""
return length * width
area = calculate_area(5, 3)
print(f"Area: {area}") # Area: 15
# Default parameters
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Alice")) # Hello, Alice!
print(greet("Alice", "Good morning")) # Good morning, Alice!
Why Functions Matter
Without functions, you'd copy-paste the same code everywhere. When you need to change it, you'd have to find and update every copy. Functions solve this:
def is_valid_email(email):
"""Basic email validation."""
return "@" in email and "." in email.split("@")[-1]
# Use it everywhere:
if is_valid_email(user_email):
create_account(user_email)
if is_valid_email(contact_email):
send_notification(contact_email)
Lists: Ordered Collections
Lists store multiple items in order.
# Creating lists
numbers = [1, 2, 3, 4, 5]
names = ["Alice", "Bob", "Charlie"]
mixed = [1, "hello", True, 3.14] # Can mix types (but usually don't)
# Accessing items (zero-indexed)
print(names[0]) # Alice
print(names[-1]) # Charlie (last item)
# Modifying lists
names.append("Diana") # Add to end
names.insert(1, "Eve") # Insert at position 1
names.remove("Bob") # Remove by value
popped = names.pop() # Remove and return last item
names.sort() # Sort in place
# Slicing
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5]) # [2, 3, 4]
print(numbers[:3]) # [0, 1, 2]
print(numbers[7:]) # [7, 8, 9]
print(numbers[::2]) # [0, 2, 4, 6, 8] (every other)
# List comprehension (powerful Python feature)
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
Common List Operations
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(len(numbers)) # 8 (length)
print(min(numbers)) # 1
print(max(numbers)) # 9
print(sum(numbers)) # 31
print(sorted(numbers)) # [1, 1, 2, 3, 4, 5, 6, 9] (returns new list)
print(5 in numbers) # True (membership check)
Dictionaries: Key-Value Pairs
Dictionaries store data as key-value pairs. Think of them as lookup tables.
person = {
"name": "Alice",
"age": 28,
"city": "New York"
}
# Accessing values
print(person["name"]) # Alice
print(person.get("email", "N/A")) # N/A (default if key missing)
# Modifying
person["email"] = "alice@example.com" # Add new key
person["age"] = 29 # Update existing key
del person["city"] # Delete a key
# Looping through dictionaries
for key, value in person.items():
print(f"{key}: {value}")
# Checking if key exists
if "name" in person:
print(f"Name is {person['name']}")
When to Use Lists vs Dictionaries
- List: ordered collection, accessed by position. "Give me the 3rd item."
- Dictionary: labeled collection, accessed by key. "Give me the item called 'name'."
# List of students
students = ["Alice", "Bob", "Charlie"]
# Dictionary of student grades
grades = {"Alice": 92, "Bob": 85, "Charlie": 78}
print(grades["Alice"]) # 92
File I/O: Reading and Writing Files
# Writing to a file
with open("notes.txt", "w") as f:
f.write("First line\n")
f.write("Second line\n")
# Reading a file
with open("notes.txt", "r") as f:
content = f.read()
print(content)
# Reading line by line
with open("notes.txt", "r") as f:
for line in f:
print(line.strip()) # strip() removes the newline
# Appending to a file
with open("notes.txt", "a") as f:
f.write("Third line\n")
The with statement automatically closes the file when you're done. Always use it.
Modules: Using Other People's Code
Python's standard library has modules for almost everything.
import random
import datetime
import os
# Random numbers
print(random.randint(1, 100)) # Random integer between 1 and 100
print(random.choice(["a", "b", "c"])) # Random choice from list
# Dates
today = datetime.date.today()
print(today) # 2026-03-26
# File system
print(os.getcwd()) # Current working directory
print(os.listdir(".")) # List files in current directory
Installing External Packages
Python has a massive ecosystem of third-party packages:
pip install requests # HTTP library
pip install flask # Web framework
pip install pandas # Data analysis
import requests
response = requests.get("https://api.github.com/users/octocat")
data = response.json()
print(data["name"])
Error Handling
Programs crash. Good programs crash gracefully.
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("Can't divide by zero")
except Exception as e:
print(f"Something went wrong: {e}")
finally:
print("This always runs")
Mini-Project: Contact Book
Let's build something real. A contact book that lets you add, search, list, and delete contacts, saved to a file.
import json
CONTACTS_FILE = "contacts.json"
def load_contacts():
"""Load contacts from file."""
try:
with open(CONTACTS_FILE, "r") as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
return {}
def save_contacts(contacts):
"""Save contacts to 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()
if not name:
print("Name cannot be empty.")
return
phone = input("Phone: ").strip()
email = input("Email: ").strip()
contacts[name] = {"phone": phone, "email": email}
save_contacts(contacts)
print(f"Added {name}.")
def search_contacts(contacts):
"""Search contacts by name."""
query = input("Search: ").strip().lower()
results = {
name: info
for name, info in contacts.items()
if query in name.lower()
}
if results:
for name, info in results.items():
print(f" {name}: {info['phone']} | {info['email']}")
else:
print("No contacts found.")
def list_contacts(contacts):
"""List all contacts."""
if not contacts:
print("No contacts yet.")
return
for name, info in sorted(contacts.items()):
print(f" {name}: {info['phone']} | {info['email']}")
def delete_contact(contacts):
"""Delete a contact by name."""
name = input("Name to delete: ").strip()
if name in contacts:
del contacts[name]
save_contacts(contacts)
print(f"Deleted {name}.")
else:
print(f"{name} not found.")
def main():
"""Main program loop."""
contacts = load_contacts()
while True:
print("\n--- Contact Book ---")
print("1. Add contact")
print("2. Search contacts")
print("3. List all contacts")
print("4. Delete contact")
print("5. Quit")
choice = input("\nChoice (1-5): ").strip()
if choice == "1":
add_contact(contacts)
elif choice == "2":
search_contacts(contacts)
elif choice == "3":
list_contacts(contacts)
elif choice == "4":
delete_contact(contacts)
elif choice == "5":
print("Goodbye!")
break
else:
print("Invalid choice. Try 1-5.")
if __name__ == "__main__":
main()
This 80-line program uses everything we covered: variables, strings, functions, dictionaries, loops, conditionals, file I/O, error handling, and modules. Save it as contacts.py and run it -- you have a working contact book.
What to Learn Next
You now know the fundamentals. Here's where to go depending on what interests you:
Web Development: Learn Flask or Django. Build a web app with routes, templates, and a database. Data Science: Learn NumPy and Pandas. Start exploring datasets and making visualizations. Automation: Learn to automate file operations, web scraping (BeautifulSoup, Selenium), and system tasks. Game Development: Try Pygame. Build simple 2D games to practice your skills. General Skill Building: Solve problems on LeetCode, HackerRank, or Project Euler. Nothing builds programming intuition faster than solving lots of small problems.The most important thing: build projects. Reading tutorials only gets you so far. The learning happens when you try to build something, get stuck, figure it out, and repeat.
For more Python tutorials, project ideas, and programming guides, check out CodeUp.