Input and Output

Big Idea

Most useful programs communicate. They show information to the user, ask the user for information, and then use that information to make decisions or produce a result. In Python, the two basic tools for this are print() and input(). print() sends output from the program to the screen. input() receives text typed by the user. This article explains how to display clear output, how to use formatted strings, how to collect input, and why user input often needs to be converted before it can be used in calculations.

1   Why Do Programs Need Input and Output?

A program that cannot receive input or produce output is like a locked room. Something might be happening inside, but the user cannot interact with it or understand what it has done.

Input and output are how a program connects to the outside world:

  • Input is information that enters the program.
  • Output is information that leaves the program and is shown to the user.

For example, a quiz program might ask the user for their name, ask several questions, calculate a score, and then print the result:

name = input("What is your name? ")
score = 8
total = 10

print(f"{name}, you scored {score}/{total}.")

Possible output:

What is your name? Alex
Alex, you scored 8/10.

The program is not just running silently. It is having a simple conversation with the user.

Analogy: A Conversation

Output is what the program says. Input is what the user says back. A program that uses both can behave differently depending on what the user types. That is the beginning of interactivity.

In beginner Python programs, input and output usually happen in the terminal. Later, the same ideas appear in web forms, buttons, database queries, APIs, and graphical interfaces. The surface changes, but the basic pattern remains the same: receive data, process data, output information.

Check Your Understanding
  1. What is the difference between input and output?
  2. In the line name = input("What is your name? "), what information enters the program?
  3. In the line print("Welcome!"), what information leaves the program?
  4. Write one example of a real program that needs input and output.

2   Output with print()

The print() function displays information on the screen. It is usually the first output tool students learn because it is simple and immediate.

print("Hello, world!")
print("Welcome to Python.")
print("This program is running.")

Output:

Hello, world!
Welcome to Python.
This program is running.

Each print() statement displays its message and then moves to a new line.

2.1   Printing Text

Text in Python is called a string. Strings must be written inside quotation marks:

print("Hello")
print('Hello')

Both versions work. Python allows either double quotes or single quotes for strings. The important rule is that the opening and closing quote must match.

