Python for Absolute Beginners: Your First 1,000 Lines

Final Exam & Certification

Complete this tutorial and pass the 12-question final exam to earn a downloadable certificate of completion.

skip to exam

Python is the most popular programming language in the world — ranked number one on the TIOBE Index at 20.97% in April 2026, leading second-place C by more than eight percentage points. The 2025 Stack Overflow Developer Survey recorded a 7-percentage-point jump in Python adoption year-over-year — the largest single-year gain of any major language — and on GitHub it dominates AI and data science with 2.6 million contributors as of Octoverse 2025. It reads like English, runs everywhere, and powers everything from simple automation scripts to multi-billion-dollar AI systems. If you have never written a single line of code in your life, this is the place to start. By the end of this guide, you will understand variables, data types, operators, conditionals, loops, functions, and basic data structures — and you will have written real, working code at every step along the way.

What's in this Python Tutorial

Programming can feel intimidating at first. The blinking cursor on a blank screen, the unfamiliar syntax, the fear that you will break something. Every developer who ever lived felt that exact hesitation at the start. The secret they all discovered is the same: you learn to code by writing code. Not by reading about it, not by watching someone else do it, but by typing it in yourself, running it, breaking it, and fixing it. This guide is designed to get your hands on the keyboard immediately. Every concept is followed by a code example you should type out and run yourself.

How This Tutorial Works (And What "Your First 1,000 Lines" Means)

This is a hands-on tutorial, not a reference. You are expected to type every code block into a Python interpreter or editor, run it, see the output, and then modify it. Reading the code is not the same as writing it — the muscle memory of typing each character is what cements the syntax in your brain. The title promises your first 1,000 lines because that is roughly the volume of code, by community consensus, where Python stops feeling alien and starts feeling like a tool you can reach for.

Here is the path you will follow:

  1. Sections 1–7 (about 280 lines): You will type every code example in this tutorial as you encounter it. By the end of the mini-project in section 7, you will have written approximately 280 lines of Python.
  2. Practice exercises (about 320 lines): After each major section, an exercise asks you to write a small program from scratch using only the concepts covered so far. Eight exercises, totaling roughly 320 lines.
  3. The Roadmap to 1,000 (about 400 lines): After the tutorial, a roadmap of four guided projects gets you from ~600 lines to over 1,000. Each project description specifies the goal, requirements, and approximate line count.

Type each example. Do each exercise. Build the four roadmap projects. By the time you finish, the title's promise will be literal — you will have written more than 1,000 lines of working Python code.

Do this now Open a plain text file on your computer and name it my_python_journey.py. As you work through this tutorial, keep that file open and paste (or better, retype) each example into it. At the end of every section, save the file and check the line count. That file is the literal record of your first 1,000 lines.
Abelson and Sussman argued that code is written primarily for human readers, with machine execution being almost incidental to that purpose. — Harold Abelson & Gerald Jay Sussman, Structure and Interpretation of Computer Programs (MIT Press, 1984)

Why Python? And How to Get Started

Python was created by Guido van Rossum at Centrum Wiskunde & Informatica (CWI) in the Netherlands, with development beginning over Christmas 1989 and the first public release arriving on February 20, 1991. Its name has nothing to do with the snake — van Rossum named it after Monty Python's Flying Circus, the British comedy series he was watching while writing it. That sense of humor is baked into Python's culture: the official documentation uses spam and eggs as example variable names instead of the traditional foo and bar. For a fuller account of the language's trajectory from a Christmas hobby project to global dominance, see how Python became popular.

Python's core design philosophy prizes readability above almost everything else. Where other languages use curly braces and semicolons to structure code, Python uses whitespace and indentation. This means Python code often looks remarkably close to plain English, which is exactly why it has become the go-to language for beginners, data scientists, web developers, cybersecurity professionals, and automation engineers alike. The guiding principles are codified in The Zen of Python — type import this in any Python interpreter to read all 19 of them. The opening line: "Beautiful is better than ugly."

As of April 2026, Python holds the number one position on the TIOBE Index with a 20.97% share, leading second-place C by more than eight percentage points. In July 2025, it briefly reached 26.98% — the highest rating any language had achieved in the index's 25-year history. The 2025 Stack Overflow Developer Survey recorded a 7-percentage-point year-over-year jump in Python adoption — the largest single-year gain of any major language in the survey's history, driven largely by the explosion in AI and machine learning work. On GitHub, Python remains the dominant language for AI and data science with 2.6 million contributors as of Octoverse 2025 (a +48% year-over-year increase), even as TypeScript edged it out for the overall #1 GitHub spot in August 2025. Its ecosystem now includes more than 736,000 packages on PyPI (the Python Package Index), and the count grows daily. Whether you want to build websites with Django, analyze data with Pandas, train machine learning models with PyTorch, or automate tedious tasks on your computer, Python has a library ready and waiting for you.

Getting Set Up

Download Python from python.org. During installation on Windows, check the box that says "Add Python to PATH" — this is critical. On macOS and Linux, Python is often pre-installed but may be an older version; install a fresh copy from python.org to be safe. Open a terminal (or Command Prompt on Windows) and type python --version (or python3 --version on macOS/Linux) to confirm it is working. You can write code in any text editor, but VS Code with the Python extension is an excellent free choice for beginners.

The Zen of Python

Type import this in any Python interpreter and press Enter. You will see all 19 guiding principles of the language, written by Tim Peters in 2004 and formalized as PEP 20. Favorites include "Readability counts," "Explicit is better than implicit," and "There should be one — and preferably only one — obvious way to do it." These aren't rules enforced by the interpreter; they're the philosophy that shapes how Python programmers think about writing good code.

Let us start with the classic first program. Open a terminal, type python (or python3 on macOS/Linux) to enter the interactive interpreter, and type the following:

python
print("Hello, World!")

When you press Enter, Python will display Hello, World! on the screen. Congratulations — you just wrote your first program. The print() function is one of Python's built-in tools. It takes whatever you put inside the parentheses and displays it as output. Simple, powerful, and something you will use in virtually every Python program you ever write.

"Talk is cheap. Show me the code." — Linus Torvalds

How to Install Python and Write Your First Program

