Day 1 / 25 Variables, Types & Your First Programs 0/0 exercises Exercises ↓

AmouAI Hub/Courses/Programming Fundamentals/Day 1

Week 1 · Python Core Foundations · Day 1

Variables, Types & Your First Programs

A computer does exactly what you tell it, with no judgment and no common sense. Today you learn to give instructions that precise - and to store the things those instructions work on.

Study time
4 hours + exercises
Reading
Think Python, Ch. 1-2
Focus
Binding, data types, conversion

By the end of today you can

  1. Explain what a program is and how Python turns your text into behaviour
  2. Create variables and predict what a name refers to after any sequence of assignments
  3. Identify and use Python's core types: int, float, str, bool, None
  4. Convert between types deliberately, and recognise which conversions fail and why
  5. Format output cleanly with f-strings
  6. Explain why input() plus arithmetic is the most common beginner bug, and fix it

Today's videos

Watch each video, then work the matching sections below. Watching alone will not do it.

1A
From Problem to Program (120 min)
What a computer actually does · source code to output · installing Python and VS Code · your first program · statements and comments · variables as names bound to values · naming as communication.
1B
Data Types & the Type System (120 min)
int, float, str, bool, None · why 0.1 + 0.2 is not 0.3 · strings and escape sequences · f-strings · type conversion and its failure modes · input() always returns a string.

1What a program really is

Before syntax, one idea: the computer has no judgment. Precision is not pedantry - it is the whole job.

Imagine you write instructions for someone who follows them exactly, has read every dictionary ever printed, and has never once used common sense. You write "spread the peanut butter on the bread." They pick up the sealed jar and press it against the loaf. Technically correct. Completely wrong.

That is your computer. It is astonishingly fast and astonishingly literal. Every bug you will ever write is a gap between what you meant and what you actually said.

From your text to actual behaviour

You write source code - plain text in a .py file. The Python interpreter reads it line by line, translates each line into operations the machine understands, and performs them immediately. This is why you can run a Python file the moment you save it, with no extra step.

Park this for Day 16

Java works differently: you compile the whole program first, into bytecode, and only then run it. That single difference explains most of what will feel strange about Java in Week 4. You do not need it yet - just know the distinction exists.

Your first program

hello.py
# hello.py - the traditional first program
print("Hello, world!")
Hello, world!

print() is a function: a named piece of behaviour you can trigger. The parentheses mean "do it now," and what goes inside them is what you are handing over. A line like this is a statement - one complete instruction. Python runs statements top to bottom, one per line.

Comments

Anything after # on a line is ignored by Python entirely. Comments are for humans.

comments.py
# This whole line is a comment.
print("Visible")   # This part is a comment too

# Good comment - explains WHY:
# Prices are stored in cents to avoid floating-point rounding errors.

# Useless comment - just restates the code:
# print the total
print(1250)
Rule of the day

If you have to think about whether the computer will guess correctly, it will not. Say exactly what you mean.

2Variables: names bound to values

Almost every beginner is taught the box metaphor. It is wrong, and it breaks the moment you meet lists. Learn the right model now.

A variable is a name that refers to a value. When you write:

example.py
score = 42

you are not putting 42 inside a container called score. You are creating the value 42 and attaching the label score to it. The name points at the value.

The difference matters immediately:

binding.py
a = 5
b = a      # b now points at the SAME value a points at
a = 10     # a is re-pointed at a new value; b is untouched

print(a)   # 10
print(b)   # 5
10 5

If a were a box and b = a poured its contents into another box, you would get the same answer here - so the metaphor survives this example. It will not survive Day 8, when b = a on a list means both names point at one list and changing either changes both. Get the model right now and Day 8 costs you nothing.

Binding animatorinteractive

Write assignments, one per line, then step through them. Watch which name points at which value after every single statement.

bindings.py
line 0 of 5
Names → values
nothing defined yet
What just happened
Press Step.

Naming rules and naming taste

