Computer ScienceFoundation20 min read

Introduction to Python Programming

Variables, types, input and output — the whole vocabulary of a first program

This topic appears in:

01

A variable is a labelled box

A variable is a name attached to a value stored in memory. Writing age = 15 creates the name age and points it at the value 15. Writing age = 16 later does not create a second variable — it points the same name at a new value, and the old one is gone.

Python decides the type from the value you give it, which is called dynamic typing. You never declare that age is a whole number; Python sees 15 and knows. That makes the language quick to write and means a mistake about types is discovered when the program runs rather than before.

TypeHoldsExample
inta whole numbermarks = 87
floata number with a decimal partaverage = 72.5
strtextname = "Ayesha"
boolTrue or Falsepassed = True
listan ordered collectionscores = [80, 75, 91]

Naming rules, and the one that catches people

A name may contain letters, digits and underscores, must not start with a digit, and must not be a Python keyword such as if, for or print. Names are case-sensitive, so Total and total are two different variables — and a program that assigns to one and prints the other fails with an error that names a variable you are sure you defined.

02

Input always arrives as text

input() displays a prompt and returns whatever the user typed — always as a string, even when it looks like a number. This single fact causes more first-program bugs than anything else.

If you read two numbers and add them without converting, Python joins the text instead of adding: "5" + "3" is "53". Convert with int() or float() first.

name = input("What is your name? ")age = int(input("How old are you? "))price = float(input("Price: "))print("Hello", name, "you are", age)wrap input() in int() or float() the moment the value is meant to be a number
Worked example

A program asks for two numbers and prints their total. Explain why a = input(); b = input(); print(a + b) prints 53 when the user types 5 and 3.

  1. input() returns a string, so a holds "5" and b holds "3".The quotes are the point — these are text, not numbers.
  2. The + operator does different things for different types.For numbers it adds; for strings it joins end to end, which is called concatenation.
  3. Since both are strings, "5" + "3" produces "53".No error occurs, which is why this bug is easy to miss — the program runs and gives a wrong answer.
  4. Fix it with a = int(input()) and b = int(input()).Now both are integers and + means addition, giving 8.

Both values are strings, so + joins them. Convert with int() first.

03

Operators

Python's arithmetic operators are mostly familiar, with three worth noting. / always produces a float, even when the division is exact — 6 / 3 is 2.0, not 2. // is integer division, discarding the remainder. % gives the remainder itself, and is how you test whether a number divides exactly.

OperatorMeaningExample
+ − *add, subtract, multiply7 * 3 → 21
/divide, always giving a float7 / 2 → 3.5
//integer division7 // 2 → 3
%remainder (modulus)7 % 2 → 1
**power2 ** 8 → 256
== != < >comparison, giving True or False5 > 3 → True
and or notcombining conditionsx > 0 and x < 10

One equals sign is not two

= assigns a value: x = 5 puts 5 into x. == compares: x == 5 asks whether x holds 5 and answers True or False. Writing if x = 5: is a syntax error in Python — which is fortunate, because in some other languages it silently assigns and the condition is always true.

04

Following a program by hand

Reading code is a skill separate from writing it, and it is what exam questions test most often. Work through line by line, writing down what every variable holds after each statement — exactly as a trace table does.

Do it slowly for programs you think you understand. A trace is the only reliable way to catch the difference between what you meant and what you wrote.

Choose Swap and step to line 4. a is already 8, so without temp holding the original value the 5 would be lost — which is why swapping two variables always needs a third.

05

Comments, and writing code someone can read

A comment begins with # and is ignored by Python entirely. Its purpose is the human reader — including you, six months later.

Good comments explain why, not what. # add 1 to count next to count = count + 1 is noise; # count only students who actually sat the paper is worth having. The other half of readable code is naming: total_marks tells the reader something that t does not, and costs nothing.