Follow these steps to get Python running on your machine and execute your first line of code. The whole process takes about five minutes.

  1. Download Python

    Go to python.org and download the latest stable version for your operating system. As of April 2026, that is Python 3.14.4 (released April 7, 2026, containing about 337 bugfixes since 3.14.3). Python 3.13 also remains a fully supported branch through October 2026. Any version 3.10 or later works fine for everything in this guide, though 3.10 reaches end-of-life on October 31, 2026.

  2. Run the installer

    On Windows, check the box labeled "Add Python to PATH" before clicking Install Now — skipping this step is the single most common beginner mistake. On macOS and Linux, a system Python is often pre-installed, but it may be an older version. Install a fresh copy from python.org to avoid conflicts.

  3. Verify the installation

    Open a terminal (macOS/Linux) or Command Prompt (Windows) and type python --version. You should see something like Python 3.14.4 printed back. On macOS or Linux, if python points to Python 2, try python3 --version instead — that is the correct command on many Unix-based systems.

  4. Open the Python interpreter

    In the same terminal, type python (or python3 on macOS/Linux) and press Enter. The prompt changes to >>>, indicating the interactive interpreter is ready.

  5. Write your first program

    At the >>> prompt, type print("Hello, World!") and press Enter. Python displays Hello, World!. You have written and executed your first program.

Pro Tip

For writing longer scripts, use a proper code editor rather than the interactive interpreter. VS Code with the official Python extension is free, has excellent autocomplete, and runs scripts with a single button press. For a full comparison of editors, see our guide to choosing the right IDE for learning Python.

Exercise 1 · Warm-up
Print three things about yourself

Open your my_python_journey.py file. Write three separate print() calls that output, in order: your name, your favorite programming language to learn first (you may have changed your mind by section 8), and the date you started this tutorial.

Run the file. You should see three lines of output. If you do not, you have a typo — usually a missing quote or a missing parenthesis. Read the error message carefully (we will spend more time on this in section 9) and fix it.

Goal: Confirm your environment runs Python Approx. lines: 3 Concepts used: print()
Lines written ~5 / 1,000

Variables, Data Types, and Operators

You can print things now, which is a real start. But every program eventually needs to remember something — a name, a count, a setting. That is what variables are for. In this section, you will create your first variables, learn the four foundational types of data Python understands, and use operators to combine them. Type every example into your my_python_journey.py file as you go.

A variable is a name that points to a piece of data stored in your computer's memory. Think of it as a labeled container. In Python, you create a variable by simply choosing a name, using the equals sign, and assigning a value. There is no need to declare the type of data ahead of time — Python figures it out automatically through a mechanism called dynamic typing.

Do this now Type the next four lines into your file, save it, and run it with python my_python_journey.py. You should see four pieces of information print to your terminal.
python
# Creating variables
name = "Kandi"
age = 30
height = 5.7
is_student = True

# Displaying them
print(name)
print(age)
print(height)
print(is_student)

In this example, name is a string (text wrapped in quotes), age is an integer (a whole number), height is a float (a decimal number), and is_student is a boolean (either True or False). These four data types form the foundation of nearly everything you will do in Python. You can check the type of any variable using the built-in type() function:

python
print(type(name))       # <class 'str'>
print(type(age))        # <class 'int'>
print(type(height))     # <class 'float'>
print(type(is_student)) # <class 'bool'>

Python's four foundational built-in data types each have a distinct purpose. The accordion below summarizes when to reach for each one and what kind of value it stores.

Holds
Any sequence of characters wrapped in single, double, or triple quotes.
Example
name = "Kandi"
When to use
Names, messages, file contents, anything human-readable. Strings are immutable: any operation that "changes" a string actually returns a new one.
Holds
Whole numbers of arbitrary size, positive or negative. Python integers have no fixed maximum.
Example
age = 30
When to use
Counters, indexes, ages, anything you would never need a decimal for. Use floor division // with integers when you want an integer result.
Holds
Numbers with a decimal point, including scientific notation like 2.5e3 for 2500.
Example
height = 5.7
When to use
Measurements, prices, percentages, scientific values. Be aware that floating-point arithmetic carries small rounding errors — for currency, the decimal module is more accurate.
Holds
One of exactly two values: True or False (capitalized; lowercase is invalid).
Example
is_student = True
When to use
Conditional flags, the result of any comparison, the answer to any yes/no question. Booleans are technically a subtype of int: True equals 1, False equals 0.

Python also gives you a full set of operators for doing math and combining values. Arithmetic operators work exactly the way you would expect from a calculator, with a few extras like floor division and the modulo operator that returns the remainder after division.

python
# Arithmetic operators
a = 15
b = 4

print(a + b)    # 19  (addition)
print(a - b)    # 11  (subtraction)
print(a * b)    # 60  (multiplication)
print(a / b)    # 3.75 (division)
print(a // b)   # 3   (floor division, rounds down)
print(a % b)    # 3   (modulo, the remainder)
print(a ** b)   # 50625 (exponentiation, 15 to the power of 4)

You can also combine strings together using the + operator, and you can mix strings and variables elegantly using f-strings. F-strings were introduced in Python 3.6 via PEP 498 (authored by Eric V. Smith) and are now the standard way to format text output in Python. Prefix any string with f and embed any expression inside curly braces:

python
# String concatenation and f-strings
first_name = "Python"
last_name = "Learner"

# The old way
greeting = "Hello, " + first_name + " " + last_name + "!"
print(greeting)

# The modern way (f-strings)
greeting = f"Hello, {first_name} {last_name}!"
print(greeting)

# F-strings can contain expressions
price = 19.99
quantity = 3
print(f"Total cost: ${price * quantity:.2f}")
Pro Tip

Variable names in Python should be lowercase with underscores separating words (called snake_case). Names like user_age and total_price are considered Pythonic. Avoid starting names with numbers, and never use Python's reserved keywords like print, list, or type as variable names.

Reading Input, Writing Comments, and the Special Value None

Three small things complete your foundation before we start making decisions. First, your programs can ask the user for input using the built-in input() function. Whatever the user types is returned as a string — always a string, even if they type a number. Second, you can leave notes for human readers using the # symbol; Python ignores everything from the # to the end of the line. Third, Python has a special value called None that represents "no value" or "nothing here" — useful as a placeholder, a default, or a signal that a function intentionally returned nothing.

python
# Asking the user for input (this line is a comment, ignored by Python)
name = input("What is your name? ")
print(f"Nice to meet you, {name}!")

# input() ALWAYS returns a string, even if the user types a number.
# To do math with it, convert with int() or float() first.
age_text = input("How old are you? ")
age = int(age_text)
print(f"In ten years, you will be {age + 10}.")

# The special value None represents "no value yet"
favorite_color = None
print(favorite_color)         # None
print(favorite_color is None) # True

# A function with no return statement implicitly returns None
def say_hi():
    print("Hi!")

result = say_hi()
print(result)  # None — say_hi() printed something but did not return anything

The is None check is the Pythonic way to test whether a variable holds the special None value — not == None. Comments, the # symbol, and None will all show up repeatedly through the rest of this guide, so it is worth knowing them now rather than meeting them mid-project.

code builder click a token to place it

Build a Python f-string that prints a greeting using a variable. Click each token in the correct order:

your code will appear here...
f" ( !" print {name} Hello, ) name =
Why: The correct order is print(f"Hello, {name}!"). Start with the function name print, then the opening paren (, then the f-string prefix f", then the literal text Hello, , then the variable expression {name}, then the closing quote !", and finally the closing paren ). The bare name = token is a distractor — that would be variable assignment, which happens on a separate line before the print statement.
Exercise 2 · Variables & F-strings
Build a personal profile printer

