Progress0%

5 of 20 topics completed

Python Input and Output Operations

Input and output operations are essential parts of any program. They allow your program to interact with users, read data, and display results. In this tutorial, you'll learn how to handle these operations in Python with easy-to-understand examples.

💡 Why this matters

Almost every useful program needs to communicate with the outside world - whether it's getting information from users, reading files, or displaying results. Input/output is the bridge between your code and the real world.

Basic Output: Using print()

The print() function is the simplest way to display output in Python. It's like a messenger that takes your data and shows it to the user.

Python
1# Basic print statement
2print("Hello, Python learner!")
3
4# Printing multiple items
5print("The answer is", 42)
6
7# Printing with variables
8name = "Alex"
9age = 15
10print("Name:", name, "Age:", age)
11
12# Output:
13# Hello, Python learner!
14# The answer is 42
15# Name: Alex Age: 15

Formatting Your Output

You can make your output look nicer with formatting options:

Python
1# Using f-strings (Python 3.6+)
2name = "Emma"
3score = 95.5
4print(f"Student {name} scored {score} points")
5
6# Using format() method
7print("Student {} scored {} points".format(name, score))
8
9# Using format specifiers
10print("Score: {:.1f}%".format(score)) # Show only 1 decimal place
11
12# Output:
13# Student Emma scored 95.5 points
14# Student Emma scored 95.5 points
15# Score: 95.5%

Printing on the Same Line

By default, print() adds a newline at the end. You can change this:

Python
1# Countdown without newlines
2print("Counting down: ", end="")
3print("3... ", end="")
4print("2... ", end="")
5print("1... ", end="")
6print("Go!")
7
8# Output:
9# Counting down: 3... 2... 1... Go!

Getting User Input with input()

The input() function allows your program to get information from the user:

Input-Output Flow Diagram
Python
1# Basic input
2name = input("What is your name? ")
3print("Hello,", name, "!")
4
5# Example output:
6# What is your name? Maria
7# Hello, Maria !

⚠️ Important Note

The input() function always returns a string, even if the user enters a number. If you need a number, you'll need to convert it.

Converting Input to Different Types

Python
1# Getting numeric input
2age_str = input("How old are you? ")
3age = int(age_str) # Convert string to integer
4
5height_str = input("How tall are you (in meters)? ")
6height = float(height_str) # Convert string to float
7
8print(f"In 5 years, you'll be {age + 5} years old.")
9print(f"Half your height is {height / 2} meters.")
10
11# Example output:
12# How old are you? 14
13# How tall are you (in meters)? 1.65
14# In 5 years, you'll be 19 years old.
15# Half your height is 0.825 meters.

Common Type Conversions

  • int(value) - Convert to integer
  • float(value) - Convert to decimal number
  • str(value) - Convert to string
  • bool(value) - Convert to boolean

Error Handling Tip

If the user enters invalid data (like "hello" when you expect a number), your program will crash with a ValueError. We'll learn how to handle these errors in a later tutorial.

Python
# This will crash if user enters text
age = int(input("Age: "))

Combining Input and Output: A Simple Conversation

Let's create a simple program that has a conversation with the user:

Python
1print("Hello! I'm a simple chatbot.")
2name = input("What's your name? ")
3
4print(f"Nice to meet you, {name}!")
5feeling = input("How are you feeling today? ")
6
7if "good" in feeling.lower() or "great" in feeling.lower() or "happy" in feeling.lower():
8 print("That's wonderful to hear!")
9elif "bad" in feeling.lower() or "sad" in feeling.lower() or "tired" in feeling.lower():
10 print("I'm sorry to hear that. I hope your day gets better!")
11else:
12 print(f"Thanks for sharing that you feel {feeling}.")
13
14age_str = input("How old are you? ")
15try:
16 age = int(age_str)
17 if age < 18:
18 print(f"Cool! You have {18 - age} more years until you're an adult.")
19 else:
20 print(f"Nice! You've been an adult for {age - 18} years.")
21except ValueError:
22 print("That doesn't seem to be a valid age, but that's okay!")
23
24print(f"It was nice talking with you, {name}. Have a great day!")

Advanced Input/Output Techniques

1. Multi-line Input

