Adding Two Numbers
The problem: ask the user for two numbers, add them together, and display the sum. It sounds too small to bother with — and it is the pattern behind almost every program you will write this year.
1Plan it before you type it
Every program answers three questions. Answer them on paper first and the code almost writes itself:
- the first number,
a - the second number,
b
total = a + b
- the value of
total, with a message
2The program
# program to add two numbers given by the user
a = int(input('Enter the first number: '))
b = int(input('Enter the second number: '))
total = a + b
print('The sum is', total)Enter the first number: 27 Enter the second number: 45 The sum is 72
Run it yourself. It stops at each input() and waits for you, exactly as it would in a terminal — type a number and press Enter:
3Line by line
a = int(input('Enter the first number: '))Three things happen, from the inside out. input() shows the message and waits. Whatever is typed comes back as text. int() turns that text into a whole number. The = stores it in a box called a.
b = int(input('Enter the second number: '))The same again for the second number, into a different box. Two boxes, because you need both values at the same time.
total = a + bThe right-hand side runs first: Python adds the two numbers. The answer then goes into a new box called total.
print('The sum is', total)print() shows the message and the value, separated by a space. Without the message the user sees a bare number and has to guess what it means.
4The mistake everybody makes
Leave out int() and the program still runs — that is what makes it dangerous. input() hands you text, and + joins two pieces of text end to end instead of adding them:
a = input('Enter the first number: ')
b = input('Enter the second number: ')
print('The sum is', a + b)Enter the first number: 27 Enter the second number: 45 The sum is 2745
2745, not 72. No error message, no traceback — just a wrong answer, which makes this a logical error. Whenever a sum comes out looking like the two numbers stuck together, you forgot to cast.
float() accepts both 7 and 7.5; int() refuses anything with a decimal point — int('7.5') is a ValueError, and so is int('7.0'). So float() is the safer, more general choice. Keep int() for values where a decimal would be plain wrong: a number of shirts, a count of students, a year.5Now you try
Two small changes to make to the program below:
- Make it work with decimal numbers too — change both
int()tofloat()and try 2.5 and 3.5. - Print the difference and the product as well, on their own lines.
6Recap
input(), cast with int() or float(), calculate into a variable, show with print(). Every program on the next few pages is this same four-step shape with a different sum in the middle.The user types 27 and 45, and the program prints 2745. What went wrong?
In a = int(input('Enter: ')), which runs first?