Create variables for: your first name, your age in years, your height in feet (with a decimal), and a True/False flag for whether you have ever written code before today. Then print a single sentence using an f-string that uses all four variables in one line of output. The sentence should read naturally — for example: "My name is Alex, I am 28 years old, I am 5.9 feet tall, and the statement 'I have written code before' is False."

For an extra challenge, add a calculation inside the f-string: print your age multiplied by 12 (your age in months) using {age * 12}.

Goal: Practice variables, types, and f-string interpolation Approx. lines: 8 Concepts used: str, int, float, bool, f-strings
Lines written ~75 / 1,000

Making Decisions with Conditionals

Variables let your program remember things. Conditionals let it react to them. In this section, you will write code that makes choices — deciding what to print, what to do, what to skip — based on the values your variables hold. Open my_python_journey.py and add the next examples directly below your previous code.

Programs need to make decisions. Should the user be granted access? Is the password correct? Is the temperature above freezing? Python handles decision-making with if, elif (short for "else if"), and else statements. The structure relies on indentation — the code that belongs inside a conditional block must be indented by four spaces (or one tab).

python
# Basic conditional
temperature = 72

if temperature > 85:
    print("It's hot outside! Stay hydrated.")
elif temperature > 65:
    print("The weather is nice today.")
elif temperature > 45:
    print("It's a bit chilly. Grab a jacket.")
else:
    print("It's cold! Bundle up.")

You can also combine conditions using the logical operators and, or, and not. These let you build more complex decision logic in a way that reads almost like natural language:

python
# Combining conditions
age = 25
has_license = True
has_insurance = True

if age >= 16 and has_license and has_insurance:
    print("You are cleared to drive.")
else:
    print("You cannot drive yet.")

# Using 'or' and 'not'
is_weekend = False
is_holiday = True

if is_weekend or is_holiday:
    print("No alarm needed. Sleep in!")

if not is_weekend:
    print("It's a weekday.")

Python also supports comparison operators that return boolean values: == (equal to), != (not equal to), < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to). Notice that a single = is for assignment while a double == is for comparison — mixing these up is one of the most common beginner mistakes.

Fowler observed that making a computer understand code is easy; the real skill is writing code that other people can understand. — Martin Fowler, Refactoring (Addison-Wesley, 1999)
Exercise 3 · Conditionals
Build a grade calculator

Use input() to ask the user for a numeric test score between 0 and 100. Convert it to an integer with int(). Then use if, elif, and else to print a letter grade based on the standard scale: 90 and above = A, 80–89 = B, 70–79 = C, 60–69 = D, below 60 = F.

For an extra challenge, add validation: if the user types a number below 0 or above 100, print an error message instead of a grade.

Goal: Practice if/elif/else with user input Approx. lines: 14 Concepts used: input(), int(), if/elif/else, comparison operators
Lines written ~125 / 1,000

Repeating Actions with Loops

So far your programs run from top to bottom, executing each line once. Loops let you do something many times without copying and pasting. In this section you will write code that prints all the numbers in a range, walks through a list of items one at a time, and counts down to zero. Add the next examples to your file and run each one as you go.

Loops are how you tell Python to repeat an action multiple times. There are two main types: for loops and while loops. A for loop iterates over a sequence of items (like a list, a string, or a range of numbers), executing the indented block of code once for each item. A while loop keeps running as long as a condition remains true. For a thorough treatment of every loop pattern in the language, see the Python loops guide on this site.

python
# For loop with range
for i in range(5):
    print(f"Iteration number: {i}")
# Output: 0, 1, 2, 3, 4

# For loop over a list
languages = ["Python", "JavaScript", "Rust", "Go"]
for language in languages:
    print(f"I want to learn {language}")

# For loop over a string
for letter in "Python":
    print(letter)

The range() function is your best friend for generating sequences of numbers. Calling range(5) produces the numbers 0 through 4. You can also specify a start, stop, and step: range(2, 20, 3) generates 2, 5, 8, 11, 14, 17.

python
# While loop
count = 0
while count < 5:
    print(f"Count is: {count}")
    count += 1  # Don't forget this, or the loop runs forever!

# Practical example: simple countdown
import time

countdown = 5
while countdown > 0:
    print(f"Launching in {countdown}...")
    countdown -= 1
    time.sleep(1)
print("Liftoff!")
Watch Out

A while loop that never has its condition become False will run forever (an infinite loop). Always make sure your loop has a clear exit condition. If you accidentally create one, press Ctrl + C in the terminal to stop it.

Python also provides break and continue keywords for finer control inside loops. break exits the loop entirely, while continue skips the rest of the current iteration and jumps to the next one:

python
# Using break and continue
for number in range(1, 20):
    if number == 13:
        print("Skipping unlucky 13!")
        continue
    if number > 15:
        print("Stopping at 15.")
        break
    print(f"Number: {number}")
spot the bug click the line that contains the bug

