LESSON 13 · BEGINNER PATH13 min

Input and Output

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.

Understand text input, convert it when needed, and present useful output.

Before you start: Variables and Types

Example check: Worked and guided code samples are checked against CPython 3.13. Practice uses Pyodide 0.29.5 (Python 3.13) in your browser. How we check lessons

Video lesson: Input and Output

The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube

Read the video transcript

Select a timestamp to watch that moment on YouTube.

  1. 00:00

    So far, many of our examples have their values written directly into the program. Input lets a user supply a value when the program runs. Output lets the program tell the user what it found or calculated. Between those two ends, the program must understand what kind of value it received. In this lesson, we will read an age, convert the entered text to an integer, and print an age for next year. We will then clean a name with strip, check numeric text before converting it, and produce a small formatted report. The key fact to remember is that input returns text, even when the characters look like digits. The string twenty-one and the integer twenty-one are different values to Python.

  2. 00:45

    Open the Input and Output lesson console if you want to test each variation. It has an input box, so you can supply the line that the code will read and see exactly what appears in the output area. The first line calls input with a question prompt. The text the user enters becomes the value of entered_age. If the user types two and one, entered_age is the string containing those two characters. The next line calls int on that string. For valid whole-number text, int returns an integer, so age now refers to twenty-one as a number. Adding one gives twenty-two. The f-string inserts that result into a clear sentence: Next year you will be twenty-two.

  3. 01:28

    The site console may show the prompt and the submitted text as part of its input display; the important computed result is the next-year sentence. To prove that conversion mattered, try printing the type of entered_age and the type of age. The first is str, and the second is int. If you try to add one directly to entered_age, Python will not guess whether you meant arithmetic or joining text. You must express the conversion. Now consider a name entered with spaces around it. Calling strip returns a new string without leading and trailing whitespace. The guide example sets display_name to the cleaned name or the fallback learner.

  4. 02:09

    If the cleaned string is empty, the fallback is used and the program prints Welcome, learner. If the input is Maya, it prints Welcome, Maya. This makes output helpful even when the user presses Enter without typing a name. For age input, conversion can fail if the text is not a valid integer. The validation example calls strip and tests isdecimal before calling int. For twenty-one, the check is true, and it prints Next birthday: twenty-two. For a word like twenty-one written out in letters, the check is false, and it asks for a nonnegative whole number instead. This is a simple rule for this lesson, not a complete solution for every numeric format: a minus sign or decimal point also fails isdecimal.

  5. 02:56

    If your program needs negative or decimal values, it needs a different validation strategy. A final example reads an item name and quantity, then prints a report. With Lesson and seven, formatting quantity with three digits produces zero zero seven. That format changes the display, not the numeric value. The second line adds one and reports eight. A useful output says what each value means. Printing bare seven and eight would force the reader to guess which is the current quantity and which is the updated quantity. Pause here and predict what happens if quantity is ten. The padded field will show zero one zero, and after one more it will show eleven.

  6. 03:39

    Then test that prediction in the console. The first mistake is adding a number to the text returned by input. A string such as seventeen plus the integer one raises TypeError because those types do not support that addition together. Convert the valid numeric string with int before performing arithmetic. The second mistake is assuming every answer can be converted. Passing the word seventeen to int raises ValueError because those characters are not a valid integer representation. You can check the input and give a helpful message, or catch the conversion error in a later lesson about exceptions. Do not silently replace every invalid answer with zero unless zero genuinely represents what the user meant.

  7. 04:26

    That would hide an input problem and perhaps produce a misleading result. Another easy mistake is to confuse the input prompt with the value returned by input. The prompt is text shown to the user; it is not the answer. Give variables names such as entered_age or raw_age to remind yourself which values still need conversion. When debugging, inspect one value and its type at each step: raw input, cleaned text, converted number, calculated result, and displayed string. That chain tells you where a mismatch arose. The practical task begins with the age program. Put twenty-one in the lesson's input box and run it.

  8. 05:07

    Add a second print line that labels the current age as well as the next-year age. Predict Current age: twenty-one and Next year: twenty-two, allowing for your exact wording while keeping both values clear. Press Check Task after the program runs. As a stretch exercise, enter blank text for a name in the separate cleanup example and see how the fallback works. Then try the word twenty-one in the validation example and explain why it does not reach int. The quiz asks what input returns, why numeric text needs conversion, and how output can communicate a result clearly. If you can describe the type at every step, you have a strong foundation for the later exceptions and file lessons, where data comes from sources beyond a single input box.

Understand the concept

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

