Tutorials / Python from Scratch / Input and output: talking to the user

Input and output: talking to the user

12 min read python
Course contents (15 lessons)
  1. Getting started
  2. Installing Python 3.13 and running your first script
  3. Variables and basic data types
  4. Text, numbers and user input
  5. Working with strings
  6. Numbers and arithmetic
  7. Input and output: talking to the user
  8. Making decisions and repeating work
  9. Making decisions with if, elif and else
  10. Loops: for, while, break and continue
  11. Collections of data
  12. Lists and tuples
  13. Dictionaries and sets
  14. Functions and modules
  15. Writing your own functions
  16. Modules, pip and virtual environments
  17. Files and errors
  18. Reading and writing files
  19. Errors and exceptions
  20. Final project: expense tracker
  21. Project: build the expense tracker, part 1
  22. Project: summaries, search and improvements

Programs that talk back

Up to now our scripts had all their data written inside them. Useful programs ask for data. The input() function pauses the program, shows a message, waits for the user to type something and press Enter, then gives you what they typed.

name = input("What is your name? ")
print("Nice to meet you, " + name)

Run it and type a name. The text you typed is stored in name.

input() always returns a string

This is the number one beginner trap. Even if the user types 25, you get the text "25". If you try to do maths with it, you will either get an error or a wrong answer.

age = input("Age: ")
print(age + 1)        # TypeError: can only concatenate str (not "int") to str

Convert the text first with int() or float():

age = int(input("Age: "))
print(age + 1)

Wrapping input() inside int() in one line is common. It reads: ask, then convert.

A complete example: a tip calculator

print("=== Restaurant bill ===")

bill = float(input("Bill amount: "))
tip_percent = float(input("Tip percent (for example 10): "))
people = int(input("Number of people: "))

tip = bill * tip_percent / 100
total = bill + tip
per_person = total / people

print()
print(f"Tip:        {tip:10.2f}")
print(f"Total:      {total:10.2f}")
print(f"Per person: {per_person:10.2f}")

Run with the values 4500, 10 and 3, and you get:

=== Restaurant bill ===
Bill amount: 4500
Tip percent (for example 10): 10
Number of people: 3

Tip:            450.00
Total:         4950.00
Per person:    1650.00

What this program does

It asks three questions and converts each answer to the right type. It calculates the tip and the total. The print() with no arguments prints a blank line. The {tip:10.2f} format reserves 10 characters of width and shows two decimals, which makes the numbers line up in a column.

More about print()

print() can take several values separated by commas. It puts a space between them and adds a new line at the end.

print("Total:", 4950, "rupees")      # Total: 4950 rupees
print("A", "B", "C", sep="-")         # A-B-C
print("Loading", end="...")           # no new line afterwards
print("done")                         # Loading...done

The sep option changes the separator. The end option changes what is printed at the end, which is a new line by default.

Notice that with commas, you do not need to convert numbers to text. print does that for you. That is another reason to prefer commas or f-strings over +.

Common mistakes

  • Forgetting to convert. Covered above. If maths gives an odd result such as "55" instead of 10, check the type.
  • Not handling bad input. If the user types abc when you call int(), the program crashes with a ValueError. You will learn to handle this in the errors lesson. For now, just know it can happen.
  • Extra spaces. Users add spaces. Call .strip() on text input: name = input("Name: ").strip().
  • Using int() on a decimal string. int("3.5") fails. Use float() first, or ask for a whole number.

Command line arguments, briefly

Not every program asks questions while running. Many get their values when you start them, such as python report.py 2025. Those values live in sys.argv. We will not use it in this course, but it is good to know it exists.

Try it yourself

Write a program that asks for a temperature in Celsius and prints it in Fahrenheit. The formula is f = c * 9 / 5 + 32. Print the result with one decimal. Check it: 37 degrees Celsius should give 98.6. Bonus: ask for the user's name first and use it in the final message, such as Ali, 37.0 C is 98.6 F.

python
print("=== Restaurant bill ===")

bill = float(input("Bill amount: "))
tip_percent = float(input("Tip percent (for example 10): "))
people = int(input("Number of people: "))

tip = bill * tip_percent / 100
total = bill + tip
per_person = total / people

print()
print(f"Tip:        {tip:10.2f}")
print(f"Total:      {total:10.2f}")
print(f"Per person: {per_person:10.2f}")

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account