The function below is supposed to print every even number from 2 to 10. It refuses to even start — Python rejects it before it runs. Click the line you think is wrong, then hit check.

1 def print_evens():
2 for i in range(1, 11):
3 if i % 2 = 0:
4 print(i)
5 print_evens()
The fix: Change if i % 2 = 0: to if i % 2 == 0:. A single = is the assignment operator (store a value in a variable). A double == is the equality operator (check whether two values are equal). Conditionals always need ==. Confusing the two is one of the most common beginner mistakes — Python will not silently let it slide; it raises a SyntaxError and refuses to run the code.
Exercise 4 · Loops
Build a multiplication table

Ask the user for a number between 1 and 12 using input(), convert it with int(), and then use a for loop with range() to print that number's multiplication table from 1 through 12. The output for the number 7 should look like:

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
... and so on through 7 x 12 = 84

Use an f-string to format each line. For an extra challenge, wrap the whole thing in a while True loop that asks for a new number after each table is printed, and use break when the user types quit.

Goal: Practice for and while loops with range() Approx. lines: 18 Concepts used: input(), int(), for, range(), while, break, f-strings
Lines written ~190 / 1,000

Organizing Code with Functions

You can already do quite a lot — print things, store values, make decisions, repeat actions. But notice what happens as your programs grow: you start writing the same few lines over and over. The grade calculator from Exercise 3 prints letter grades; what if you needed to grade five test scores instead of one? Copy-paste five times? Functions are the cure. In this section you will wrap reusable logic in named blocks, then call those blocks whenever you need them.

Functions solve this problem by letting you wrap a block of code in a reusable package, give it a name, and call it whenever you need it. You define a function with the def keyword:

python
# Defining and calling a function
def greet(name):
    """Display a personalized greeting."""
    print(f"Welcome to Python, {name}!")

greet("Kandi")
greet("Reader")
greet("World")

Functions can accept multiple parameters, return values, and even have default values for parameters that the caller may or may not provide:

python
# Function with return value and default parameter
def calculate_tip(bill_amount, tip_percent=18):
    """Calculate the tip and total for a restaurant bill."""
    tip = bill_amount * (tip_percent / 100)
    total = bill_amount + tip
    return tip, total

# Using the function
my_tip, my_total = calculate_tip(85.50)
print(f"Tip: ${my_tip:.2f}")
print(f"Total: ${my_total:.2f}")

# Overriding the default
my_tip, my_total = calculate_tip(85.50, 25)
print(f"Generous total: ${my_total:.2f}")

Notice the triple-quoted string right below the def line. That is called a docstring, and it documents what your function does. It is a Python best practice to include docstrings in every function you write. You can view a function's docstring at any time by calling help(calculate_tip) in the interpreter.

Kernighan and Plauger warned that debugging is harder than writing code, so writing maximally clever code leaves you unable to debug it. — Brian Kernighan & P.J. Plauger, The Elements of Programming Style (McGraw-Hill, 1978)
Exercise 5 · Functions
Build a unit converter with three functions

Define three functions, each with a docstring:

  • fahrenheit_to_celsius(f) — takes a Fahrenheit temperature and returns Celsius using the formula (f - 32) * 5/9
  • miles_to_km(miles) — takes miles and returns kilometers (multiply by 1.60934)
  • pounds_to_kg(pounds) — takes pounds and returns kilograms (multiply by 0.453592)

Then write a small main program that asks the user which conversion they want (using input() and an if/elif chain), prompts them for the value to convert, calls the right function, and prints the result rounded to two decimal places using {result:.2f} in an f-string.

Goal: Practice def, parameters, return values, and docstrings Approx. lines: 30 Concepts used: functions, docstrings, return, input(), float(), conditionals, f-string formatting
Lines written ~250 / 1,000

Working with Lists and Dictionaries

Every variable you have written so far holds exactly one piece of information — one name, one age, one True or False. But real programs work with collections: a list of users, a record with many fields, a roster of scores. In this section you will learn the two most important collection types in Python and use them to organize related data. Add the next examples to your file as you go.

So far, each variable has held a single value. But what if you need to store a collection of items? Python gives you powerful built-in data structures for this. The two most important ones for beginners are lists and dictionaries.

A list is an ordered, changeable collection of items enclosed in square brackets. Lists can hold any data type, and you can mix types within the same list (though it is usually cleaner to keep them consistent):

python
# Creating and manipulating lists
fruits = ["apple", "banana", "cherry", "date"]

# Accessing items by index (starts at 0)
print(fruits[0])    # apple
print(fruits[-1])   # date (last item)

# Adding and removing items
fruits.append("elderberry")
fruits.insert(1, "blueberry")
fruits.remove("cherry")
print(fruits)

# Slicing a list
print(fruits[1:3])  # ['blueberry', 'banana']

# List comprehension (a Pythonic shortcut)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = [n for n in numbers if n % 2 == 0]
print(f"Even numbers: {evens}")

# Useful list operations
print(f"Length: {len(fruits)}")
print(f"Sorted: {sorted(fruits)}")

A dictionary is an ordered collection of key-value pairs, enclosed in curly braces. Dictionaries are guaranteed to preserve insertion order as of Python 3.7 — first as a CPython implementation detail in 3.6, then officially guaranteed by the language spec in 3.7. Dictionaries are extraordinarily useful for representing structured data where each piece of information has a label:

python
# Creating and using dictionaries
student = {
    "name": "Kandi",
    "major": "Cybersecurity",
    "gpa": 3.85,
    "courses": ["Python 101", "Network Security", "Ethical Hacking"]
}

# Accessing values by key
print(student["name"])
print(student["courses"])

# Adding and updating entries
student["graduation_year"] = 2026
student["gpa"] = 3.90

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

# Checking if a key exists
if "major" in student:
    print(f"Major found: {student['major']}")
Pro Tip

Use the .get() method instead of square brackets when you are not sure a key exists: student.get("phone", "Not on file") returns the default value instead of crashing your program with a KeyError.

Exercise 6 · Lists & Dictionaries
Build a contact book

Create an empty list called contacts. Then write a while True loop that asks the user what they want to do (add, list, find, or quit):

  • add: prompt for name, phone, and email; build a dictionary from those three fields and append it to contacts
  • list: loop through every contact in contacts and print each one's fields on its own line using f-strings
  • find: prompt for a name; loop through contacts and print any that match (case-insensitive — use .lower() on both sides)
  • quit: break out of the loop