Before you leave this chapter

  1. A variable is a name pointing at a value; assigning again replaces it.
  2. Python infers the type from the value — int, float, str, bool, list.
  3. input() always returns a string. Wrap it in int() or float() for numbers.
  4. / gives a float, // discards the remainder, % gives the remainder.
  5. = assigns, == compares. Names are case-sensitive.

Practice questions

6 questions · 20 marks · full working on every one

Try each one on paper first, then open the working. The marks are shown where they are actually awarded, because that is where they are actually lost.

Short questions

3 · 6 marks

Two marks each, in the style of the short-question section of the paper. Answer in two or three lines.

SQ1[2 marks]
What is a variable, and what does x = 10 do?
Model answer

A variable is a named location in memory holding a value. x = 10 creates the name x and assigns the integer value 10 to it. Assigning again later replaces the value rather than creating a second variable.

Examiner tip. Use the word "assign" rather than "equals". The = sign in programming does not state a fact; it performs an action.

SQ2[2 marks]
Why must int() often be used with input()?
Model answer

Because input() always returns a string, even when the user types digits. Without conversion, + would join the text instead of adding — "5" + "3" gives "53" — and comparisons would compare text rather than numeric value.

Examiner tip. Give the concrete consequence. "It converts to an integer" restates the function name without explaining why it is needed.

SQ3[2 marks]
State the difference between = and ==.
Model answer

= is the assignment operator, storing a value in a variable. == is the comparison operator, testing whether two values are equal and producing True or False.

Examiner tip. One does something; the other asks something. Saying it that way makes the distinction unambiguous.

Solved numericals

2 · 8 marks

Full working, one step per line, with the marks shown where they are awarded.

N1[4 marks]
Write a Python program that asks the user for the length and width of a rectangle and prints its area.
Full working
  1. length = float(input("Enter length: "))float rather than int allows decimal measurements[1]
  2. width = float(input("Enter width: "))[1]
  3. area = length * widtha meaningful variable name is expected[1]
  4. print("The area is", area)output must be labelled, not a bare number[1]

Read both values as floats, multiply, and print with a label.

Examiner tip. Use float rather than int for a measurement — a rectangle 2.5 m long is perfectly reasonable, and int() would refuse it.

N2[4 marks]
State the output of each: (i) print(7 // 2) (ii) print(7 % 2) (iii) print(7 / 2) (iv) print(2 ** 3)
Full working
  1. (i) 3 — integer division discards the remaindernot 3.5[1]
  2. (ii) 1 — the remainder when 7 is divided by 2[1]
  3. (iii) 3.5 — / always produces a floatnote the decimal point[1]
  4. (iv) 8 — ** is the power operator2 cubed[1]

(i) 3 (ii) 1 (iii) 3.5 (iv) 8

Examiner tip. Note that 6 / 3 gives 2.0 rather than 2. The / operator produces a float even when the division comes out exact.

Long questions

1 · 6 marks

Theory and numerical together, as they appear in the long-question section.

LQ1[6 marks]
A student writes this program to calculate a average of two test marks: a = input("Mark 1: "), b = input("Mark 2: "), avg = a + b / 2, print(avg)
  1. Identify two errors in this program.
  2. Write a corrected version.
  3. Explain how you would test that your corrected version works.
Mark scheme
  1. Error 1: the inputs are strings, so they are joined rather than addedint() or float() is missing[1]
  2. Error 2: operator precedence — a + b / 2 divides b by 2 first, so brackets are needed: (a + b) / 2this error survives even after the type is fixed[1]
  3. Corrected input lines using float(input(…))[1]
  4. avg = (a + b) / 2 followed by a labelled print[1]
  5. Test with normal data, such as 60 and 80, and check the answer is 70a value you can verify by hand[1]
  6. Test with boundary data such as 0 and 100, and with erroneous data such as text, to see how it behavesall three kinds of test data[1]

(a) inputs not converted, and missing brackets (b) float(input(…)) and (a+b)/2 (c) normal, boundary and erroneous data

Examiner tip. The precedence error is the interesting one, because it survives after the obvious type error is fixed. Division binds tighter than addition, so brackets are compulsory here.