All 1.3 18 min read 10 question quiz 17 exam marks

Input and Operators

Getting data from the user, converting it before you use it, and every arithmetic and comparison operator you need.

Input

Python
name = input("What is your name? ")
print("Hello,", name)
input always returns a string

Even if the user types 42, you get the text "42". Convert it before doing arithmetic.

Python
age = int(input("How old are you? "))
price = float(input("Enter the price: "))

If the user types something that cannot be converted, the program crashes with a ValueError. Handling that properly comes later, but be aware of it now.

A safe pattern

Python
entry = input("Enter your age: ")
while not entry.isdigit():
    print("Please enter a whole number.")
    entry = input("Enter your age: ")
age = int(entry)
input() gives text, so convert it before doing sumsThe journey of one typed answer. The program asks How old are you, and the user types 15. The input function always gives back text, so the variable age holds the string 15 in quote marks, not the number. Passing it through int turns the text into the whole number 15, which can now be added to, so age plus one gives 16. The code on the bottom left does exactly that in three lines. The trap on the right shows what happens if the conversion is forgotten: adding the text 15 and the text 1 with a plus sign joins them into 151, whereas adding the numbers 15 and 1 gives 16.consoleHow old are you?15the user types 15age"15"strinput() always gives textint()age15intnow it can be added upage + 1 gives 16age.py1age = input("How old are you? ")2age = int(age)3print("Next year you will be", age + 1)The trap"15" + "1"15 + 1= "151"= 16joined, not addedarithmeticforget int() and + joins text1234
  1. The user types an answer at the console.
  2. input() always hands it back as text, a string, even when it looks like a number.
  3. int() turns the text into a whole number, so it can be used in sums.
  4. Skip the conversion and + joins text instead of adding: "15" + "1" is "151".
If the answer is going into a calculation, convert it as you take it in.
Casting between types: int, float and str, and when it failsCasting converts a value from one data type to another. int of the text 42 gives the whole number 42. int of 3.7 gives 3, because it cuts off the decimal part and does not round. str of the number 5 gives the text 5, so it can be joined to words. float of the text 3.14 gives the decimal number 3.14. The input function always gives back text, so a number typed by a user must be converted, as in age equals int of input. Some conversions fail: int of the text hello raises a ValueError, so input should be checked before it is converted.int("42")42stringint()42integertext to a whole numberint(3.7)3.7floatint()3integercuts off the decimal part: it does not roundstr(5)5integerstr()"5"stringa number to text, so it can be joined to wordsfloat("3.14")"3.14"stringfloat()3.14floattext to a decimal number1234input() always gives text5age = int(input("Age? "))print(age + 1)convert it before doing sums with itSome conversions fail6Output>>> int("hello")ValueError: invalid literalso check the input before converting it
  1. int() turns text into a whole number.
  2. int() on a float cuts off the decimals. It does not round.
  3. str() turns a number into text.
  4. float() turns text into a decimal number.
  5. input() always returns text, so convert it before doing sums.
  6. A conversion that does not make sense raises an error, so validate first.
Casting does not change the original. It makes a new value of the type you asked for.

Operators

Arithmetic

OperatorMeaningExampleResult
+Add7 + 310
-Subtract7 - 34
*Multiply7 * 321
/Divide, always gives a float7 / 23.5
//Integer division7 // 23
%Modulus, the remainder7 % 21
**Power2 ** 38

Modulus is more useful than it looks:

Python
if number % 2 == 0:
    print("Even")

minutes = seconds // 60
remaining = seconds % 60

if turn % 4 == 0:
    print("Every fourth turn")

Comparison

OperatorMeaning
==Equal to
!=Not equal to
< >Less than, greater than
<= >=Less than or equal to, greater than or equal to
One equals sign assigns, two compare

x = 5 puts 5 into x. x == 5 asks whether x is 5.

Logical

Python
if age >= 13 and age <= 19:
    print("Teenager")

if day == "Saturday" or day == "Sunday":
    print("Weekend")

if not logged_in:
    print("Please sign in")
  • and needs both sides true
  • or needs at least one true
  • not reverses it
Arithmetic and comparison operatorsThe arithmetic operators as seven cards: plus, minus, multiply, divide, DIV, MOD and power, each with a worked example. Seven divided by two is 3.5. DIV gives the whole number of times it goes in, so 7 DIV 2 is 3, written with a double slash in Python, and MOD gives what is left over, so 7 MOD 2 is 1, written with a percent sign. A picture shows it as seven cookies shared between two people: three each, and one left over. Below, the comparison operators give True or False: 5 equals 5 is True, 5 is not equal to 5 is False, 5 greater than or equal to 6 is False and 5 less than 6 is True. A warning shows the commonest slip: a single equals sign stores a value, while a double equals sign asks whether two values are equal.+add7 + 2= 9-subtract7 - 2= 5*multiply7 * 2= 14/divide7 / 2= 3.5//DIV7 // 2= 3%MOD7 % 2= 1**power2 ** 3= 81DIV and MOD: 7 cookies, 2 people3 each3 each1 left over7 // 2 = 3 (DIV)7 % 2 = 1 (MOD)2Comparing: True or False5 == 5True5 != 5False5 >= 6False5 < 6True= stores a value== asks "are they equal?"34
  1. Arithmetic: + - * / then DIV, MOD and power.
  2. DIV is how many whole times it goes in. MOD is what is left over.
  3. Comparisons ask a question, and the answer is always True or False.
  4. = stores a value. == asks whether two values are equal.
MOD is the clock operator: it is what is left when you have gone round as many times as you can.

Key terms you must be able to define