Use .get() with a default like "(none)" when printing fields that might be missing. For an extra challenge, store the contact book as a list of dictionaries where each contact also has a list of tags like ["work", "client"].

Goal: Combine lists, dictionaries, loops, conditionals, and functions Approx. lines: 35 Concepts used: lists, dictionaries, .append(), .get(), while, if/elif, break, input(), string methods
Lines written ~340 / 1,000

Putting It All Together: A Mini Project

You have now seen every core building block of Python. Time to combine them into one complete, working program. The mini project below is a password strength checker — the kind of utility you might actually use. Type the whole thing into your file. Run it. Then come back and read it again, line by line, and notice how every concept from sections 2 through 6 shows up: variables, conditionals, loops, functions, lists, and dictionaries all working together.

The best way to cement what you have learned is to build something. Here is a small but complete program that combines variables, input, conditionals, loops, functions, lists, and dictionaries into a working password strength checker:

python
def check_password_strength(password):
    """Analyze a password and return a strength rating."""
    score = 0
    feedback = []

    # Check length
    if len(password) >= 12:
        score += 2
    elif len(password) >= 8:
        score += 1
    else:
        feedback.append("Use at least 8 characters")

    # Check for uppercase letters
    if any(char.isupper() for char in password):
        score += 1
    else:
        feedback.append("Add uppercase letters")

    # Check for lowercase letters
    if any(char.islower() for char in password):
        score += 1
    else:
        feedback.append("Add lowercase letters")

    # Check for digits
    if any(char.isdigit() for char in password):
        score += 1
    else:
        feedback.append("Add numbers")

    # Check for special characters
    special_chars = "!@#$%^&*()_+-=[]{}|;:',.<>?/~`"
    if any(char in special_chars for char in password):
        score += 1
    else:
        feedback.append("Add special characters")

    # Determine rating
    ratings = {0: "Very Weak", 1: "Weak", 2: "Weak",
               3: "Fair", 4: "Strong", 5: "Strong",
               6: "Very Strong"}
    rating = ratings.get(score, "Very Strong")

    return rating, score, feedback

# Main program loop
print("=== Password Strength Checker ===\n")
while True:
    user_input = input("Enter a password to check (or 'quit' to exit): ")
    if user_input.lower() == "quit":
        print("Goodbye!")
        break

    rating, score, tips = check_password_strength(user_input)
    print(f"\nRating: {rating} ({score}/6)")

    if tips:
        print("Suggestions for improvement:")
        for tip in tips:
            print(f"  - {tip}")
    else:
        print("Excellent! Your password meets all criteria.")
    print()

This small project uses almost every concept covered in this tutorial. The function receives a string, analyzes it with conditionals and loops, stores results in a list and a dictionary, and returns multiple values. The main program uses a while loop with break to let the user check multiple passwords before exiting. Take the time to type it out line by line, run it, and experiment with changes.

If cybersecurity is where you want to take your Python skills, the logic patterns in this project — iterating over character data, scoring against criteria, building feedback lists — are exactly the same patterns used in real-world threat analysis and security tooling. Python's role in offensive and defensive security is substantial, and everything you have learned in this guide is directly transferable.

Ritchie held that learning a programming language requires actually writing programs in it — there is no substitute. — Dennis Ritchie, creator of the C programming language
Exercise 7 · Mini Project Extension
Extend the password checker

Take the password strength checker code above and add three new features:

  1. Reject any password that contains the user's name (ask for the name first with input(), then check with name.lower() in password.lower())
  2. Add a check for sequential characters like abc, 123, or xyz — any three-letter or three-digit run knocks one point off the score
  3. Track every password the user enters in a list called history; when they type history instead of a password, print all previously checked passwords (just for the current session — do not save them anywhere)

This is the kind of incremental change real software development looks like: take a working program, add one feature, run it, fix what broke, repeat.

Goal: Modify and extend an existing program Approx. lines added: 25 Concepts used: string methods, lists, conditionals, the in operator
Secure Code From Day One
The habits you build now are the habits you will ship with

You just built a password strength checker. Take a moment to notice something: every line of code you write is either making the world slightly safer or slightly less safe. Real software runs on real machines, holds real data about real people, and gets attacked by real adversaries. The defensive habits below are not enterprise concerns to worry about later. They are beginner concerns to internalize right now, so you never have to unlearn the unsafe shortcuts later.

  • Validate every input. If a value comes from outside your code — user input, a file, a URL, an environment variable — assume it is wrong, malicious, or malformed until you have proven otherwise. Notice how every exercise in this tutorial validates with .strip(), .isdigit(), or a length check before using the value. Make that reflexive.
  • Never put secrets in your code. Passwords, API keys, database credentials, and tokens belong in environment variables or a secrets manager — never in a Python file you might commit to GitHub. Search "GitHub leaked secrets" if you doubt how often this matters.
  • Use the secrets module, not random, for anything security-related. The random module is for games and simulations. For password generation, session tokens, or anything an attacker could exploit, use secrets.token_hex() or secrets.choice() — they are cryptographically secure.
  • Never print or log sensitive data. If your password checker actually printed the password back to the screen, that password would end up in terminal history, log files, screen recordings, and screenshots. The same goes for printing API tokens, credit card numbers, or anything else you would not put on a billboard.
  • Pin your dependencies and patch them. When you start using pip install later, every package you install is code from someone else running on your machine. Use pip install package==1.2.3 with explicit versions, and run pip-audit regularly to catch known vulnerabilities.
  • Read the error message before you Google it. Errors are not the enemy — they are how Python protects you from your own mistakes. The next section is a field guide to the ten errors you will see most often. Read errors carefully, then ask for help.

Security is not a separate skill you bolt onto Python later. It is a way of thinking that begins with your very first input() call. For deeper coverage of how attackers actually exploit insecure code in the wild, browse the threat intelligence publications at CyberSpit and NoHacky.

Lines written ~440 / 1,000

The 10 Errors Every Beginner Hits (And How to Read Them)

Every Python beginner runs into the same handful of error messages in their first month. Most tutorials skip past this entirely, leaving you to fight Stack Overflow alone the first time your terminal lights up red. The error message is not punishment — it is a precisely worded clue. Below is a field guide to the ten you will actually see, what each one means in plain English, and the exact one-line fix. Bookmark this section. You will refer back to it.

