Input and output
Read user input, convert it to numbers and format output with f-strings.
- 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
- 1Ask a question with input("...") and store the answer in a variable.
- 2Convert the string to a number with int() or float() inside try.
- 3Print the result with an f-string so the value appears in the message.
- 4Catch ValueError to handle non-numeric typing without crashing.
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.
Read and double a number
Ask the user for a number, convert it to a float, double it and print the result in a sentence.
answer = input("Enter a number: ")
What type does input() always return?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.