DEV Community

Manu Kipkoech
Manu Kipkoech

Posted on

Python 101: Your Complete Beginner's Guide from Setup to Running Programs

Learning to code can feel intimidating at first, especially when you see terminals, unfamiliar symbols, and technical jargon everywhere. Python is one of the best languages to start with because it was designed to be readable. In many cases, Python code reads almost like plain English, which lets you focus on solving problems instead of memorizing complicated punctuation.

Whether you want to automate boring spreadsheet tasks, explore data, build web tools, or simply understand how software works, this guide walks you through everything from installing Python on your computer to writing and running five practical programs.

1. Why Start with Python?

Before we install anything, it helps to understand why millions of beginners and professionals choose Python:

  • Clean, readable syntax: Python uses indentation (spaces) rather than curly braces to organize code blocks, making programs easier to scan and debug.
  • Runs everywhere: The same Python script generally works on Windows, macOS, and Linux with little or no modification.
  • Massive ecosystem: Once you master the basics, you can use Python for data analytics, automation, web backends, and machine learning.
  • Immediate feedback: You can write a small five-line script, run it in seconds, and see the result right away.

2. Setting Up Your Python Environment

To write and run Python programs on your own machine, you need two pieces:

  1. Python itself (the interpreter): This is the engine that reads your .py files and executes your instructions.
  2. A code editor: This is where you write and organize your files. You can also run quick experiments in the browser with Google Colab without installing anything, though having a local setup is essential for real projects.

Step 1: Install Python

  1. Visit the official Python Downloads page and download the latest Python 3 installer for your operating system.
  2. Important for Windows users: On the first screen of the installer, check the box that says "Add python.exe to PATH" before clicking Install Now. This ensures your terminal recognizes the python or python3 command from any folder.
  3. On macOS, run the downloaded .pkg installer and follow the prompts. On Linux, Python 3 is often pre-installed, or you can install it via your distribution's package manager.

Step 2: Install a Code Editor (VS Code)

While you can write Python in any plain text editor, Visual Studio Code (VS Code) is free, lightweight, and beginner-friendly. Download the installer for your system, open VS Code, and install the official Python extension from Microsoft in the Extensions panel.

Step 3: Verify Your Setup

Open your terminal (Command Prompt or PowerShell on Windows, Terminal on macOS/Linux, or the built-in terminal inside VS Code) and run:

python3 --version
Enter fullscreen mode Exit fullscreen mode

(On Windows, if python3 is not recognized, try python --version.)

If you see a version number such as Python 3.11.2 or newer, your engine is ready.


3. Your First Python Program (01_hello_python.py)

Create a new folder on your computer called python101 and open it in VS Code. Inside that folder, create a file named 01_hello_python.py. Every Python script uses the .py file extension.

Type the following code into 01_hello_python.py:

# 01_hello_python.py
# Your very first Python program!

print("Hello, Python!")
print("Welcome to your coding journey.")

# Python can also do math right away
print("2 + 3 =", 2 + 3)
print("10 * 5 =", 10 * 5)
Enter fullscreen mode Exit fullscreen mode

