LEARN TO PROGRAM / ORIGINAL WRITTEN COURSE
Free Python: complete beginner course
Go from your first script to functions, files, classes and automated tests. Twelve lessons, exercises, solutions and a small capstone—free, with no account or payment.
By Tech Life Hybrid · Content and source review dated
What this course covers—and what it does not
This is a complete beginner sequence, not every advanced Python topic, a video course, a professional qualification or a promise of employment. Work in order, run each example and try its exercise before opening the solution. You need a computer where you can install or use Python 3.
The example and solution scripts were checked locally with Python 3.14.8. This does not mean that version is the newest release. Use the supported release appropriate for your computer and read its official installation instructions. No code runs on your device merely by opening this page.
Python’s official downloads and installation resources · Download the original practice files (ZIP)
Create a new practice folder, extract the files there and read README.txt. Do not paste these examples into a folder containing important work. The file exercise uses a temporary directory and synthetic data; it is not a backup or hardware-diagnosis program.
LESSON 1
Run your first program
Goal: Create a small script, run it and compare exact output.
A program is a text file of instructions. Start in a new practice folder, not a folder containing important work. Save the example as lesson_01.py, then run it with your installed Python 3 interpreter. If your system uses a different launcher name, follow its official installation instructions rather than changing security settings.
Read an error from the last line upward and check the named file and line. Quotes mark text; parentheses contain the arguments supplied to print. The # comment is for the reader, not an instruction that prints.
Example
print("Tech Life Hybrid Python")
print(2 + 3)
# This comment does not print.
Expected result
Tech Life Hybrid Python
5
Try it yourself
Add a third printed line saying Practice, then change the arithmetic to 6 times 7.
Show the solution and expected result
print("Tech Life Hybrid Python")
print(6 * 7)
print("Practice")
Tech Life Hybrid Python
42
Practice
LESSON 2
Variables, numbers and units
Goal: Name values and make a calculation you can explain.
A variable name refers to a value. Choose names that include the meaning or unit instead of calling everything x. An integer and a floating-point number have different roles; displaying two decimal places is formatting, not evidence that a measurement is accurate to that precision.
The example uses invented values. Work out the expected result before running it. Change one value and predict which output will change. Avoid using these toy calculations as an electrical or PC-sizing recommendation.
Example
modules = 2
gb_per_module = 16
total_gb = modules * gb_per_module
print(f"Capacity example: {total_gb} GB")
print(f"Half: {total_gb / 2:.1f} GB")
Expected result
Capacity example: 32 GB
Half: 16.0 GB
Try it yourself
Use three items of 8 GB each. Print the total and half with the same formatting.
Show the solution and expected result
modules = 3
gb_per_module = 8
total_gb = modules * gb_per_module
print(f"Capacity example: {total_gb} GB")
print(f"Half: {total_gb / 2:.1f} GB")
Capacity example: 24 GB
Half: 12.0 GB
LESSON 3
Text, cleanup and user input
Goal: Separate the text someone types from the value your program expects.
A string is text. Leading spaces and letter case can make two visually similar labels different. strip removes surrounding whitespace; upper creates uppercase text. These transformations return a new string, so keep the result you need.
input reads a line locally and returns text. It does not turn a number-looking string into an integer. Never ask someone to put a password or private identifier into a practice program. This lesson sends nothing over a network.
Example
raw_label = " demo board "
label = raw_label.strip().upper()
print(label)
print(len(label))
Expected result
DEMO BOARD
10
Try it yourself
Replace the fixed text with input. Enter demo, then print the cleaned uppercase label.
Show the solution and expected result
raw_label = input("Project label: ")
print(raw_label.strip().upper())
Project label: DEMO
LESSON 4
Decisions with if, elif and else
Goal: Write a branch that does not confuse missing evidence with approval.
A condition chooses which indented block runs. == compares values; = assigns a name. Use elif for a distinct alternative and else for the remaining cases. Consistent indentation is part of Python syntax, not decoration.
Here unknown is deliberately different from documented. A computer can apply your rule precisely while the rule itself remains a poor real-world model. Treat these labels as practice data, not a hardware diagnosis.
Example
status = "unknown"
if status == "conflict":
print("Resolve the conflict")
elif status == "documented":
print("Record the source")
else:
print("Keep researching")
Expected result
Keep researching
Try it yourself
Set status to conflict. Keep the three branches and predict the output.
Show the solution and expected result
status = "conflict"
if status == "conflict":
print("Resolve the conflict")
elif status == "documented":
print("Record the source")
else:
print("Keep researching")
Resolve the conflict
LESSON 5
Repeat work with loops
Goal: Visit each item once and keep a running total.
A for loop visits items in a sequence. range produces a sequence of integer positions; its stop value is excluded. Start with a short finite list so you can trace every iteration by hand.
Create a new result rather than removing items from the same list while you loop over it. When you later use while, define the condition that ends it before writing the loop. Stop a runaway practice program through your normal interpreter controls.
Example
parts = ["CPU", "RAM", "SSD"]
for number, part in enumerate(parts, start=1):
print(f"{number}. {part}")
print(f"Items: {len(parts)}")
Expected result
1. CPU
2. RAM
3. SSD
Items: 3
Try it yourself
Loop through the numbers 1 to 4, add them and print only the total.
Show the solution and expected result
total = 0
for number in range(1, 5):
total += number
print(total)
10
LESSON 6
Lists, dictionaries, tuples and sets
Goal: Pick a collection that matches the question.
Use a list for an ordered sequence that can change, a dictionary for key/value records, a tuple for a fixed sequence, and a set when membership or uniqueness matters more than order. The example sorts a set before printing so the output is repeatable.
Dictionary keys must be unique. Appending a record to a list does not validate its contents. Keep validation as a separate step, and avoid relying on the printed order of a set.
Example
record = {"part": "SSD", "status": "unknown"}
items = [record]
items.append({"part": "RAM", "status": "documented"})
labels = {item["part"] for item in items}
point = (4, 7)
print(", ".join(sorted(labels)))
print(point[0])
Expected result
RAM, SSD
4
Try it yourself
Create a dictionary with two part statuses. Print the status for CPU, then print the number of entries.
Show the solution and expected result
statuses = {"CPU": "unknown", "PSU": "conflict"}
print(statuses["CPU"])
print(len(statuses))
unknown
2
LESSON 7
Functions, parameters and return values
Goal: Package a calculation without hiding its assumptions.
A function names a reusable operation. Parameters receive input values; return sends a result back to the caller. A printed result and a returned value are not the same thing. Prefer a small function that can be tested without asking for input inside it.
Local names belong to the function call. Do not use an unexplained global variable when a parameter expresses the dependency. The example is arithmetic only; it does not measure frame rate or latency.
Example
def frame_interval_ms(fps):
if fps <= 0:
raise ValueError("fps must be positive")
return 1000 / fps
print(f"{frame_interval_ms(50):.1f} ms")
Expected result
20.0 ms
Try it yourself
Write a function that returns the total of quantity times unit_size. Call it with 3 and 8.
Show the solution and expected result
def total_size(quantity, unit_size):
return quantity * unit_size
print(total_size(3, 8))
24
LESSON 8
Imports, modules and standard-library tools
Goal: Reuse a documented tool without adding a package you do not need.
import makes another module available by name. Python includes a standard library; these lessons require no downloaded third-party packages. Give your own files descriptive names so a file named statistics.py does not accidentally hide the standard-library module.
As a project grows, move related functions into a separate .py file and import them. Code at a module's top level runs when it is first imported, so keep demonstrations behind an if __name__ == '__main__' guard when you want the module to be reusable.
Example
from statistics import mean
samples_ms = [12, 14, 16]
print(f"Mean: {mean(samples_ms):.1f} ms")
Expected result
Mean: 14.0 ms
Try it yourself
Use the math module to print the square root of 81 as an integer.
Show the solution and expected result
import math
print(int(math.sqrt(81)))
9
LESSON 9
Errors, validation and debugging
Goal: Handle an expected input error without concealing unrelated failures.
A syntax error prevents code from being parsed; an exception happens while code runs. Catch the specific exception you expect around the smallest relevant operation. An empty except block can hide a real defect and leave the program reporting a false success.
Use a tiny failing input to reproduce a problem. Record the expected result, actual result and a minimal example without secrets. In this example None means no valid count; it is not the same as zero.
Example
def parse_count(text):
try:
count = int(text)
except ValueError:
return None
return count if count >= 0 else None
print(parse_count("4"))
print(parse_count("four"))
Expected result
4
None
Try it yourself
Keep the same validation and show what happens for -1 and 0.
Show the solution and expected result
def parse_count(text):
try:
count = int(text)
except ValueError:
return None
return count if count >= 0 else None
print(parse_count("-1"))
print(parse_count("0"))
None
0
LESSON 10
Files, paths and JSON
Goal: Save structured practice data without overwriting existing work.
A path identifies a location; JSON is one format for storing simple structured values. Specify a text encoding. The example creates a temporary practice folder and reads back its own synthetic file. It does not search, reorganize or modify your documents.
The temporary folder is removed when the with block ends. For a permanent project file, choose a new project folder and use an exclusive-create operation when you must not overwrite a file. Do not point a beginner exercise at backups, system folders or real customer records.
Example
import json
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory(prefix="tlh-python-") as folder:
path = Path(folder) / "practice.json"
path.write_text(json.dumps({"status": "unknown"}), encoding="utf-8")
restored = json.loads(path.read_text(encoding="utf-8"))
print(restored["status"])
Expected result
unknown
Try it yourself
Store a list of two synthetic part names in the same temporary-file pattern, read it back and print its length.
Show the solution and expected result
import json
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory(prefix="tlh-python-") as folder:
path = Path(folder) / "practice.json"
path.write_text(json.dumps(["CPU", "RAM"]), encoding="utf-8")
parts = json.loads(path.read_text(encoding="utf-8"))
print(len(parts))
2
LESSON 11
Classes and separate instances
Goal: Keep related data and behavior together when that makes the program clearer.
A class defines a kind of object. __init__ prepares an instance; self refers to that instance inside its methods. Attributes on one instance should not silently become shared progress for every learner or every record.
You do not need a class for every calculation. Start with functions and dictionaries, then use a class when the relationship between data and behavior is useful. This simple example records a label and a self-reported state; it does not verify a component.
Example
class ResearchItem:
def __init__(self, label):
self.label = label
self.status = "unknown"
def describe(self):
return f"{self.label}: {self.status}"
item = ResearchItem("CPU")
print(item.describe())
Expected result
CPU: unknown
Try it yourself
Create two independent items. Change only the first one's status, then print the second item's description.
Show the solution and expected result
class ResearchItem:
def __init__(self, label):
self.label = label
self.status = "unknown"
def describe(self):
return f"{self.label}: {self.status}"
first = ResearchItem("CPU")
second = ResearchItem("RAM")
first.status = "documented"
print(second.describe())
RAM: unknown
LESSON 12
Automated tests and a useful next step
Goal: Prove a small behavior with normal, boundary and invalid inputs.
A test states an expected result and fails when the program disagrees. The standard-library unittest runner collects methods beginning with test. A passing arithmetic test does not prove that a whole application or hardware system works.
Test the boundary that could change a decision, not only the happy path. Keep test data synthetic and repeatable. After completing this lesson, build the capstone below, run its tests and explain one limitation in your own words.
Example
import unittest
def is_nonnegative(value):
return value >= 0
class CountTests(unittest.TestCase):
def test_positive(self):
self.assertTrue(is_nonnegative(3))
def test_zero(self):
self.assertTrue(is_nonnegative(0))
if __name__ == "__main__":
unittest.main()
Expected result
The runner reports 2 tests and OK. Its timing varies.Try it yourself
Add a third test confirming that -1 is not nonnegative.
Show the solution and expected result
import unittest
def is_nonnegative(value):
return value >= 0
class CountTests(unittest.TestCase):
def test_positive(self):
self.assertTrue(is_nonnegative(3))
def test_zero(self):
self.assertTrue(is_nonnegative(0))
def test_negative(self):
self.assertFalse(is_nonnegative(-1))
if __name__ == "__main__":
unittest.main()
Ran 3 testsCapstone: summarize research, not hardware compatibility
Put the following two files in the same practice folder. The program counts documented, unknown and conflicting notes. It does not inspect your computer or certify a build. Missing evidence stays unknown; a documented checklist still means the actual hardware is untested.
research_plan.py
VALID_STATES = {"unknown", "documented", "conflict"}
def summarize(records):
counts = dict.fromkeys(sorted(VALID_STATES), 0)
for record in records:
state = record.get("status", "unknown")
if state not in VALID_STATES:
raise ValueError("Unrecognized research status")
counts[state] += 1
if not records:
message = "No research records supplied"
elif counts["conflict"]:
message = "Resolve recorded conflicts"
elif counts["unknown"]:
message = "Research remains incomplete"
else:
message = "Checklist only; actual hardware remains untested"
return counts, message
if __name__ == "__main__":
sample = [{"part": "CPU", "status": "unknown"},
{"part": "PSU", "status": "conflict"}]
counts, message = summarize(sample)
print(counts)
print(message)
test_research_plan.py
import unittest
from research_plan import summarize
class ResearchPlanTests(unittest.TestCase):
def test_empty(self):
self.assertEqual(summarize([])[1], "No research records supplied")
def test_missing_status_is_unknown(self):
self.assertEqual(summarize([{"part": "CPU"}])[0]["unknown"], 1)
def test_conflict_takes_precedence(self):
self.assertEqual(summarize([{"status": "unknown"}, {"status": "conflict"}])[1], "Resolve recorded conflicts")
def test_documented_is_not_a_certificate(self):
self.assertIn("untested", summarize([{"status": "documented"}])[1])
def test_invalid_status_is_rejected(self):
with self.assertRaises(ValueError):
summarize([{"status": "guaranteed"}])
if __name__ == "__main__":
unittest.main()
Run python test_research_plan.py with your installed Python 3 launcher. The expected result is five tests and OK; the displayed duration varies. Try adding your own synthetic cases, then explain why changing every status to documented still does not prove a PC works.