What it means
You wrote something Python cannot parse. The interpreter cannot even begin to run the file.
Most common cause
A missing colon at the end of an if, for, while, def, or class line. Or a stray quote, parenthesis, or bracket somewhere.
How to fix
Look at the line number Python prints, then look at the line just above it. Python often catches the syntax error one line late because that is when it realizes something is wrong.
What it means
Python expected the body of a function, loop, or conditional but found nothing indented underneath it.
Most common cause
You wrote def greet(): on one line and forgot to indent the next line, or you accidentally mixed tabs and spaces in the same block.
How to fix
Indent the body by exactly four spaces. Configure your editor to insert spaces (not tabs) when you press the Tab key. VS Code does this by default for Python files.
What it means
You used a variable, function, or module name that Python has never seen.
Most common cause
A typo (prnit instead of print), forgetting to import a module (random.randint without import random), or a case mismatch (Name vs name — Python is case-sensitive).
How to fix
Read the offending name carefully. Run import this, then check spelling and capitalization. If it is a function from a library, add the relevant import statement at the top of your file.
What it means
You tried to combine two values whose types do not work together — usually adding a string to a number.
Most common cause
The input() function always returns a string. Doing age = input("Age? ") followed by age + 1 raises this error because you cannot add an integer to a string.
How to fix
Wrap user input in int() or float() when you need a number: age = int(input("Age? ")). Or convert the number to a string with str() if you want to concatenate.
What it means
You tried to access an item at an index that does not exist in the list.
Most common cause
Forgetting that Python uses zero-based indexing. A list with three items has valid indices 0, 1, and 2 — not 1, 2, and 3. Calling fruits[3] on a three-item list raises this error.
How to fix
Use len(my_list) to check the actual length, or use my_list[-1] to safely grab the last item regardless of length. When iterating, prefer for item in my_list: over indexing manually.
What it means
You tried to access a dictionary key that does not exist.
Most common cause
Typo in the key name, accessing data parsed from JSON or an API where a field was missing, or assuming a key exists without checking.
How to fix
Use my_dict.get("key", default_value) instead of square brackets. The .get() method returns the default value (or None) when the key is missing instead of crashing your program.
What it means
You called a method on something that is None, which has no methods.
Most common cause
Methods like list.sort(), list.append(), and list.reverse() modify the list in place and return None. Writing sorted_list = my_list.sort() stores None in sorted_list, and then any method call on it crashes.
How to fix
Use the built-in sorted(my_list) function instead, which returns a new sorted list. As a rule, if a method modifies an object in place, expect it to return None.
What it means
Python cannot find the package you imported. It is not installed in the environment running your script.
Most common cause
You installed the package with pip but Python is using a different interpreter than pip targeted — classic on macOS where system Python and Homebrew Python coexist.
How to fix
Run python -m pip install requests instead of just pip install requests. The python -m pip form guarantees the package gets installed for the same Python interpreter that runs your code.
What it means
You divided a number by zero, which is mathematically undefined.
Most common cause
Calculating an average from an empty list, or using a denominator that came from user input or an API response that turned out to be zero.
How to fix
Check the denominator first: if count > 0: average = total / count. Or wrap the division in a try/except ZeroDivisionError block if a zero is genuinely possible and you want a fallback value.
What it means
Inside a function, you tried to read a variable before assigning to it — even though a variable with the same name exists outside the function.
Most common cause
Trying to modify a global variable inside a function: count += 1 where count was defined outside. Python sees the assignment and decides count is local, but you read it before assigning, so it crashes.
How to fix
Either pass the variable in as a parameter and return the new value (the clean way), or declare global count at the top of the function (the quick fix). Generally, prefer parameters and return values over global state.
Pro Tip

When Python prints a traceback, read it from the bottom up. The last line tells you the actual error type and message. The lines above show the call chain — how Python got from your top-level code into the function where things broke. Beginners often read the traceback top-to-bottom and panic at the unfamiliar internal function names. Skip to the bottom; the answer is almost always there.

Exercise 8 · Error Hunting
Break things on purpose, then fix them

Take any working program from the previous exercises (the contact book is a good one because it uses everything). For each of the ten error types in the field guide above, deliberately introduce that error into the code, run the program, read the traceback carefully, and then fix the error. Keep a short note for each one: what the error message said, which line Python pointed to, and what the actual fix was.

This exercise is the most useful one in the entire tutorial. Real programmers spend more time reading errors than writing code. Building the habit of causing errors on purpose — in a safe, controlled setting — takes the fear out of seeing them later in real projects.

Goal: Make Python's error messages familiar and unintimidating Approx. lines: ~100 (10 fixes plus your notes) Concepts used: all of them, applied as bugs and fixes
Lines written ~600 / 1,000

Your 1,000 Lines Roadmap: Four Projects to Finish the Journey

You are at roughly 600 lines now if you typed every example and finished every exercise. The last 400 lines come from building four small but real projects. Each one takes the concepts you learned in this tutorial and applies them to something genuinely useful — the kind of program you might actually keep on your machine and reach for again. Click any project card below to open the full step-by-step guide, including every line of solution code (gated behind a "show solution" button so you can attempt each step yourself first). Pick them in any order. Use the practice file you have been building, or start fresh project files (project_1.py, etc.).

After roadmap ~1,010 / 1,000

Finish all four and you will have crossed the 1,000-line threshold. You will have written your first 1,000 lines of Python — not the kind of throwaway tutorial code that gets deleted at the end of a video, but real programs that solve real problems for you. Keep them in a folder. Show them to someone. They are proof you can do this.

Key Takeaways and Next Steps

  1. Python reads like English. Its clean syntax and indentation-based structure make it the most accessible language for beginners. You learned to print output, store data in variables, and use f-strings for formatting.
  2. Control flow is straightforward. Conditionals (if/elif/else) let your programs make decisions, and loops (for and while) let them repeat actions efficiently.
  3. Functions keep your code organized. By wrapping reusable logic in functions with clear names and docstrings, you write code that is easier to read, test, and maintain.
  4. Lists and dictionaries are essential. These two data structures will appear in virtually every Python program you write. Master them early, and everything else becomes easier.
  5. Build projects to learn. Reading tutorials gives you knowledge, but building real programs gives you skill. Start small, break things, fix them, and gradually increase complexity.

