— Thinking Like a Programmer Python from First Principles
No account is required. Learn the material, try the examples, and mark it complete locally when you are ready to move on.
Phase 1 - Thinking Like a Programmer
Python from First Principles
Phase 0 taught you how to work with a computer as a developer:
how files and folders work
how to use the terminal
how to run programs
how to use Git and GitHub
how to save meaningful checkpoints of your work
Now we are going to learn how to think like a programmer.
This phase is not about memorizing Python syntax.
It is about learning how to take a problem that exists in the real world and turn it into a sequence of precise instructions that a computer can execute.
The language we will use is Python.
Python is a good language for this because its syntax is relatively readable, but the underlying ideas you learn here apply far beyond Python.
By the end of Phase 1, you should be able to look at a problem and think:
text
What information do I have?
↓
What information do I need?
↓
What transformations need to happen?
↓
What decisions need to be made?
↓
What should repeat?
↓
How should I organize the solution?
↓
How can I test whether it works?
That way of thinking is more important than any individual Python command.
1. What Is Programming?
Programming is the process of giving a computer a precise set of instructions for solving a problem.
Humans are very good at interpreting vague instructions.
Computers are not.
If you tell a person:
"Make me some tea."
They can fill in many missing details.
They might assume:
Find a cup.
Put tea in it.
Boil water.
Pour the water into the cup.
Wait.
Add milk if appropriate.
A computer cannot safely make those assumptions.
A computer needs explicit instructions.
Programming is therefore partly the art of turning:
text
Human intention
into:
text
Precise instructions
2. Programming Is Problem Decomposition
Suppose you want to build a program that calculates the total price of an order.
The human-level problem is:
"Calculate the order total."
But the computer needs smaller steps.
We might decompose it into:
text
Get item prices
↓
Get quantities
↓
Multiply each price by its quantity
↓
Add the results
↓
Apply tax
↓
Display total
This process is called decomposition.
You take one large problem and break it into smaller problems.
This is one of the most important programming skills you can develop.
3. Algorithms
An algorithm is a sequence of steps for solving a problem.
For example, suppose we want to determine whether a number is even.
We can describe the algorithm:
text
Take a number
↓
Divide it by 2
↓
Look at the remainder
↓
If remainder = 0
→ even
Otherwise
→ odd
In Python:
python
number = 17
if number % 2 == 0:
print("Even")
else:
print("Odd")
The Python code is simply one representation of the underlying algorithm.
Once one condition is true, the remaining branches are skipped.
27. Indentation
Python uses indentation to define blocks of code.
For example:
python
if age >= 18:
print("Adult")
The indented line belongs to the if.
This is not valid:
python
if age >= 18:
print("Adult")
Indentation is part of Python's syntax.
Use four spaces for indentation.
Most editors will handle this automatically.
28. Nested Conditions
You can place conditions inside other conditions.
For example:
python
age = 25
has_ticket = True
if age >= 18:
if has_ticket:
print("Enter")
However, deeply nested code can become difficult to understand.
As you become more experienced, you will learn ways to simplify complicated logic.
29. Input
Programs become much more interesting when they interact with users.
Python's input() function lets you receive text from the user.
python
name = input("What is your name? ")
print("Hello", name)
If the user enters:
text
Alice
the program prints:
text
Hello Alice
30. Important: input() Returns a String
This surprises many beginners.
Suppose you write:
python
age = input("How old are you? ")
Even if the user types:
text
25
Python gives you:
text
"25"
not:
python
25
The result is a string.
This matters when doing arithmetic.
31. Converting Types
Suppose we want an integer.
We can use:
python
age = int(input("How old are you? "))
Now age is an integer.
Similarly:
python
price = float(input("Price: "))
converts the input to a floating-point number.
32. Type Conversion
Common conversion functions include:
python
int()
float()
str()
bool()
Examples:
python
int("42")
python
float("3.14")
python
str(42)
Be careful.
Not every string can become a number.
This works:
python
int("42")
This does not:
python
int("hello")
It raises an error.
33. F-Strings
Python provides a convenient way to construct strings.
Instead of:
python
name = "Alice"
age = 25
print("My name is " + name + " and I am " + str(age))
you can write:
python
print(f"My name is {name} and I am {age}")
This is called an f-string.
It is one of the most useful ways to format text in Python.
34. Your First Real Program
Let's combine what we have learned.
python
name = input("What is your name? ")
age = int(input("How old are you? "))
if age >= 18:
status = "an adult"
else:
status = "not an adult"
print(f"Hello {name}. You are {status}.")
This program:
asks for a name
asks for an age
converts the age to an integer
makes a decision
creates a message
prints the result
This is programming.
35. Lists
So far, variables have stored individual values.
But what if we have many values?
For example:
text
Alice
Bob
Charlie
David
A list lets us store multiple values.
python
names = ["Alice", "Bob", "Charlie", "David"]
36. Accessing List Elements
Python uses zero-based indexing.
That means the first element is index 0.
python
names = ["Alice", "Bob", "Charlie"]
Then:
python
names[0]
is:
text
Alice
python
names[1]
is:
text
Bob
python
names[2]
is:
text
Charlie
37. Why Does Python Start at Zero?
This can feel strange.
Think of an index as an offset from the beginning.
The first element has an offset of zero:
text
Index: 0 1 2
Alice Bob Charlie
You will encounter zero-based indexing frequently in programming.
As programs grow, functions help create boundaries between different responsibilities.
66. Scope
Variables have a scope.
Consider:
python
def greet():
message = "Hello"
print(message)
The variable message exists inside the function.
Trying to use it outside:
python
print(message)
will fail because message is local to the function.
Understanding scope becomes increasingly important as your programs grow.
67. Modules
A Python file can contain reusable code.
Suppose you have:
text
calculator.py
containing:
python
def add(a, b):
return a + b
Another file can import it:
python
from calculator import add
print(add(10, 5))
This is the beginning of organizing programs into multiple modules.
68. Why Modules Matter
Imagine a project containing:
text
app.py
database.py
users.py
payments.py
email.py
Instead of putting every function into one enormous file, each module can have a focused responsibility.
This becomes extremely important in larger software projects.
69. Exceptions
Programs sometimes encounter unexpected situations.
For example:
python
number = int(input("Enter a number: "))
What if the user enters:
text
hello
Python cannot convert "hello" into an integer.
It raises an exception.
70. try and except
We can handle certain errors:
python
try:
number = int(input("Enter a number: "))
print(number)
except ValueError:
print("Please enter a valid number.")
Now the program can respond gracefully.
This is called exception handling.
71. Errors Are Information
Do not develop the mindset:
"Errors are bad."
Instead think:
"Errors tell me something about what happened."
Python errors often tell you:
what went wrong
where it happened
what type of error occurred
Learning to read error messages is a core programming skill.
72. Reading Tracebacks
Suppose Python displays:
text
Traceback (most recent call last):
File "app.py", line 5, in <module>
result = 10 / 0
ZeroDivisionError: division by zero
Do not panic.
Read it from the bottom.
The final line says:
text
ZeroDivisionError: division by zero
The traceback also tells you:
text
app.py
line 5
Start there.
73. Debugging
Debugging means finding and fixing problems in a program.
A useful debugging process is:
text
Observe the problem
↓
Reproduce the problem
↓
Identify where it occurs
↓
Form a hypothesis
↓
Test the hypothesis
↓
Make a change
↓
Run the program again
Do not randomly change code.
Try to understand the problem first.
74. The Scientific Method for Programming
Debugging is surprisingly similar to science.
You observe:
The program gives the wrong total.
You hypothesize:
Maybe tax is being applied twice.
You test:
python
print(subtotal)
print(tax)
print(total)
You observe the output.
Then you update your hypothesis.
This mindset is much more powerful than guessing.
75. Comments
Python allows comments using #.
python
# Calculate the total price
total = price * quantity
Comments can explain why something exists.
Avoid comments that merely repeat the code.
Weak:
python
# Add 1 to count
count += 1
Better:
python
# Move to the next student
count += 1
The best comments often explain reasoning that is not obvious from the code itself.
76. Truthiness
Python allows many values to be interpreted as true or false.
For example:
python
if name:
print("Name provided")
An empty string:
python
""
is considered false.
A non-empty string:
python
"Alice"
is considered true.
Similar behavior exists for collections.
For example:
python
items = []
if items:
print("There are items")
else:
print("The list is empty")
77. None
Python has a special value:
python
None
It represents the absence of a value.
For example:
python
result = None
You might use this when a value does not exist yet.
Check for it using:
python
if result is None:
print("No result")
Prefer is None rather than:
python
result == None
78. String Operations
Strings have many useful methods.
For example:
python
name = "alice"
Uppercase:
python
name.upper()
Result:
text
ALICE
Lowercase:
python
name.lower()
Capitalize:
python
name.capitalize()
Strip whitespace:
python
name.strip()
79. Splitting Strings
Suppose:
python
sentence = "Python is fun"
You can split it:
python
words = sentence.split()
Now:
python
words
contains:
text
["Python", "is", "fun"]
This is useful when processing text.
80. Joining Strings
You can join strings:
python
words = ["Python", "is", "fun"]
sentence = " ".join(words)
Result:
text
Python is fun
This becomes useful when working with text data.
81. File Handling
Programs often need to work with files.
Python provides open().
For example:
python
with open("notes.txt", "r") as file:
content = file.read()
print(content)
The with statement ensures the file is handled safely.
82. Writing Files
You can write to a file:
python
with open("notes.txt", "w") as file:
file.write("Hello from Python!")
Be careful with "w".
It can overwrite an existing file.
83. Appending to Files
If you want to add content rather than replace the existing content:
python
with open("notes.txt", "a") as file:
file.write("\nAnother line.")
The "a" means append.
84. JSON
Many applications exchange information using JSON.
At the end of Phase 1, do not measure yourself by asking:
"Can I remember every Python method?"
Instead ask:
"Can I solve a new problem?"
If someone gives you a problem you have never seen before, you should be able to:
text
Understand the problem
↓
Break it into smaller pieces
↓
Identify inputs and outputs
↓
Choose appropriate data structures
↓
Write an algorithm
↓
Implement it in Python
↓
Test it
↓
Debug it
↓
Improve it
That is the real goal.
105. The Programmer's Mental Model
As you progress through the curriculum, try to develop this habit:
When you see a problem, don't immediately think:
"What Python syntax do I need?"
Instead think:
"What is the underlying problem?"
Then:
text
Problem
↓
Inputs
↓
Data
↓
Operations
↓
Decisions
↓
Repetition
↓
Output
Only then translate those ideas into Python.
106. Final Challenge
Before moving to the next phase, build something without following a tutorial step-by-step.
Choose a problem that matters to you.
Describe it in plain English first.
For example:
text
I want to build a program that helps me track
how much time I spend studying.
Then break it down:
text
Record subject
Record duration
Store records
Calculate total
Calculate totals by subject
Display results
Then decide:
text
What data structures do I need?
What functions do I need?
What decisions do I need?
What loops do I need?
What errors could happen?
Then build it.
Do not worry if the first version is ugly.
Build version 1.
Then improve it.
Commit each meaningful milestone with Git.
107. The Core Lesson
Programming is not primarily about typing code.
Programming is about turning problems into precise, executable ideas.
Python is the language we are using to practice that skill.
The most important progression in Phase 1 is:
text
"I don't know how to solve this."
↓
"I can break the problem into pieces."
↓
"I can describe the algorithm."
↓
"I can implement the algorithm."
↓
"I can test the implementation."
↓
"I can debug it when it fails."
↓
"I can improve the solution."
Once you can do that, you are no longer simply learning Python syntax.
You are learning to program.
Finished this lesson?
Completion is saved in this browser without creating an account.