PYTHON
age_text = "21"
age = int(age_text)
print(f"Current age: {age}")
print(f"Next year: {age + 1}")
EXPECTED OUTPUT
Current age: 21
Next year: 22

input() also returns text like '21'. int() converts it before arithmetic; labels make the output clear.

02. Display labeled text

PYTHON
name = "Maya"
print("Learner:", name)
print(f"Name type: {type(name).__name__}")
EXPECTED OUTPUT
Learner: Maya
Name type: str

print() can combine a label and a value. An f-string gives you another way to label output.

A closer look

Follow the reasoning, inspect each result, then try the suggested changes in the console below.

01 / 03

Read one line, then clean it

Each input() call consumes one line from the input stream and returns a string without its trailing newline. A user may still type spaces before or after the useful text. Calling strip() removes that surrounding whitespace. The returned string can then be checked before you include it in a message or store it for later use.

The lesson console provides input through its separate input box: put one response on each line, in the same order as input() calls. This example handles an empty name by choosing a friendly default. Enter three spaces instead of Maya and predict the result after strip() makes the name empty. Then try a name with extra spaces around it.

PYTHON
name = input().strip()
display_name = name or "learner"
print(f"Welcome, {display_name}!")
EXPECTED OUTPUT
Welcome, Maya!
SAMPLE INPUT — ONE VALUE PER LINE
Maya
Follow the reasoning
  1. input() reads Maya as text from the first input line.
  2. strip() removes surrounding whitespace if present.
  3. The or expression supplies a fallback only for an empty name.
02 / 03

Validate numeric text before converting it

Text that looks like a number is still a string. A program should decide what inputs it accepts before calling int(), because converting unsuitable text raises ValueError. For a simple nonnegative whole-number input, isdecimal() can be a first check. Only after that check does this example convert the text and add one.

This is a narrow rule: a minus sign, decimal point, or empty line does not pass isdecimal(). That is appropriate for a nonnegative whole-number age but not for every numeric field. Try entering -1 and then 12.5; predict the message each time. Later, exceptions will offer another way to handle failed conversion when valid formats are more varied.

PYTHON
raw_age = input().strip()

if raw_age.isdecimal():
    age = int(raw_age)
    print(f"Next birthday: {age + 1}")
else:
    print("Enter a nonnegative whole number")
EXPECTED OUTPUT
Next birthday: 22
SAMPLE INPUT — ONE VALUE PER LINE
21
Follow the reasoning
  1. The first line is read as '21', not as the integer 21.
  2. isdecimal() accepts these digits, so int() converts them.
  3. The program prints the numeric result after adding one.
03 / 03

Make output useful to the next reader

A bare value may be hard to interpret when a script grows. Labeled output explains what the value represents, and formatting can keep a report consistent. Two input() calls below consume two separate lines: one for a label and one for a quantity. The integer format :03d displays a whole number in a field of at least three digits, padding with zeros when needed.

Formatting changes the displayed text, not the underlying integer. If you later calculate with quantity, it remains 7. Keep a clear distinction between data and its presentation. Change the second input line to 125 and predict whether any zeros appear. Then add a third print() call that shows quantity + 1 to confirm that the value is still numeric.

PYTHON
item = input().strip()
quantity = int(input().strip())

print(f"{item}: {quantity:03d}")
print(f"Items after one more: {quantity + 1}")
EXPECTED OUTPUT
Lesson: 007
Items after one more: 8
SAMPLE INPUT — ONE VALUE PER LINE
Lesson
7
Follow the reasoning
  1. The first input line supplies the label; the second supplies numeric text.
  2. int() converts 7 before arithmetic or numeric formatting.
  3. :03d pads the display to three digits, while the stored value stays 7.

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 run
Need input()? Add one value per line
Ctrl / ⌘ + Enter to run
OUTPUT
Your output appears here.
Your turnChange the value in the input box to 21 and run again. Add a second print line that shows the current age and next-year age with clear labels.
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.

    01.What type does input() return in a normal Python terminal?

    02.What is int("4") + 1?

    03.What does print("a", "b") display by default?

    Typical mistakes

    Everyone meets these errors. See what causes them and how to fix them.

    Adding a number to input text

    COMMON MISTAKE
    entered_age = "17"
    print(entered_age + 1)
    FIX
    entered_age = "17"
    print(int(entered_age) + 1)

    What happens: TypeError because entered_age is text.
    Convert numeric text before arithmetic.

    Converting nonnumeric text

    COMMON MISTAKE
    entered_age = "seventeen"
    print(int(entered_age))
    FIX
    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.

    Browse this lesson’s problem fixes