From here, your next steps should include learning about file handling (reading and writing files with open()), error handling with try/except blocks, working with modules and packages from the Python standard library, and exploring object-oriented programming with classes. Each of these topics builds naturally on the foundation you have built today. Picking a specific domain will sharpen your skills faster than any tutorial — build a small web app with Flask, explore data with Pandas, or automate a task you actually do every day. The official Python Tutorial at docs.python.org is free, authoritative, and an excellent next read. The most important thing is to keep writing code every single day, even if it is just a few lines. Consistency beats intensity in programming, just as it does in everything else worth learning.

Einstein attributed his success less to raw intelligence than to his willingness to keep working on difficult problems longer than others would. — Albert Einstein

Python is not just a language — it is a gateway. It opens doors to web development, data science, artificial intelligence, cybersecurity, automation, and dozens of other fields. Whatever drew you to programming in the first place, Python has the tools to take you there. The journey of a thousand programs begins with a single print(). You have already taken that step. Keep going.

check your understanding question 1 of N

Frequently Asked Questions

No. Python is widely considered the most beginner-friendly programming language available. Its syntax is designed to read like English, and this guide starts from absolute zero with no assumptions about prior experience.

Download the latest stable version of Python 3 from python.org. As of April 2026 that is Python 3.14.4 (released April 7, 2026); Python 3.13 also remains supported through October 2026. Either is a great choice. Python 2 reached end-of-life in January 2020 and must not be used for new projects. Python 3.9 reached end-of-life on October 31, 2025, and Python 3.10 reaches end-of-life on October 31, 2026, so 3.11 or later is the safest pick for new code. The Python Software Foundation follows a five-year support lifecycle for each release, with two years of full bug-fix support followed by three years of security-only support (per PEP 602 and PEP 745).

A list is an ordered collection of items accessed by numeric index, such as fruits[0]. A dictionary is a collection of key-value pairs accessed by a named key, such as student["name"]. As of Python 3.7, dictionaries preserve insertion order. Use a list when order matters and items do not have labels; use a dictionary when each piece of data has a meaningful name.

With consistent daily practice, many learners become comfortable with Python fundamentals in four to eight weeks. The concepts in this guide form the core foundation and can be understood in a single focused session. Building small projects alongside your reading accelerates the timeline significantly.

Many macOS and Linux systems ship with Python 2 mapped to the python command for legacy compatibility, even though Python 2 is end-of-life. Use python3 to explicitly invoke Python 3 on these systems. After installing a fresh copy from python.org, you can verify with python3 --version. On Windows, a fresh python.org installer maps python directly to Python 3.

After mastering the basics covered here, good next steps include file handling (reading and writing files with open()), error handling with try/except blocks, working with modules and the Python standard library, and object-oriented programming with classes. From there, picking a domain — web development with Flask or Django, data analysis with Pandas, or automation with the os and pathlib modules — will sharpen your skills faster than any additional tutorial.

Yes. Python is completely free and open source. It is distributed under the Python Software Foundation License, which is GPL-compatible. You can download it at no cost from python.org, use it for personal or commercial projects, and distribute it freely. The entire standard library is included at no charge.

Yes. Python is one of the most self-teachable programming languages available. The official Python documentation at docs.python.org is comprehensive and free. Many developers have learned Python entirely through free online tutorials, practice projects, and community resources like Stack Overflow. Consistent daily practice and building real projects matters far more than formal instruction.

For beginners, VS Code (Visual Studio Code) with the official Python extension is the most practical starting point. It is free, runs on Windows, macOS, and Linux, and provides syntax highlighting, autocomplete, and a built-in terminal so you can run scripts without leaving the editor. PyCharm Community Edition is another strong free option with more Python-specific tooling out of the box. If you want to experiment without installing anything, python.org's online shell and browser-based environments like Replit let you run code immediately. Avoid using plain Notepad or TextEdit — they provide no feedback and make errors harder to spot. Once you are comfortable with the basics, the choice of editor rarely matters; what matters is that you write code every day.

In many languages, indentation is optional style. In Python, it is syntax. Python uses whitespace to define blocks of code — the body of a function, the contents of a loop, or the branch of a conditional must be consistently indented, typically by 4 spaces. If the indentation is inconsistent or missing, Python raises an IndentationError and refuses to run the code. This is deliberate. By forcing structure through whitespace, Python guarantees that code looks the same regardless of who wrote it, which makes it dramatically easier to read and understand. A practical rule: never mix tabs and spaces. Configure your editor to insert 4 spaces when you press Tab, and you will never hit this problem.

print() displays a value on the screen for a human to read — it produces output, but that value cannot be used elsewhere in your program. return sends a value back from a function so that other parts of your program can use it. For example, if a function calculates a total and uses print(total), only the screen sees that number. If it uses return total, the calling code receives the number and can store it in a variable, pass it to another function, or use it in a calculation. A good rule of thumb: use return inside functions when you need the result, and use print() when you want to show something to the user.

The # symbol starts a comment. Python ignores everything on a line after a #, so comments are notes for humans — not instructions for the interpreter. They explain why the code does what it does, flag areas that need attention, or temporarily disable a line during testing. For example: score = score + 1 # award one point. Comments are not optional decoration; they are part of writing code that other people (and your future self) can understand. The only rule is to keep them accurate — an outdated comment that contradicts the code is worse than no comment at all.

Yes, and it is one of Python's strongest domains. Security professionals use Python to write network scanners, parse log files, automate penetration testing tasks, build custom tools for threat hunting, and analyze malware behavior. Many of the most widely used security frameworks — including tools built on top of Scapy for packet manipulation and Metasploit modules written in Python — rely on the skills covered in this guide. CompTIA certifications like PenTest+ and CySA+ regularly reference Python in their exam objectives. If cybersecurity is your goal, the fundamentals here are exactly the right starting point. Variables, loops, functions, and data structures are the building blocks of every Python security automation script you will ever write.

