Skip to content
FORGENO ADS GAMESUnlock all $8

Python Programming · Unit 1 of 8

Unit 1: Python foundations

How Python runs a program, print and comments, values, types and variables, arithmetic and its traps, reading input, converting types and formatting output with f-strings.

Opens the first lesson of this unit in Python Programming. Every lesson is open from the start.

Lesson 1: Your first Python program

Goal: Run a program, use print() and comments, and explain how Python runs a file from top to bottom.

Python is a programming language: a precise way to write instructions that a computer carries out. It is one of the most widely used languages in the world, behind websites and their back ends, data analysis, automation scripts, testing tools, science and AI. Its code reads almost like English, which makes it a good first language and a practical tool for a whole career.

A Python program, often called a script, is a plain text file of instructions, usually ending in .py. The Python interpreter reads the file and runs it one statement at a time, from the top line to the bottom. When it runs out of lines, the program ends. In this course the interpreter is real Python 3 running inside this page, so your code behaves exactly as it would on a computer at work.

# hello.py: a comment starts with #, and Python ignores it
print("Hello, world!")
print("Python runs these lines in order.")
print(2 + 3)

print() is a function: a named piece of code that does one job. You call a function by writing its name followed by parentheses; the value inside the parentheses is its argument. print writes its argument to the output and then moves to a new line. Text must be inside quotes, single or double as long as they match, and is called a string. 2 + 3 has no quotes, so Python works it out first and prints 5.

Worked example: reading a program before running it

  1. Line 1 starts with #, so the whole line is a comment: a note for people. Python skips it.
  2. Line 2 calls print with the string "Hello, world!". The output shows Hello, world!, without the quotes: quotes only mark where the text starts and ends.
  3. Line 3 prints the second sentence on a new line, because each print ends with a newline.
  4. Line 4 has no quotes, so Python calculates 2 + 3 and prints 5.

Output: three lines. Predicting the output before you press Run is the single most useful habit in programming: when the result surprises you, you have found a gap in your understanding.

Run it below. Then break it on purpose: delete the closing quote on line 2 and run again. Python stops with a SyntaxError before running anything at all, because it reads and checks the whole file first. The left panel explains the error in plain words; the right panel shows exactly what Python printed. Reading that raw message is a skill you will build all course, because it is what you will see at work.

Hands-on lab in the room: Python playground. Press Run. The first run downloads Python (about 13 MB), so it takes a few seconds; after that it is quick.

Program (script)
A text file of instructions, usually ending in .py, that Python runs from top to bottom.
Interpreter
The program that reads Python code and carries it out, one statement at a time.
Statement
One instruction, usually one line, such as a print() call or an assignment.
Function
A named piece of code that does a job, called by writing its name and parentheses, like print().
Argument
A value passed to a function inside its parentheses.
Comment
Text after # that Python ignores; notes for people reading the code.
String
A piece of text in quotes, such as "Hello"; its type is str.

Remember: Python runs a file top to bottom, one statement at a time. print() shows values; # starts a comment.

Lesson 2: Values, variables and types

Goal: Store values in variables, name them well and tell int, float, str, bool and None apart.

Every piece of data in Python is a value, and every value has a type that decides what you can do with it. You can multiply two numbers but not two names; you can make text upper case but not a number. These five types appear in almost every program:

The five everyday types
TypeExamplesUsed for
int42, -7, 0Whole numbers: counts, ages, quantities
float3.14, 2.5, -0.1Numbers with a decimal point: prices, measurements
str"Ana", "42", ""Text. "42" is text that happens to contain digits, not a number
boolTrue, FalseYes-or-no facts, such as "is it in stock?"
NoneNoneNo value yet, or nothing found

A variable is a name that refers to a value. You create one with an assignment: a name, one = sign, then a value. Read price = 4.5 as "price now refers to 4.5", not "price equals 4.5": Python works out the right-hand side first and then attaches the name to the result. You can reassign a name later, even to a value of a different type, because in Python types belong to values, not to names.

item = "Notebook"     # str
qty = 3               # int
price = 2.5           # float
in_stock = True       # bool
discount = None       # no discount yet

