Branchwell

Become a Pro / website · becomeapro.ai / content / lessons / knowledge-work / coding / your-first-small-program.mdx

1---
2title: "Writing your first small program in Python"
3description: "Install Python and VS Code, write a small tip and split calculator, learn variables, input, math, decisions and functions, then add a test."
4updated: 2026-12-03
5minutes: 12
6level: Beginner
7order: 2
8sources:
9 - https://docs.python.org/3/tutorial/
10 - https://code.visualstudio.com/docs/python/python-tutorial
11 - https://docs.pytest.org/en/stable/getting-started.html
12 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide
13 - https://docs.python.org/3/using/windows.html
14 - https://docs.python.org/3/library/venv.html
15 - https://git-scm.com/book/en/v2/Getting-Started-First-Time-Git-Setup
16 - https://git-scm.com/downloads
17 - https://nodejs.org/en/download
18 - https://vitest.dev/guide/
19---
20
21The fastest way to learn coding is to build something small that works. In this lesson you will write a tip and bill-splitting calculator in **Python**. Python is a great first language: it reads almost like English, it is used everywhere from websites to data analysis to AI, and you can do useful things with very little code.
22
23You will learn the five ideas that show up in almost every program: variables, input and output, math, decisions and functions. Then you will add a test.
24
25## Set up (15 minutes, once)
26
27<Steps>
28 <Step title="Install Python">On Windows, install the Python install manager from python.org or the Microsoft Store, then let it add Python to your PATH when it asks (PATH is the list of places your computer looks for commands). On a Mac, use the python.org installer or Homebrew. Then open a terminal and type `python3 --version` (or `python --version` on Windows) to check it works.</Step>
29 <Step title="Install VS Code">Download it from code.visualstudio.com.</Step>
30 <Step title="Add the Python extension">In VS Code, open the Extensions panel, search for "Python" and install the one from Microsoft.</Step>
31 <Step title="Install Git">On Windows, install Git for Windows from git-scm.com. On a Mac, type `git --version` in Terminal and accept the offer to install the developer tools. Then tell Git who you are, once per computer: `git config --global user.name "Your Name"` and `git config --global user.email "you@example.com"`.</Step>
32 <Step title="Make a project folder">Create a folder called `tip-calculator` and open it in VS Code with File, then Open Folder.</Step>
33</Steps>
34
35## How a program flows
36
37<Diagram caption="Most small programs follow the same path: get input, do some work, make decisions, show the output.">
38 <svg viewBox="0 0 600 200" role="img" aria-label="Program flow: input goes to calculate, then decide, then output">
39 <rect x="20" y="60" width="120" height="70" rx="10" fill="none" stroke="currentColor" strokeWidth="2" />
40 <text x="80" y="92" fontSize="16" textAnchor="middle" fill="currentColor">Input</text>
41 <text x="80" y="112" fontSize="14" textAnchor="middle" fill="currentColor">bill, people</text>
42 <rect x="170" y="60" width="120" height="70" rx="10" className="soft" stroke="currentColor" strokeWidth="2" />
43 <text x="230" y="92" fontSize="16" textAnchor="middle" fill="currentColor">Calculate</text>
44 <text x="230" y="112" fontSize="14" textAnchor="middle" fill="currentColor">tip, total</text>
45 <rect x="320" y="60" width="120" height="70" rx="10" fill="none" stroke="currentColor" strokeWidth="2" />
46 <text x="380" y="92" fontSize="16" textAnchor="middle" fill="currentColor">Decide</text>
47 <text x="380" y="112" fontSize="14" textAnchor="middle" fill="currentColor">is input OK?</text>
48 <rect x="470" y="60" width="110" height="70" rx="10" fill="none" stroke="currentColor" strokeWidth="2" />
49 <text x="525" y="92" fontSize="16" textAnchor="middle" fill="currentColor">Output</text>
50 <text x="525" y="112" fontSize="14" textAnchor="middle" fill="currentColor">each pays</text>
51 <line x1="140" y1="95" x2="168" y2="95" stroke="currentColor" strokeWidth="2" />
52 <line x1="290" y1="95" x2="318" y2="95" stroke="currentColor" strokeWidth="2" />
53 <line x1="440" y1="95" x2="468" y2="95" stroke="currentColor" strokeWidth="2" />
54 <text x="300" y="175" fontSize="14" textAnchor="middle" fill="currentColor">Put the calculation in a function so you can test it</text>
55 </svg>
56</Diagram>
57
58## Step 1: Hello and variables
59
60Create a file called `tip.py` and type:
61
62```python
63bill = 84.50
64people = 3
65print("Bill:", bill)
66print("People:", people)
67```
68
69Click the Run button (the triangle at the top right) or type `python3 tip.py` in the VS Code terminal (`python tip.py` on Windows).
70
71A **variable** is a name that holds a value. `bill` holds 84.50 and `people` holds 3. `print` shows something on the screen.
72
73## Step 2: Do the math
74
75Add these lines:
76
77```python
78tip_rate = 0.20
79tip = bill * tip_rate
80total = bill + tip
81each = total / people
82print(f"Tip: {tip:.2f}")
83print(f"Total: {total:.2f}")
84print(f"Each person pays: {each:.2f}")
85```
86
87`*` multiplies and `/` divides. The `f` before the quotes makes an **f-string**, which lets you put variables inside text with curly braces. `:.2f` means "show two decimal places", which is right for money.
88
89## Step 3: Ask the user
90
91Hard-coded numbers are not very useful. Replace the first two lines with:
92
93```python
94bill = float(input("Bill amount: "))
95people = int(input("How many people? "))
96```
97
98`input` asks a question and waits for an answer. The answer always comes back as text, so `float` turns it into a decimal number and `int` turns it into a whole number. Run it and try a few amounts.
99
100## Step 4: Make a decision
101
102What if someone types 0 people? Dividing by zero crashes the program. Use `if` to check first:
103
104```python
105if people <= 0:
106 print("Please enter at least 1 person.")
107else:
108 each = total / people
109 print(f"Each person pays: {each:.2f}")
110```
111
112The indented lines belong to the `if` or the `else`. Python uses indentation (four spaces) to group code, so keep it neat. VS Code does this for you.
113
114## Step 5: Put it in a function
115
116A **function** is a named block of code you can reuse. It takes inputs (called parameters) and gives back a result with `return`. Rewrite your file like this:
117
118```python
119def split_bill(bill, people, tip_rate=0.20):
120 """Return what each person pays, including tip."""
121 if people <= 0:
122 raise ValueError("people must be at least 1")
123 total = bill * (1 + tip_rate)
124 return round(total / people, 2)
125
126if __name__ == "__main__":
127 bill = float(input("Bill amount: "))
128 people = int(input("How many people? "))
129 print(f"Each person pays: {split_bill(bill, people):.2f}")
130```
131
132The function does the math. The bottom part handles input and output. The line `if __name__ == "__main__":` means "only ask questions when this file is run directly", which lets other files, like tests, use the function without being asked for input.
133
134<Callout type="note">Computers store decimal numbers in a way that can cause tiny rounding errors. For learning, `round` is fine. Real money software uses Python's `decimal` module or stores amounts in whole cents.</Callout>
135
136## Step 6: Add a test
137
138Install **pytest**, a popular testing tool. In the terminal:
139
140```bash
141python3 -m venv .venv
142source .venv/bin/activate # on Windows: .venv\Scripts\activate
143pip install pytest
144```
145
146The first line makes a **virtual environment**, a private space for this project's tools so they do not clash with other projects. Then create `test_tip.py`:
147
148```python
149import pytest
150from tip import split_bill
151
152def test_three_people():
153 assert split_bill(90, 3) == 36.0
154
155def test_no_tip():
156 assert split_bill(50, 2, tip_rate=0) == 25.0
157
158def test_zero_people_is_an_error():
159 with pytest.raises(ValueError):
160 split_bill(50, 0)
161```
162
163Run `pytest` in the terminal. You should see three passing tests. Now change the math in `split_bill` on purpose to break it and run `pytest` again. The tests catch it. That is the whole point.
164
165## Step 7: Save it with Git
166
167In the terminal:
168
169```bash
170git init
171git add tip.py test_tip.py
172git commit -m "Tip calculator with tests"
173```
174
175Now you have a saved snapshot you can always return to.
176
177## Using an AI agent on this project
178
179Try asking Claude Code or Codex, inside this folder: "Add an option to round each person's share up to the nearest dollar, and add tests for it." Watch what it changes, read the diff, run `pytest` yourself, and only commit if you understand every line. Asking the agent to explain its code line by line is one of the best ways to learn.
180
181## Prefer JavaScript?
182
183The same ideas work in JavaScript, the language of web browsers. Install Node.js from nodejs.org and the same function looks like this:
184
185```javascript
186function splitBill(bill, people, tipRate = 0.2) {
187 if (people <= 0) throw new Error("people must be at least 1");
188 return Math.round((bill * (1 + tipRate) / people) * 100) / 100;
189}
190console.log(splitBill(90, 3)); // 36
191```
192
193Run it with `node tip.js`. Tests in JavaScript are often written with Vitest.
194
195## Common mistakes
196
197- Forgetting to convert `input` text to a number
198- Mixing tabs and spaces, or uneven indentation
199- Naming your file the same as a module you import, like `pytest.py`
200- Skipping tests because the program "seems to work"
201- Copying AI code you do not understand