How It Works

  • Comments (#): Any line starting with # is a comment. Python completely ignores comments when running your code—they exist solely to leave helpful notes for yourself and other humans.
  • The print() function: print() displays text or calculation results on your screen. Text must be wrapped in quotation marks ("..." or '...') so Python knows it is literal text rather than a command.
  • Built-in math: You can pass numbers and operators (+ for addition, * for multiplication) directly to print(), and Python evaluates the math before displaying the answer.

Save the file (Ctrl+S on Windows/Linux or Cmd+S on macOS), then run it in your terminal:

python 01_hello_python.py
Enter fullscreen mode Exit fullscreen mode

Terminal output showing python --version and 01_hello_python.py execution

Seeing your own code print output in the terminal is your first milestone. From here, every program you build follows the same cycle: edit the .py file, save it, and run it.


4. Variables and Data Types (02_variables_and_types.py)

Real programs need to remember information—such as a user's name, an item price, or whether a task is finished. In Python, you store information inside variables. Think of a variable as a labeled box that holds a value.

Create a second file named 02_variables_and_types.py and add this code:

# 02_variables_and_types.py
# Storing information in variables and checking their data types

learner_name = "Alex"          # str (text)
days_learning = 3              # int (whole number)
hours_per_day = 1.5            # float (decimal number)
is_enjoying_python = True      # bool (True or False)

total_hours = days_learning * hours_per_day

print(f"Learner: {learner_name}")
print(f"Total study time: {total_hours} hours")
print("Type of learner_name:", type(learner_name).__name__)
print("Type of days_learning:", type(days_learning).__name__)
print("Type of hours_per_day:", type(hours_per_day).__name__)
print("Type of is_enjoying_python:", type(is_enjoying_python).__name__)
Enter fullscreen mode Exit fullscreen mode

Key Concepts in This Script

  1. Four core data types:
    • String (str): Text wrapped in quotes, like "Alex".
    • Integer (int): Whole numbers with no decimal point, like 3.
    • Float (float): Numbers with a decimal point, like 1.5.
    • Boolean (bool): A simple yes-or-no flag that is either True or False (always capitalized in Python).
  2. Naming variables cleanly: Use lowercase words separated by underscores (learner_name, hours_per_day). This style—known as snake_case—is the standard Python convention because it is easy to read.
  3. Formatted strings (f-strings): Putting the letter f right before the opening quote (f"Learner: {learner_name}") lets you drop variables directly inside {curly braces}. Python automatically replaces each placeholder with its current value.
  4. Checking types: The type() function reveals what kind of data a variable currently holds, which is invaluable when debugging unexpected errors.

Run the script in your terminal:

python 02_variables_and_types.py
Enter fullscreen mode Exit fullscreen mode

Terminal output for 02_variables_and_types.py


5. Making Decisions with Conditionals (03_conditionals_and_decisions.py)

Programs become truly useful when they can react differently depending on the data they receive. In Python, you make decisions using if, elif (short for "else if"), and else.

Create 03_conditionals_and_decisions.py:

# 03_conditionals_and_decisions.py
# Making decisions with if, elif, and else

daily_budget = 50.00
total_spent = 38.50

remaining = daily_budget - total_spent
print(f"Spent: ${total_spent:.2f} | Remaining: ${remaining:.2f}")

if remaining > 15:
    print("Status: You are well within your daily budget.")
elif remaining >= 0:
    print("Status: You are close to your daily limit. Spend carefully!")
else:
    print(f"Status: Over budget by ${abs(remaining):.2f}.")
Enter fullscreen mode Exit fullscreen mode

How It Works

  • Top-to-bottom evaluation: Python checks the if condition first (remaining > 15). Because remaining is 11.50, that condition is False, so Python moves down to elif remaining >= 0. That condition is True, so Python runs that indented block and skips else.
  • Indentation matters: Notice the four spaces before each print(...) inside the if, elif, and else blocks. Indentation tells Python which lines belong to each branch. Mixing spaces and tabs—or forgetting to indent—will trigger an IndentationError.
  • Formatting currency: Inside the f-string, :.2f tells Python to display the number with exactly two decimal places (for example, 38.50 instead of 38.5).
  • abs(): If you go over budget, remaining becomes negative. abs(remaining) converts it to a positive number so the message reads cleanly.

Run it to see the decision logic in action:

python 03_conditionals_and_decisions.py
Enter fullscreen mode Exit fullscreen mode

Terminal output for 03_conditionals_and_decisions.py

Try changing total_spent to 20.00 or 62.00 and re-running the file to watch the output branch change.


6. Storing Collections and Repeating Work (04_lists_and_loops.py)

What if you need to store five topics, fifty prices, or a thousand customer names? Creating separate variables (topic1, topic2, topic3) quickly becomes unmanageable. Instead, Python gives you lists to hold ordered collections and loops to repeat actions automatically.

Create 04_lists_and_loops.py:

# 04_lists_and_loops.py
# Storing multiple items in a list and repeating actions with loops

study_topics = ["Setup", "Variables", "Conditionals", "Loops", "Functions"]

print("Python 101 Roadmap:")
for index, topic in enumerate(study_topics, start=1):
    print(f"  {index}. {topic}")

print("\nQuick countdown before coding:")
count = 3
while count > 0:
    print(f"  {count}...")
    count -= 1
print("  Go!")
Enter fullscreen mode Exit fullscreen mode

How It Works

  • Lists ([...]): Square brackets create a list. study_topics holds five strings in order.
  • for loops: A for loop steps through every item in a collection one by one. Using enumerate(study_topics, start=1) gives you both the item and a clean human-friendly counter starting at 1.
  • while loops: A while loop keeps repeating as long as a condition stays True. In this example, count -= 1 subtracts 1 from count on each pass so the loop eventually stops at 0. Always make sure a while loop has a clear way to end, or it will run forever!

Run the script:

python 04_lists_and_loops.py
Enter fullscreen mode Exit fullscreen mode

Terminal output for 04_lists_and_loops.py


7. Writing Reusable Functions (05_functions_expense_tracker.py)

As your scripts grow, you will notice yourself repeating the same calculations or formatting steps. Functions let you package a block of logic once, give it a clear name, and reuse it whenever you need it.

Create 05_functions_expense_tracker.py:

# 05_functions_expense_tracker.py
# Organizing reusable logic with functions

def calculate_total(expenses):
    return sum(expenses)

def summarize_week(label, expenses, weekly_limit):
    total = calculate_total(expenses)
    average = total / len(expenses)
    status = "Within budget" if total <= weekly_limit else "Over budget"

    print(f"=== {label} ===")
    print(f"Expenses recorded : {len(expenses)}")
    print(f"Total spent       : ${total:.2f}")
    print(f"Average expense   : ${average:.2f}")
    print(f"Weekly status     : {status} (Limit: ${weekly_limit:.2f})")

coffee_and_lunch = [4.50, 12.00, 3.75, 14.25, 8.50]
summarize_week("Weekday Coffee & Lunch", coffee_and_lunch, weekly_limit=50.00)
Enter fullscreen mode Exit fullscreen mode

How It Works

  • Defining a function (def): def calculate_total(expenses): creates a reusable helper that accepts a list of numbers (expenses) and sends back their sum using return.
  • Built-in helpers: Python includes handy built-in functions like sum() (adds all numbers in a list) and len() (counts how many items are in a list).
  • Combining everything: summarize_week() brings together variables, f-strings, arithmetic, a one-line conditional expression, a list, and another function call.

Run the final program:

python 05_functions_expense_tracker.py
Enter fullscreen mode Exit fullscreen mode

Terminal output for 05_functions_expense_tracker.py


8. Common Beginner Mistakes (and How to Fix Them)

Everyone hits errors when learning Python—even experienced developers see them daily. Here are three common ones and what they mean:

  • SyntaxError: You missed a closing quote, parenthesis, or colon (:) at the end of an if, for, or def line. Check the line number in the error message and the line right above it.
  • IndentationError: Your spaces inside an if block, loop, or function do not line up. Stick to four spaces per level.
  • NameError: You tried to use a variable or function name before defining it, or you made a small typo in the name (remember Python is case-sensitive, so Total and total are different).

Access the beginner guide: https://github.com/Manu-Data1/PYTHON_101

Happy coding!

Top comments (0)