qty = qty + 2         # right side first: 3 + 2 is 5, then qty refers to 5
print(item, qty, price * qty)
print(type(qty), type(price), type(item))

Worked example: following a variable as it changes

  1. qty = 3 attaches the name qty to the int 3.
  2. qty = qty + 2: Python evaluates the right side with the current value, 3 + 2, gets 5, then attaches qty to 5. The old value is simply no longer used.
  3. price * qty is 2.5 * 5, which is 12.5: an int times a float gives a float.
  4. type() reports what a value is: <class 'int'>, <class 'float'> and <class 'str'>.

Output: Notebook 5 12.5, then the three types.

Names may contain letters, digits and underscores, cannot start with a digit, cannot contain spaces and are case-sensitive: Total and total are two different variables. Python's style guide, PEP 8, uses lower-case words joined by underscores, such as unit_price or max_retries (often called snake_case). Choose names that say what the value means: seconds_left beats s. Never reuse the names of built-in functions such as list, str, sum or print, or you will hide the real one for the rest of the program.

Hands-on lab in the room: Python playground. Run it, then change qty to 10 and predict the new output before running again.

Value
A piece of data, such as 42, "Ana" or True.
Type
The kind of a value (int, float, str, bool, None...), which decides what you can do with it.
Variable
A name that refers to a value.
Assignment
A statement with one = that attaches a name to the value on the right.
int
The type of whole numbers, such as 3 or -12.
float
The type of numbers with a decimal point, such as 2.5.
bool
The type with just two values, True and False.
None
A special value meaning "no value".
PEP 8
Python's official style guide: lower_case_with_underscores names, 4-space indents and more.

Remember: = attaches a name to a value, and the right side is worked out first. Types belong to values: check one with type().

Lesson 3: Numbers and arithmetic

Goal: Calculate with Python's operators, predict int and float results, and handle rounding and float precision.

Python is an excellent calculator, but its operators have exact rules that you need to know to predict results.

Arithmetic operators
OperatorMeaningExampleResult
+ - *add, subtract, multiply7 * 214
/divide (always gives a float)7 / 23.5
//floor division: divide, then round down7 // 23
%remainder (modulo)7 % 21
**power2 ** 38

There are two kinds of division. / always gives a float, even when the answer is whole: 6 / 3 is 2.0. // divides and rounds down to a whole number, so 7 // 2 is 3 (and -7 // 2 is -4, because down means toward minus infinity). % gives the remainder: 7 % 2 is 1. Together, // and % split a quantity into parts, and n % 2 == 0 is the standard test for an even number.

Precedence works as in school mathematics: ** first, then *, /, // and %, then + and -; operators at the same level go left to right. When in doubt, add parentheses: (price + shipping) * qty is clearer than relying on rules.

Worked example: turning 135 minutes into hours and minutes

  1. hours = 135 // 60 gives 2, the number of whole hours.
  2. left = 135 % 60 gives 15, the minutes that do not fill another hour.
  3. Check: 2 * 60 + 15 is 135. The pair // and % always splits a number exactly.
  4. With tax: round(19.5 * 1.08, 2) gives 21.06; round keeps two decimal places.

The same pattern splits seconds into minutes, cents into whole currency units and items into full boxes plus leftovers.

Floats are approximations. Computers store floats in binary, and most decimals, such as 0.1, cannot be stored exactly, so 0.1 + 0.2 prints 0.30000000000000004. This is not a Python bug: almost every language does the same. Round results for display, never test floats with == (check that the difference is tiny instead), and in real money systems count whole cents as ints or use the decimal module.

Ints have no size limit in Python, so 2 100 is exact. Mixing an int and a float gives a float: 3 + 0.5 is 3.5. Useful built-ins: abs(-4) is 4, round(3.14159, 2) is 3.14, min(4, 9, 2) is 2 and max(4, 9, 2) is 9. Augmented assignment** shortens updates: total += 5 means total = total + 5, and there are also -=, *= and /=.

Hands-on lab in the room: Python playground.