Python
1print("Tell me a short story (press Enter twice when done):")
2story_lines = []
3line = input()
4
5while line:
6 story_lines.append(line)
7 line = input()
8
9story = "
10".join(story_lines)
11print("
12Your story:")
13print(story)
14
15# Example:
16# Tell me a short story (press Enter twice when done):
17# Once upon a time, there was a Python programmer.
18# They loved coding day and night.
19# The end.
20#
21# Your story:
22# Once upon a time, there was a Python programmer.
23# They loved coding day and night.
24# The end.

2. Creating a Simple Menu

Python
1def show_menu():
2 print("
3==== Calculator Menu ====")
4 print("1. Add two numbers")
5 print("2. Subtract two numbers")
6 print("3. Multiply two numbers")
7 print("4. Divide two numbers")
8 print("5. Exit")
9 return input("Enter your choice (1-5): ")
10
11def get_numbers():
12 a = float(input("Enter first number: "))
13 b = float(input("Enter second number: "))
14 return a, b
15
16choice = ""
17while choice != "5":
18 choice = show_menu()
19
20 if choice == "1":
21 a, b = get_numbers()
22 print(f"Result: {a} + {b} = {a + b}")
23 elif choice == "2":
24 a, b = get_numbers()
25 print(f"Result: {a} - {b} = {a - b}")
26 elif choice == "3":
27 a, b = get_numbers()
28 print(f"Result: {a} * {b} = {a * b}")
29 elif choice == "4":
30 a, b = get_numbers()
31 if b == 0:
32 print("Error: Cannot divide by zero!")
33 else:
34 print(f"Result: {a} / {b} = {a / b}")
35 elif choice == "5":
36 print("Thank you for using the calculator. Goodbye!")
37 else:
38 print("Invalid choice. Please try again.")

Practice Exercise: Build a Mad Libs Game

Let's create a fun "Mad Libs" game that asks for different words and creates a story:

Python
1def mad_libs_game():
2 print("Welcome to Mad Libs!")
3 print("I'll ask for some words, then create a funny story.")
4
5 # Get inputs
6 name = input("Enter a name: ")
7 adjective1 = input("Enter an adjective: ")
8 adjective2 = input("Enter another adjective: ")
9 animal = input("Enter an animal: ")
10 verb1 = input("Enter a verb ending in 'ing': ")
11 verb2 = input("Enter another verb: ")
12 place = input("Enter a place: ")
13 number = input("Enter a number: ")
14
15 # Create the story
16 story = f"""
17 Once upon a time, there was a {adjective1} person named {name}.
18 {name} loved {verb1} with their pet {animal} every day.
19 One day, while at the {place}, {name} saw {number} {adjective2} birds.
20 The birds started to {verb2} which made {name} laugh uncontrollably.
21 It was truly the most {adjective1} day of {name}'s life!
22 """
23
24 # Display the result
25 print("
26Here's your story:")
27 print(story)
28
29# Run the game
30mad_libs_game()
31
32# Example output:
33# Welcome to Mad Libs!
34# I'll ask for some words, then create a funny story.
35# Enter a name: Skyler
36# Enter an adjective: silly
37# Enter another adjective: blue
38# Enter an animal: penguin
39# Enter a verb ending in 'ing': dancing
40# Enter another verb: sing
41# Enter a place: library
42# Enter a number: 42
43#
44# Here's your story:
45#
46# Once upon a time, there was a silly person named Skyler.
47# Skyler loved dancing with their pet penguin every day.
48# One day, while at the library, Skyler saw 42 blue birds.
49# The birds started to sing which made Skyler laugh uncontrollably.
50# It was truly the most silly day of Skyler's life!

🎯 Try it yourself!

Enhance the Mad Libs game with these ideas:

  • Add more story templates and let the user choose one
  • Include error checking to make sure inputs are appropriate
  • Allow saving the story to play again later

Input/Output in Real-World Programs

As you build more complex programs, you'll use these I/O concepts in many ways:

Forms & Websites

Web applications use forms to get user input and display formatted HTML as output.

Data Analysis

Programs read input from files or databases and output charts, reports, and statistics.

Games

Games accept player input (keyboard, mouse) and output graphics, sound, and text.

Summary

FunctionPurposeExample
print()Display output to the userprint("Hello")
input()Get text input from the username = input("Name: ")
int()Convert string to integerage = int(input("Age: "))
float()Convert string to decimalprice = float("10.99")

Related Tutorials

Learn about different types of data and how to store them in Python.

Learn more

Master string manipulation in Python.

Learn more

Learn about if statements, loops, and control flow in Python.

Learn more