Chapter 4

Input and Output

Show information with print and collect data from users with input.

Programs talk to the user in two directions: they show things with print() and they collect things with input().

Printing output

The print() function displays whatever you pass it, then moves to a new line:

print('Hello!')
print('Sum is', 5)

Several values separated by commas are printed with a space between them. You can change the separator or ending:

print('a', 'b', sep='-')   # a-b
print('no newline', end=' ')

Reading input

The input() function pauses the program, shows an optional prompt, and returns whatever the user types. It always returns a string:

name = input('Your name: ')
print('Hi', name)

Converting input to numbers

Because input is always text, you must convert it before doing maths. Use int() or float():

age_text = input('Age: ')
age = int(age_text)
print(age + 1)

Doing maths on a raw input without converting causes errors or joins text instead of adding numbers.

Combining output nicely

f-strings make friendly output easy:

city = input('City: ')
print(f'You live in {city}')

A short interactive example

Here is a tiny program that asks for two numbers and adds them. Notice each input is converted before the maths:

a = int(input('First number: '))
b = int(input('Second number: '))
print('Total is', a + b)

If you forgot the int() calls, the two answers would be joined as text instead of added, so 2 and 3 would give 23 rather than 5.

Printing several things together

You can mix text and values in one print call. Commas add spaces automatically, while an f-string gives you full control:

score = 8
print('You scored', score, 'points')
print(f'You scored {score} points')

Rounding numbers for display

When showing a decimal answer, round it so it reads cleanly:

average = 7.6666
print(round(average, 1))   # 7.7

Guarding against bad input

Users sometimes type the wrong thing. A safe habit is to check the text before converting, for example with the isdigit() method which is True only when the text is all digits:

reply = input('Age: ')
if reply.isdigit():
    print('Next year you will be', int(reply) + 1)
else:
    print('Please type a number')

This keeps the program from crashing when someone types letters by mistake.

Remember

  • input() always gives you a string, even if the user types digits.
  • Wrap input in int() or float() before doing arithmetic.
  • print() adds a newline unless you change the end value.

Stuck on this topic? A verified JomKelas tutor can walk you through it.

Find a verified tutor