Both are excellent first languages, and the right answer depends on what you want to build. Pick Python if you are interested in data science, machine learning, AI, scientific computing, automation, scripting, cybersecurity, or back-end web development. Python's syntax is cleaner and more forgiving for beginners, and it is the dominant language in nearly every emerging technical field. Pick JavaScript if you specifically want to build websites, browser apps, or interactive front-end experiences — it is the only language that runs natively in every web browser. Many developers learn both within the first year. If you have no preference and just want to start writing code as quickly as possible, Python's gentler learning curve makes it the more common recommendation for absolute beginners. The 2025 Stack Overflow Developer Survey reported the largest single-year usage gain of any major language went to Python (+7 percentage points), driven largely by AI work.

Yes, but with intent. AI tools are excellent at explaining concepts in different ways, generating example variations, and helping you debug confusing error messages. They are terrible at building the muscle memory that comes from typing and running your own code. The trap most beginners fall into is using AI to generate solutions before they have struggled with the problem — the struggle is where learning actually happens. A practical rule for the first three months: write every line of practice code yourself first. If you get stuck for more than 15 minutes, ask the AI to explain the concept (not solve the problem). Once you can read and understand AI-generated code line by line, you have permission to use it as a productivity tool. Until then, treat it like a tutor, not a worker. The 2025 Stack Overflow Developer Survey found that 84% of developers now use AI tools in their workflow, but 46% report they do not trust the accuracy of AI output — a number that has grown significantly. Trust your own understanding more than the autocomplete.

Far more than you would expect with the concepts in this guide alone. Realistic first projects include: a command-line to-do list that saves tasks to a text file; a number-guessing game; a unit converter (miles to kilometers, Fahrenheit to Celsius); a script that renames hundreds of files in a folder according to a pattern; a personal expense tracker that reads a CSV and prints a summary; a markdown table generator; a dice-roll simulator; the password strength checker built earlier in this guide. Slightly more ambitious second-month projects: a script that downloads weather data from a public API and emails it to you each morning; a basic web scraper that pulls headlines from a news site; a Discord or Slack bot that responds to commands; a simple flashcard quiz app. The pattern is consistent: pick something you genuinely want to use yourself, keep it small enough to finish in a weekend, and build the next one slightly larger than the last.

Python is an interpreted language with dynamic typing, which means it does more work at runtime than compiled languages like C, Rust, or Go. On pure CPU-bound benchmarks, Python is often 10 to 60 times slower than these compiled alternatives. For 99% of what you will write as a beginner, this does not matter at all — the bottleneck in real programs is almost always disk reads, network calls, or waiting for a human, not raw computation. When speed truly matters, Python programmers reach for libraries like NumPy and Pandas (whose hot loops are written in C and run at C speeds), or use the new free-threaded build introduced in Python 3.14, or rewrite the slow part in another language and call it from Python. The combination of "easy to write, fast where it counts" is exactly why Python dominates AI and data science despite being slow on paper. If you ever hit a real performance ceiling, it will be a good problem to have, and the entire ecosystem has tools to fix it.

No. Programming is fundamentally about logic, sequencing, and breaking large problems into smaller ones — not arithmetic. If you can follow a recipe, you can write code. The math you actually need for general-purpose Python is what you learned by sixth grade: addition, subtraction, multiplication, division, percentages, and the ability to read a comparison like x > 5. Specific specializations have their own math requirements — machine learning leans on linear algebra and statistics, computer graphics uses trigonometry, cryptography uses number theory — but you can write professional Python for years without touching any of that. Many career programmers describe themselves as bad at math. The skill that matters is breaking down a vague problem into precise, ordered steps, and that is a skill anyone can build with practice.

A script is any .py file you run directly to do something — python my_script.py. A module is any .py file whose code is intended to be imported and reused by other files; the file helpers.py becomes the module helpers when you write import helpers. A package is a folder containing multiple related modules (typically with an __init__.py file inside it that marks it as a package); requests, numpy, and flask are all packages. The terms blur together in practice. The same file can act as a script when run directly and as a module when imported. The Python Package Index (PyPI) hosts more than 736,000 packages as of March 2026, all installable with pip install package_name.

A virtual environment is an isolated copy of Python and its installed packages, scoped to a single project. The point is to prevent two projects from fighting over conflicting package versions — project A might need requests version 2.28 while project B needs version 2.31. For the small scripts in this guide, you do not need one. For any real project where you start installing packages with pip install, you absolutely should. Create one with python -m venv .venv in your project folder, then activate it with source .venv/bin/activate on macOS/Linux or .venv\Scripts\activate on Windows. Modern Python on macOS and many Linux distributions actually requires a virtual environment to install packages at all (per PEP 668) — so you will hit this sooner rather than later. Tools like uv and Poetry create and manage virtual environments automatically.

You are reading a Python 2 tutorial, and you should close it. Python 2 was the previous major version of the language, and one of its biggest syntactic differences is that print was a statement, written without parentheses: print "hello". In Python 3, print is a function and requires parentheses: print("hello"). Python 2 reached end-of-life on January 1, 2020 and stopped receiving security updates. Any tutorial that uses the old print syntax was written before late 2019 and is likely outdated in many other ways too. When searching for Python tutorials, prefer results from the past two to three years. The official Python documentation at docs.python.org/3 is always current and authoritative.

The name is a play on words rooted in two sides of the same person. PythonCodeCrack is run by Kandi Brian, who holds an M.S. in Cybersecurity and Information Assurance and works as an active cybersecurity defender — her daily tradecraft covers threat intelligence, detection engineering, and adversary emulation, backed by CompTIA Security+, CySA+, and PenTest+ certifications. The word "crack" nods to that security background, but that is the secondary meaning. The primary meaning is about being hooked on Python itself. The term "crack addict" has long been used in pop culture as shorthand for someone who cannot put a thing down, and Python developers famously fall into that exact relationship with the language — the clean syntax, the readability, the way idiomatic Pythonic code can express an algorithm in a handful of lines that would take a page in another language. PythonCodeCrack is written for the people addicted to that elegance: developers who read PEPs for fun, who care about the difference between a list comprehension and a generator expression, and who want tutorials that respect the craft of writing good Python rather than just gluing snippets together.

Certificate of Completion
Final Exam
Pass mark: 80% · Score 80% or higher to receive your certificate

Enter your name as you want it to appear on your certificate, then start the exam. Your name is used only to generate your certificate and is never transmitted or stored anywhere.

Question 1 of 12