Input and Operators
Getting data from the user, converting it before you use it, and every arithmetic and comparison operator you need.
Input
name = input("What is your name? ")
print("Hello,", name)Even if the user types 42, you get the text "42". Convert it before doing arithmetic.
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
entry = input("Enter your age: ")
while not entry.isdigit():
print("Please enter a whole number.")
entry = input("Enter your age: ")
age = int(entry)- The user types an answer at the console.
- input() always hands it back as text, a string, even when it looks like a number.
- int() turns the text into a whole number, so it can be used in sums.
- Skip the conversion and + joins text instead of adding: "15" + "1" is "151".
- int() turns text into a whole number.
- int() on a float cuts off the decimals. It does not round.
- str() turns a number into text.
- float() turns text into a decimal number.
- input() always returns text, so convert it before doing sums.
- A conversion that does not make sense raises an error, so validate first.
Operators
Arithmetic
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Add | 7 + 3 | 10 |
- | Subtract | 7 - 3 | 4 |
* | Multiply | 7 * 3 | 21 |
/ | Divide, always gives a float | 7 / 2 | 3.5 |
// | Integer division | 7 // 2 | 3 |
% | Modulus, the remainder | 7 % 2 | 1 |
** | Power | 2 ** 3 | 8 |
Modulus is more useful than it looks:
if number % 2 == 0:
print("Even")
minutes = seconds // 60
remaining = seconds % 60
if turn % 4 == 0:
print("Every fourth turn")Comparison
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
< > | Less than, greater than |
<= >= | Less than or equal to, greater than or equal to |
x = 5 puts 5 into x. x == 5 asks whether x is 5.
Logical
if age >= 13 and age <= 19:
print("Teenager")
if day == "Saturday" or day == "Sunday":
print("Weekend")
if not logged_in:
print("Please sign in")andneeds both sides trueorneeds at least one truenotreverses it
- Arithmetic: + - * / then DIV, MOD and power.
- DIV is how many whole times it goes in. MOD is what is left over.
- Comparisons ask a question, and the answer is always True or False.
- = stores a value. == asks whether two values are equal.
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.
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
- 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.
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
input() always return?17 % 5 give?17 // 5 give?7 / 2 give in Python?6 / 2 give?2 ** 5?" hi ".strip() give?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.
age = input("Age: ") followed by if age > 18: causes an error.3 marks- Linput returns a string
- LA string cannot be compared with a number
- LConvert with int() first
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.
- 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
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.
- L/ performs normal division and always gives a float
- L// performs integer division, giving only the whole number part
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.
- 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
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.
- 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
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.