Python Foundations·Python from zero

Input and output

Read user input, convert it to numbers and format output with f-strings.

Beginner 10 min read Lesson 3 of 480 Challenge included
What you will be able to do
  • Print output with print()
  • Read typed input with input()
  • Convert strings to numbers with int() and float()
  • Format output with f-strings

In plain English

Programs talk through output (text they print) and input (text the user types). print() writes a message to the screen. input() pauses the program and returns whatever the user typed as a string. To do math on that string you convert it with int() or float(). An f-string (a string starting with f) lets you drop values straight into a message inside curly braces.

Step by step

  1. 1Ask a question with input("...") and store the answer in a variable.
  2. 2Convert the string to a number with int() or float() inside try.
  3. 3Print the result with an f-string so the value appears in the message.
  4. 4Catch ValueError to handle non-numeric typing without crashing.
greet.pyPython
name = input("What is your name? ")
print(f"Hello, {name}!")

answer = input("How many lessons have you finished? ")
try:
    completed = int(answer)
    print(f"You are {completed} lessons in.")
except ValueError:
    print("That is not a whole number. Please try again.")

Common mistakes

  • Forgetting that input() always returns a string, then trying to do math on it.
  • Writing print(f...) but missing the f, so the curly braces print literally.
  • Comparing a converted number to a string, like 10 == "10", which is always False.
  • Letting bad input crash the program instead of catching ValueError.
Your turn

Read and double a number

Easy

Ask the user for a number, convert it to a float, double it and print the result in a sentence.

PYTHON · starter
answer = input("Enter a number: ")
Check your understanding before moving on.
Knowledge checkQuestion 1

What type does input() always return?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Numbers and math
Lesson 3 of 480 · 0% of course