RuleAllowedNot allowed
Letters, digits, underscores onlytotal_2total-2, total 2
Cannot start with a digitx11x
Case sensitiveScore and score are different names
Cannot be a keywordclass_nameclass, if, for
Convention: snake_casedays_elapseddaysElapsed (that is Java's style - Week 4)
Names are documentation

Compare d = 30 * 24 * 60 with minutes_in_a_month = 30 * 24 * 60. Identical to Python. Wildly different to the person reading it in six weeks - who is usually you.

3The five types you need today

Python tracks what kind of thing every value is, and that determines what you are allowed to do with it.

TypeWhat it holdsExamples
intWhole numbers, positive or negative, unlimited size0, 42, -7, 10**100
floatNumbers with a decimal point3.14, -0.5, 2.0
strText, in quotes"hello", 'A', ""
boolTruth values - exactly two of themTrue, False
NoneTypeThe deliberate absence of a valueNone
types.py
print(type(42))        # <class 'int'>
print(type(3.14))      # <class 'float'>
print(type("hello"))   # <class 'str'>
print(type(True))      # <class 'bool'>
print(type(None))      # <class 'NoneType'>

# Note: 2 and 2.0 are DIFFERENT types
print(type(2), type(2.0))
<class 'int'> <class 'float'> <class 'str'> <class 'bool'> <class 'NoneType'> <class 'int'> <class 'float'>

Type decides what operations make sense:

type_ops.py
print("ha" * 3)     # 'hahaha'  - repetition
print(3 * 3)        # 9         - multiplication
print("ha" + "ha")  # 'haha'    - joining
print("ha" - "ha")  # TypeError - subtraction is meaningless for text
hahaha 9 haha TypeError: unsupported operand type(s) for -: 'str' and 'str'
Type inspectorlive python

Type any Python expression. See what it evaluates to, what type it is, and whether Python considers it true or false. Try 0, "", "0", 2 == 2.0, None.

python not loaded
Press Inspect.

Why 0.1 + 0.2 is not 0.3

floats.py
print(0.1 + 0.2)          # 0.30000000000000004
print(0.1 + 0.2 == 0.3)   # False
0.30000000000000004 False

This is not a Python bug. Computers store floats in binary, and 0.1 in binary is an infinitely repeating fraction - exactly like 1/3 is 0.333... in decimal. The stored value is very slightly off, and the errors accumulate. Every mainstream language does this.

Never compare floats with ==

Use round(x, 2) == round(y, 2), or check that the difference is tiny: abs(x - y) < 0.0001. For money, work in whole cents as int and divide only when you display.

4Strings and f-strings

Most real data arrives as text. And unformatted output is the fastest way to make a working program look broken.

Strings can use single or double quotes - pick one and be consistent. Triple quotes span multiple lines.

strings.py
single = 'Python'
double = "Python"
multi = """Line one
Line two"""

# Use the OTHER quote when your text contains one:
quote = "It's fine."
other = 'She said "hello".'

# Escape sequences
print("Tab\there")
print("Line one\nLine two")
print("A backslash: \\")
Tab here Line one Line two A backslash: \

f-strings: the only formatting you need

Put f before the opening quote, then write any expression inside { }.

fstrings.py
name = "Amin"
items = 3
price = 12.5

# The painful old way:
print("Hi " + name + ", you have " + str(items) + " items.")

# The f-string way:
print(f"Hi {name}, you have {items} items.")

# Expressions work inside the braces:
print(f"Total: {items * price}")

# Format specifiers control the display:
print(f"Total: ${items * price:.2f}")     # 2 decimal places
print(f"|{name:>10}|")                    # right-aligned in 10 columns
print(f"|{name:<10}|")                    # left-aligned
print(f"|{name:^10}|")                    # centred
print(f"{1234567:,}")                     # thousands separators
Hi Amin, you have 3 items. Hi Amin, you have 3 items. Total: 37.5 Total: $37.50 | Amin| |Amin | | Amin | 1,234,567
SpecifierEffectExample result
{x:.2f}Fixed to 2 decimal places3.14
{x:>8}Right-align in 8 columns    3.14
{x:<8}Left-align in 8 columns3.14    
{x:^8}Centre in 8 columns  3.14  
{x:,}Thousands separators1,234,567
{x:08.2f}Zero-padded, width 8, 2 decimals00003.14

5Type conversion - and where it bites

Python will not silently guess what you meant. That is a feature. It does mean you have to ask explicitly.

convert.py
int("42")       # 42        - text that looks like a whole number
int(3.9)        # 3         - TRUNCATES, does not round
int("3.9")      # ValueError - not a whole number in text form
float("3.14")   # 3.14
str(99)         # '99'
bool(0)         # False
bool("")        # False
bool("False")   # True  <- it is a non-empty string!
int() truncates, it does not round

int(3.9) is 3, and int(-3.9) is -3. If you want rounding, say round(3.9), which gives 4.

Conversion lablive python

Pick a value and a conversion. See the result, or the exact error message Python produces. Try converting "3.9" with int.

( )
Press Convert.

Quick tries: int('42') · int('3.9') · int(3.9) · bool('False') · float('abc')

The bug that catches everyone

input() reads what the user typed and hands it back as a string. Always. Even if they typed digits.

the_bug.py
a = input("First number: ")   # user types 5
b = input("Second number: ")  # user types 3
print(a + b)                  # '53'  <- string joining, not addition!
First number: 5 Second number: 3 53

The fix is to convert on the way in:

the_fix.py
a = int(input("First number: "))
b = int(input("Second number: "))
print(a + b)                  # 8
First number: 5 Second number: 3 8
Say it out loud three times

input() always returns a string. If you are going to do maths with it, wrap it in int() or float() immediately.

6Putting it together

A complete small program, built the way you should build every program: decide the parts first, then type.

Before writing a line, name the three parts: what comes in, what processing happens, what goes out.

InProcessOut
A temperature in Celsius, typed by the userConvert with F = C × 9/5 + 32A formatted sentence with both values
unit_converter.py
# unit_converter.py - Celsius to Fahrenheit

FREEZING_C = 0          # named constant, not a magic number

celsius_text = input("Temperature in Celsius: ")
celsius = float(celsius_text)          # convert immediately

fahrenheit = celsius * 9 / 5 + 32

print(f"{celsius:.1f} C is {fahrenheit:.1f} F")
if_below = celsius < FREEZING_C
print(f"Below freezing: {if_below}")
Temperature in Celsius: 21.5 21.5 C is 70.7 F Below freezing: False

Notice four habits worth stealing:

  • Convert at the boundary. The moment text enters your program, turn it into the type you actually need.
  • Name your constants. FREEZING_C beats a bare 0 six months from now.
  • Format your output. :.1f is the difference between 70.7 and 70.70000000000001.
  • One idea per line. You can cram it all into one statement. Do not.
Now go use the playground

Scroll to the Python playground below and retype this program from memory - do not copy it. Getting it wrong and fixing it is the part that sticks.

>_Python playground

A real Python interpreter running inside your browser. Nothing is installed, nothing is uploaded, nothing can break.

scratch.pypython not loaded
Values for input(), comma separated →
Output appears here. The first run takes a few seconds while Python loads.

Exercise set

Checked automatically the moment you submit. Work top to bottom — each one assumes the last. Your answers are saved in this browser.

All Warm-up Core Challenge Reset day

Day 2 — Operators, Expressions & Strings

Arithmetic, the modulo workhorse, boolean logic, and everything strings can do.

Continue →