print("This works.")
print('This also works.')
print("This does not work.')
# SyntaxError because the quotes do not match
Warning: Strings need matching quotes

If you start a string with double quotes, end it with double quotes. If you start with single quotes, end with single quotes. Mismatched quotes cause a SyntaxError.

2.2   Printing Numbers

You can also print numbers. Numbers do not need quotation marks:

print(42)
print(3.14)
print(100 + 25)

Output:

42
3.14
125

When Python sees 100 + 25, it calculates the result first and then prints the result.

2.3   Printing Variables

A variable stores a value. You can print the value stored in a variable by writing the variable name inside print():

name = "Alex"
age = 14

print(name)
print(age)

Output:

Alex
14

Notice the difference between printing a string and printing a variable:

name = "Alex"

print("name")  # prints the literal text: name
print(name)    # prints the value stored in the variable: Alex

Output:

name
Alex
Common Confusion: "name" vs. name

"name" is a string containing the letters n-a-m-e. name without quotes is a variable name. Python looks up the value stored in that variable. Quotation marks change the meaning completely.

2.4   Printing Multiple Values

You can print more than one value by separating the values with commas:

name = "Alex"
score = 85

print(name, "scored", score, "points.")

Output:

Alex scored 85 points.

When you use commas inside print(), Python automatically adds spaces between the values. This is useful for quick output, especially when you are debugging.

2.5   Printing Blank Lines

An empty print() statement prints a blank line:

print("Student Report")
print()
print("Name: Alex")
print("Score: 85")

Output:

Student Report

Name: Alex
Score: 85

Blank lines can make output easier to read.

Check Your Understanding
  1. What does print() do?
  2. What is the difference between print("score") and print(score)?
  3. Predict the output:

    city = "Warsaw"
    temperature = 21
    
    print("City:", city)
    print("Temperature:", temperature)
  4. Write three print() statements that display a simple profile: name, age, and favourite subject.

3   Formatted Strings

Printing with commas works, but formatted strings are usually cleaner. A formatted string, usually called an f-string, lets you place variable values directly inside a string.

An f-string begins with the letter f before the opening quote. Variables or expressions go inside curly braces: { }.

name = "Alex"
score = 85

print(f"{name} scored {score} points.")

Output:

Alex scored 85 points.

This is easier to read than joining many pieces with commas or plus signs.

3.1   The Anatomy of an f-string

print(f"{name} scored {score} points.")
PartWhat it is
fTells Python this is a formatted string.
"..."The string itself. It still needs quotation marks.
{name}Python replaces this with the value stored in name.
{score}Python replaces this with the value stored in score.
Normal textAnything outside curly braces is printed exactly as written.

3.2   f-strings Can Use Expressions

The curly braces can contain variables, but they can also contain simple calculations:

score = 8
total = 10

print(f"You scored {score}/{total}.")
print(f"Percentage: {score / total * 100}%")

Output:

You scored 8/10.
Percentage: 80.0%

Python evaluates the expression inside the braces and inserts the result into the string.

3.3   Rounding Numbers in f-strings

Sometimes calculations produce long decimal numbers. You can format a number to a fixed number of decimal places using :.1f, :.2f, and so on.

score = 7
total = 9
percentage = score / total * 100

print(f"Percentage: {percentage}")
print(f"Percentage: {percentage:.1f}%")
print(f"Percentage: {percentage:.2f}%")

Output:

Percentage: 77.77777777777779
Percentage: 77.8%
Percentage: 77.78%
FormatMeaningExample output
{percentage}Print the value as Python normally displays it.77.77777777777779
{percentage:.1f}Print as a decimal number with 1 digit after the decimal point.77.8
{percentage:.2f}Print as a decimal number with 2 digits after the decimal point.77.78
Useful habit

Use f-strings for output that includes variables. They make your code easier to read and make your output easier to control.

3.4   Aligning Output

f-strings can also align text. This is useful when printing simple tables in the terminal.

name1 = "Alex"
name2 = "Priya"
name3 = "Sam"

score1 = 85
score2 = 92
score3 = 7

print(f"{'Name':<10} {'Score':>5}")
print(f"{name1:<10} {score1:>5}")
print(f"{name2:<10} {score2:>5}")
print(f"{name3:<10} {score3:>5}")

Output:

Name       Score
Alex          85
Priya         92
Sam            7

The symbol < means left-align. The symbol > means right-align. The number says how wide the space should be.

{name1:<10}   # left-align in a space 10 characters wide
{score1:>5}   # right-align in a space 5 characters wide

You do not need alignment for every beginner program, but it is useful when output should look organized.

Check Your Understanding
  1. What does the f before a string mean?
  2. What do curly braces do inside an f-string?
  3. Predict the output:

    name = "Maya"
    points = 17
    
    print(f"{name} earned {points} points.")
  4. Write an f-string that prints: Alex has 12 coins. Use variables for the name and number of coins.
  5. What does {price:.2f} do inside an f-string?

4   Input with input()

The input() function pauses the program and waits for the user to type something. When the user presses Enter, Python takes what the user typed and gives it back to the program as a string.

name = input("What is your name? ")
print(f"Hello, {name}!")

Possible run:

What is your name? Alex
Hello, Alex!

The text inside input() is called the prompt. It tells the user what to type.

4.1   The Anatomy of input()

name = input("What is your name? ")
PartWhat it is
nameThe variable where the user's answer will be stored.
=Assignment. The result of input() is assigned to the variable.
inputThe function that waits for the user to type something.
("What is your name? ")The prompt shown to the user before they type.

4.2   The Prompt Should Be Clear

A prompt should tell the user exactly what kind of information to enter:

name = input("Enter your name: ")
city = input("Enter your city: ")
subject = input("Enter your favourite subject: ")

print(f"{name} lives in {city} and likes {subject}.")

Possible output:

Enter your name: Alex
Enter your city: Warsaw
Enter your favourite subject: Computer Science
Alex lives in Warsaw and likes Computer Science.

Good prompts reduce confusion. Bad prompts make the user guess what the program wants.

Weak promptBetter promptWhy it is better
input("Name")input("Enter your name: ")It clearly asks the user to do something.
input("Number?")input("Enter a number from 1 to 10: ")It gives the expected range.
input("Age")input("Enter your age in years: ")It explains the unit.

4.3   input() Always Returns a String

This is the most important rule about input():

Important rule

input() always returns a string, even if the user types a number.

Look carefully at this program:

age = input("Enter your age: ")

print(age)
print(type(age))

Possible output:

Enter your age: 14
14
<class 'str'>

The user typed 14, but Python stored it as the string "14", not the integer 14.

Common Confusion: It looks like a number, but it is text

When the user types 14, it looks like a number to a human. But input() gives Python the string "14". If you want to do math with it, you must convert it first.

Check Your Understanding
  1. What does input() do?
  2. What is a prompt?
  3. What type of value does input() always return?
  4. Predict the output:

    colour = input("Enter a colour: ")
    print(f"You chose {colour}.")
  5. Why is input("Enter your age: ") clearer than input("Age")?

5   Converting Input

Since input() always returns a string, numeric input must be converted before you can use it in calculations.

This program does not work correctly:

age = input("Enter your age: ")
next_year = age + 1

print(f"Next year you will be {next_year}.")

If the user types 14, Python raises an error:

TypeError: can only concatenate str (not "int") to str

The problem is that age contains the string "14", not the integer 14. You cannot add the number 1 to the text "14".

5.1   Converting to an Integer with int()

Use int() when the user should enter a whole number:

age_text = input("Enter your age: ")
age = int(age_text)

next_year = age + 1

print(f"Next year you will be {next_year}.")

Possible output:

Enter your age: 14
Next year you will be 15.

This can be shortened to one line:

age = int(input("Enter your age: "))
print(f"Next year you will be {age + 1}.")

Both versions work. The two-step version is easier to understand when you are learning. The one-line version is common once you are comfortable.

5.2   Converting to a Float with float()

Use float() when the user may enter a decimal number:

price = float(input("Enter the price: "))
tax_rate = 0.23

total = price + price * tax_rate

print(f"Total price: {total:.2f}")

Possible output:

Enter the price: 19.99
Total price: 24.59

A float is a number that can include a decimal point.

5.3   Choosing the Right Conversion

User inputUse this conversionExample
Name, city, password, favourite subjectNo conversion neededname = input("Enter your name: ")
Age, score, number of lives, number of studentsint()age = int(input("Enter your age: "))
Price, height, weight, temperature, percentagefloat()price = float(input("Enter price: "))

5.4   What Happens If Conversion Fails?

If Python cannot convert the user's input, the program crashes with a ValueError:

age = int(input("Enter your age: "))

If the user types fourteen instead of 14, Python cannot turn that word into an integer:

Enter your age: fourteen
ValueError: invalid literal for int() with base 10: 'fourteen'

This is normal. Beginner programs often assume the user enters valid input. Later, you will learn how to validate input and handle errors more carefully.

Warning: Conversion only works on valid text

int("14") works. int("fourteen") does not. float("3.5") works. float("three point five") does not. Python needs numeric text in a format it understands.

5.5   String Addition vs. Number Addition

This example shows why conversion matters:

a = input("Enter first number: ")
b = input("Enter second number: ")

print(a + b)

Possible output:

Enter first number: 10
Enter second number: 5
105

Python prints 105, not 15, because both values are strings. The + operator joins strings together. This is called concatenation.

To add the numbers mathematically, convert them:

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

print(a + b)

Output:

Enter first number: 10
Enter second number: 5
15
Common Confusion: Why did Python print 105?

If a is "10" and b is "5", then a + b means join the strings together: "10" + "5" becomes "105". If a is 10 and b is 5, then a + b means numeric addition: 10 + 5 becomes 15.

Check Your Understanding
  1. Why does numeric input usually need to be converted?
  2. When should you use int()?
  3. When should you use float()?
  4. Predict the output:

    x = input("Enter x: ")
    y = input("Enter y: ")
    print(x + y)

    Assume the user enters 3 and then 4.

  5. Fix the program above so it prints 7 instead of 34.

6   Building Useful Output

Good output is not just correct. It is readable. The user should understand what the program is asking and what the result means.

Compare these two programs:

# Harder to understand
x = int(input())
y = int(input())
print(x + y)
# Easier to understand
first_number = int(input("Enter the first number: "))
second_number = int(input("Enter the second number: "))

total = first_number + second_number

print(f"{first_number} + {second_number} = {total}")

Possible output:

Enter the first number: 8
Enter the second number: 12
8 + 12 = 20

The second version is better because:

  • The prompts tell the user what to enter.
  • The variable names explain what the values mean.
  • The output labels the result instead of printing a mystery number.

6.1   Example: Personal Data Card

This program asks the user for information and prints a simple formatted card:

name = input("Enter your name: ")
age = int(input("Enter your age: "))
city = input("Enter your city: ")
subject = input("Enter your favourite subject: ")

print()
print("=== Personal Data Card ===")
print(f"Name:              {name}")
print(f"Age:               {age}")
print(f"City:              {city}")
print(f"Favourite subject: {subject}")
print(f"Next year:         {age + 1}")

Possible output:

Enter your name: Alex
Enter your age: 14
Enter your city: Warsaw
Enter your favourite subject: Computer Science

=== Personal Data Card ===
Name:              Alex
Age:               14
City:              Warsaw
Favourite subject: Computer Science
Next year:         15

This is a simple program, but it already follows the basic pattern of many larger programs:

  1. Ask for input.
  2. Store the input in variables.
  3. Convert values when necessary.
  4. Process the data.
  5. Print useful output.

6.2   Example: Score Calculator

This program asks for a score and a total, calculates a percentage, and prints a clear result:

name = input("Enter student name: ")
score = float(input("Enter score earned: "))
total = float(input("Enter total possible points: "))

percentage = score / total * 100

print()
print("=== Score Report ===")
print(f"Student:    {name}")
print(f"Score:      {score}/{total}")
print(f"Percentage: {percentage:.1f}%")

Possible output:

Enter student name: Priya
Enter score earned: 37
Enter total possible points: 50

=== Score Report ===
Student:    Priya
Score:      37.0/50.0
Percentage: 74.0%

The program uses float() because scores might include decimals, such as 37.5.

The output should explain the result

A program should not just print 74.0. It should print enough context for the user to understand what 74.0 means. Clear output is part of good programming.

Check Your Understanding
  1. Why is print(total) less helpful than print(f"Total: {total}")?
  2. Write a program that asks for a user's name and favourite food, then prints a sentence using both values.
  3. Write a program that asks for the width and height of a rectangle, converts both to integers, and prints the area.
  4. Modify the score calculator so it also prints whether the percentage is greater than or equal to 60.

7   New Lines, Tabs, and Special Characters

Sometimes you need to include special formatting inside a string. Python uses escape characters for this. An escape character begins with a backslash: \.

7.1   New Line: \n

The escape character \n means "start a new line."

print("Line 1\nLine 2\nLine 3")

Output:

Line 1
Line 2
Line 3

This can be useful, but do not overuse it. Multiple print() statements are often clearer for beginners.

7.2   Tab: \t

The escape character \t inserts a tab space:

print("Name\tScore")
print("Alex\t85")
print("Priya\t92")

Output:

Name    Score
Alex    85
Priya   92

Tabs can help line up simple output, but f-string alignment is usually more reliable for tables.

7.3   Quotation Marks Inside Strings

If your string contains quotation marks, you have two common choices. You can use single quotes outside and double quotes inside:

print('She said, "Hello!"')

Or you can escape the inner quotes:

print("She said, \"Hello!\"")

Both produce the same output:

She said, "Hello!"
Check Your Understanding
  1. What does \n do inside a string?
  2. What does \t do inside a string?
  3. Write one print() statement that prints two lines of output using \n.
  4. Why might f-string alignment be better than tabs for printing a table?

8   Common Mistakes to Watch For

MistakeWhat it looks likeWhat actually happensFix
Forgetting quotation marks around textprint(Hello)Python looks for a variable named Hello. If it does not exist, you get a NameError.Use quotes: print("Hello").
Printing the variable name instead of the variable valueprint("score")Prints the literal word score, not the value stored in the variable.Remove quotes around the variable: print(score).
Forgetting the f in an f-stringprint("{name} scored {score}")Prints the braces literally instead of inserting variable values.Add f: print(f"{name} scored {score}").
Trying to do math with unconverted inputage = input("Age: ")
print(age + 1)
age is a string, so Python cannot add the integer 1.Convert first: age = int(input("Age: ")).
Getting string joining instead of number additionUser types 10 and 5; program prints 105.input() returned strings, so + joined them.Convert both values with int() or float().
Using int() for decimal inputprice = int(input("Price: ")) and user types 19.99.Python raises a ValueError because 19.99 is not an integer.Use float() for decimal values.
Writing unclear promptsinput("Number: ")The user may not know what number is expected.Write a specific prompt: input("Enter a score from 0 to 100: ").
Check Your Understanding
  1. This program has a bug. Identify it and fix it:

    name = "Alex"
    print("Hello, {name}")
  2. This program has a bug. Identify it and fix it:

    score = input("Enter score: ")
    total = score + 10
    print(total)
  3. Why does this print 55 instead of 10?

    a = input("Enter a number: ")
    b = input("Enter another number: ")
    print(a + b)
  4. Write a corrected version of the program above.

9   Putting It All Together

Here is a complete beginner program that uses clear prompts, input, type conversion, calculations, and formatted output.

print("=== Rectangle Area Calculator ===")
print()

width = float(input("Enter the width of the rectangle: "))
height = float(input("Enter the height of the rectangle: "))

area = width * height
perimeter = 2 * (width + height)

print()
print("=== Results ===")
print(f"Width:     {width:.2f}")
print(f"Height:    {height:.2f}")
print(f"Area:      {area:.2f}")
print(f"Perimeter: {perimeter:.2f}")

Possible output:

=== Rectangle Area Calculator ===

Enter the width of the rectangle: 6
Enter the height of the rectangle: 8

=== Results ===
Width:     6.00
Height:    8.00
Area:      48.00
Perimeter: 28.00

What to notice:

  • The program begins with a title so the user knows what it does.
  • Each prompt clearly tells the user what to enter.
  • float() is used because width and height might be decimal values.
  • The calculations are stored in well-named variables.
  • The output labels every result.
  • The f-strings format numbers to two decimal places.
The basic input/output pattern

A strong beginner program usually follows this structure: print a title, ask for input with clear prompts, convert input if needed, process the data, then print labelled output. This pattern will appear again and again in your programs.

10   Quick Reference

TaskSyntax / ExampleKey rule
Print textprint("Hello")Text strings must be inside quotation marks.
Print a variableprint(name)No quotation marks around the variable name.
Print multiple valuesprint(name, score)Commas automatically add spaces between values.
Use an f-stringprint(f"Hello, {name}")Start with f. Put variables inside { }.
Format a decimalprint(f"{price:.2f}")Prints the number with two digits after the decimal point.
Ask for text inputname = input("Enter your name: ")input() always returns a string.
Ask for integer inputage = int(input("Enter your age: "))Use int() for whole numbers.
Ask for decimal inputprice = float(input("Enter price: "))Use float() for decimal numbers.
Print a blank lineprint()Useful for spacing output.
New line inside a stringprint("Line 1\nLine 2")\n means start a new line.