Hands-on lab in the room: Unit 1 coding exercises. Now write it yourself: the minutes come from input(), and hidden tests try several values.

Operator
A symbol that combines values, such as +, * or //.
Floor division
Division with //, which rounds the result down to a whole number.
Remainder (modulo)
What is left over after whole division, given by %.
Precedence
The order in which operators are applied: ** first, then * / // %, then + -.
Floating-point number
A float: a number stored in binary that is often a close approximation of the decimal you typed.
Augmented assignment
A shortcut such as total += 5, meaning total = total + 5.

Remember: / always gives a float; // rounds down; % is the remainder. Round floats for display and never compare them with ==.

Lesson 4: Input, output and f-strings

Goal: Read input, convert it to the right type and format output exactly with f-strings.

input() pauses the program, shows an optional prompt and waits for the user to type a line and press Enter. It always returns a string, even when the user types digits. So after age = input("Age: "), the line age + 1 crashes with a TypeError: Python will not add text and a number, because it cannot know whether you meant arithmetic or joining. You must convert the text first.

Converting between types
ExpressionResultNote
int("42")42Text to whole number. Spaces at the ends are fine: int(" 7 ") is 7
float("2.5")2.5Text to decimal number
str(42)"42"Anything to text
int("4.5")ValueErrorint() of text only accepts whole numbers
float("1,5")ValueErrorA comma is not a decimal point to Python
bool("False")TrueAny non-empty string is True. Compare text instead: answer == "yes"

In this page, input() reads from the Program input box under the editor: write one line there for each input() call before you press Run. What you "typed" appears in blue in the output, the way a terminal shows your typing.

print() takes several arguments and joins them with spaces. Two options change that: sep sets the separator, so print("a", "b", sep="-") prints a-b, and end sets what comes at the end instead of a new line, so print("Loading", end="...") stays on the same line.

f-strings are the modern way to build text from values. Put f before the opening quote and write any expression inside braces: f"{name} is {age} years old". A format spec after a colon controls how a value looks, without changing the value:

Common format specs
Inside the bracesShowsMeaning
{price:.2f}3.50exactly two decimals (rounded)
{n:,}1,234,567commas between thousands
{total:,.2f}1,234.50both together
{rate:.0%}25%a fraction (0.25) as a percentage
{name:>10} / {name:<10} Anaright- or left-aligned in 10 characters
{qty=}qty=3name and value, handy when debugging
item = input("Item: ")            # the user types: Notebook
qty = int(input("Quantity: "))     # 3   (converted to int)
price = float(input("Price: "))    # 2.5 (converted to float)
total = qty * price
print(f"{qty} x {item:<10} {total:>8.2f}")

Worked example: a receipt line from user input

  1. item stays a string: it is a name, not a number.
  2. int(...) and float(...) wrap input(...), converting the text as soon as it arrives.
  3. total is 3 * 2.5, which is 7.5.
  4. The f-string left-aligns the item in 10 characters and right-aligns the total in 8, with 2 decimals.

Output: 3, the item padded to 10 characters, then 7.50 padded to 8. Every receipt line lines up in neat columns, whatever the item name.

Hands-on lab in the room: Python playground. The Program input box is filled in for you. Change the answers and run again.

Hands-on lab in the room: Unit 1 coding exercises. Graded exercise: two inputs, a conversion and a format spec.

input()
A function that shows a prompt, waits for a line of typing and returns it as a string.
Type conversion
Turning a value into another type with int(), float(), str() and similar functions.
f-string
A string with f before the quote, where expressions in {braces} are evaluated and inserted.
Format specification
The part after a colon inside f-string braces, such as :.2f or :,, that controls how a value is shown.

Remember: input() always gives a string: convert it with int() or float(). Format output with f-strings: {x:.2f}, {n:,}.

Practise it in Python Programming

Each lesson ends with three questions that check you can use the idea, not just recognise it. Wrong answers explain why and come back in Review. The unit ends with a 7-question quiz; pass it with 80% or more to master the unit. Hands-on lab: Python playground and Unit 1 coding exercises.

Every lesson is free: no ads, no lives and no paywall.