Input and Output
Understand text input, convert it when needed, and present useful output.
Video coming to YouTube
Work through the full lesson and run its code while the video is being prepared for publication.
Understand the concept
In a normal Python terminal, input() reads a line and returns it as a string. If you need a number, convert that text with int() or float() before doing arithmetic.
The input box below the editor supplies one response per line to input(). We have put 17 there so the example runs immediately. Change it and run again. print() can show multiple values, and an f-string can give the result a clear label.
- input() returns text
- Convert numeric text
- Label output clearly
See it step by step
Read the code, predict the output, then compare it with the result.
01. Convert numeric text
age_text = "21"
age = int(age_text)
print(f"Current age: {age}")
print(f"Next year: {age + 1}")Current age: 21
Next year: 22input() also returns text like '21'. int() converts it before arithmetic; labels make the output clear.
02. Display labeled text
name = "Maya"
print("Learner:", name)
print(f"Name type: {type(name).__name__}")Learner: Maya
Name type: strprint() can combine a label and a value. An f-string gives you another way to label output.
Try it in Python
Edit the example and run it. Python starts in your browser the first time you click Run.
Python console
Ready to runNeed input()? Add one value per line
Your output appears here.
Need a hint?
Enter 21 in the console's input box before running. Keep int(entered_age); then print a line such as f'Current age: {age}; next year: {next_year}'.
Complete the task and select Check task to verify your code.
Quick quiz
Three questions. You can change your answers and try again.
Typical mistakes
Everyone meets these errors. See what causes them and how to fix them.
Adding a number to input text
entered_age = "17"
print(entered_age + 1)entered_age = "17"
print(int(entered_age) + 1)What happens: TypeError because entered_age is text.
Convert numeric text before arithmetic.
Converting nonnumeric text
entered_age = "seventeen"
print(int(entered_age))entered_age = "17"
print(int(entered_age))What happens: ValueError because the text is not a valid integer.
int accepts text that represents a valid whole number.