input()
A function that displays a prompt and returns whatever the user types, always as a string.
Modulus
The % operator, which returns the remainder after division.
Integer division
The // operator, which returns only the whole number part of a division.
Casting
Converting a value from one type to another, such as int() around input().
Operator
A symbol that performs an operation on one or more values.
Operand
A value that an operator acts on.

Flashcards

Say the definition out loud before you flip the card. Retrieving it from memory is what builds recall, reading it again is not.

Defineinput()
AnswerA function that displays a prompt and returns whatever the user types, always as a string.
DefineModulus
AnswerThe % operator, which returns the remainder after division.
DefineInteger division
AnswerThe // operator, which returns only the whole number part of a division.
DefineCasting
AnswerConverting a value from one type to another, such as int() around input().
DefineOperator
AnswerA symbol that performs an operation on one or more values.
DefineOperand
AnswerA value that an operator acts on.

Reach the top grade on this topic

  • Always convert input before doing arithmetic on it
  • Use modulus to test for even numbers, extract time units and cycle values
  • Know when / is wrong and // is what you meant
  • Write a prompt that tells the user exactly what format you expect

Mistakes that cost marks here

Avoid these
  • Forgetting int() around input, then doing arithmetic on a string.
  • Using / when // was meant, leaving a decimal point in a count of whole things.
  • Writing a prompt with no trailing space, so the user types against the question mark.
  • Assuming input strips spaces. It does not, which is why strip() is so often needed.
Fun fact

The single most common beginner bug in the world is forgetting that input returns text. If you remember only one thing from this page, make it that.

Knowledge check

0 of 10 answered
1What does input() always return?
2What does 17 % 5 give?
3What does 17 // 5 give?
4Which condition correctly tests whether n is even?
5How would you get the seconds part of a total number of seconds?
6What does 7 / 2 give in Python?
7What does 6 / 2 give?
8What is 2 ** 5?
9Which correctly reads a whole number from the user?
10What does " hi ".strip() give?
Score 0 / 10

Exam-style questions

Five written questions in the style of the real paper. Write a full answer, then let the marker check it against the mark scheme.

17 marks
1Explain why age = input("Age: ") followed by if age > 18: causes an error.3 marks
Explain

Mark scheme0 / 3
  • Linput returns a string
  • LA string cannot be compared with a number
  • LConvert with int() first
Model answer

The input function always returns a string, so age holds the text "20" rather than the number 20 even if the user types digits. Python cannot compare a string with an integer using a greater than operator, because there is no meaningful way to order text against a number, so it raises a TypeError. The fix is to convert the input as it is read, writing age = int(input("Age: ")), after which the comparison works as intended.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2Write a program that asks for a number and states whether it is even or odd.4 marks
Write

Mark scheme0 / 4
  • LAsks for input and converts it to an integer
  • LUses the modulus operator to test divisibility by 2
  • LPrints Even when the remainder is 0
  • LUses else to print Odd otherwise
Model answer

number = int(input("Enter a number: ")) if number % 2 == 0: print("Even") else: print("Odd") The input is converted to an integer so arithmetic can be performed. The modulus operator gives the remainder after dividing by 2, and a remainder of exactly 0 means the number divides evenly and is therefore even. Any other remainder means it is odd, which the else branch handles.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3Explain the difference between the / operator and the // operator in Python.2 marks
Explain

Mark scheme0 / 2
  • L/ performs normal division and always gives a float
  • L// performs integer division, giving only the whole number part
Model answer

The single slash performs ordinary division and always produces a float, so 7 / 2 gives 3.5 and even 6 / 2 gives 3.0 rather than 3. The double slash performs integer division, discarding anything after the decimal point and returning only the whole number part, so 7 // 2 gives 3. Integer division is useful when a fractional result makes no sense, for example working out how many whole minutes are in a number of seconds.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
4A program asks the user for a number of pencils and a total cost, then works out the cost of one pencil. Explain which operators and conversions are needed and why.4 marks
Explain

Mark scheme0 / 4
  • Linput returns a string so both values must be converted
  • LThe count is converted with int because it is a whole number
  • LThe cost is converted with float because it has a decimal part
  • LDivision with a single slash is used, which correctly gives a float
Model answer

count = int(input("How many pencils? ")) cost = float(input("Total cost: ")) print(f"Each pencil costs {cost / count:.2f}") The input function always returns a string, so neither value can be used in arithmetic until it is converted. The number of pencils is converted with int because a count is always a whole number, while the total cost is converted with float because prices include pence and an int would discard them. Ordinary division with a single slash is correct here because the answer genuinely may have a decimal part, and it returns a float even when the division happens to be exact. Integer division would be wrong, because it would throw away the pence.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
5Explain what the modulus operator does and give two situations where it is useful.4 marks
Explain

Mark scheme0 / 4
  • LModulus returns the remainder after division
  • LGives a correct example such as 17 % 5 being 2
  • LFirst use such as testing whether a number is even
  • LSecond use such as extracting time units or cycling a value
Model answer

The modulus operator performs a division and returns the remainder rather than the quotient, so 17 % 5 gives 2 because 5 goes into 17 three times with 2 left over. One common use is testing divisibility: if a number modulus 2 equals 0 then it divides exactly by two and is therefore even, and the same technique checks whether something should happen every third or every tenth time round a loop. A second use is extracting units from a total, for example converting a total number of seconds into minutes and seconds, where total // 60 gives the whole minutes and total % 60 gives the seconds remaining. Modulus is also used to wrap a value around a fixed range, such as moving a player back to the start of a board after the last square.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
Machine mark 0 / 17