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.
1# Basic print statement2print("Hello, Python learner!")34# Printing multiple items5print("The answer is", 42)67# Printing with variables8name = "Alex"9age = 1510print("Name:", name, "Age:", age)1112# Output:13# Hello, Python learner!14# The answer is 4215# Name: Alex Age: 15
Formatting Your Output
You can make your output look nicer with formatting options:
1# Using f-strings (Python 3.6+)2name = "Emma"3score = 95.54print(f"Student {name} scored {score} points")56# Using format() method7print("Student {} scored {} points".format(name, score))89# Using format specifiers10print("Score: {:.1f}%".format(score)) # Show only 1 decimal place1112# Output:13# Student Emma scored 95.5 points14# Student Emma scored 95.5 points15# Score: 95.5%
Printing on the Same Line
By default, print()
adds a newline at the end. You can change this:
1# Countdown without newlines2print("Counting down: ", end="")3print("3... ", end="")4print("2... ", end="")5print("1... ", end="")6print("Go!")78# 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:

1# Basic input2name = input("What is your name? ")3print("Hello,", name, "!")45# Example output:6# What is your name? Maria7# 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
1# Getting numeric input2age_str = input("How old are you? ")3age = int(age_str) # Convert string to integer45height_str = input("How tall are you (in meters)? ")6height = float(height_str) # Convert string to float78print(f"In 5 years, you'll be {age + 5} years old.")9print(f"Half your height is {height / 2} meters.")1011# Example output:12# How old are you? 1413# How tall are you (in meters)? 1.6514# In 5 years, you'll be 19 years old.15# Half your height is 0.825 meters.
Common Type Conversions
int(value)
- Convert to integerfloat(value)
- Convert to decimal numberstr(value)
- Convert to stringbool(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.
# This will crash if user enters textage = int(input("Age: "))
Combining Input and Output: A Simple Conversation
Let's create a simple program that has a conversation with the user:
1print("Hello! I'm a simple chatbot.")2name = input("What's your name? ")34print(f"Nice to meet you, {name}!")5feeling = input("How are you feeling today? ")67if "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}.")1314age_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!")2324print(f"It was nice talking with you, {name}. Have a great day!")
Advanced Input/Output Techniques
1. Multi-line Input
1print("Tell me a short story (press Enter twice when done):")2story_lines = []3line = input()45while line:6 story_lines.append(line)7 line = input()89story = "10".join(story_lines)11print("12Your story:")13print(story)1415# 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
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): ")1011def get_numbers():12 a = float(input("Enter first number: "))13 b = float(input("Enter second number: "))14 return a, b1516choice = ""17while choice != "5":18 choice = show_menu()1920 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:
1def mad_libs_game():2 print("Welcome to Mad Libs!")3 print("I'll ask for some words, then create a funny story.")45 # Get inputs6 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: ")1415 # Create the story16 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 """2324 # Display the result25 print("26Here's your story:")27 print(story)2829# Run the game30mad_libs_game()3132# Example output:33# Welcome to Mad Libs!34# I'll ask for some words, then create a funny story.35# Enter a name: Skyler36# Enter an adjective: silly37# Enter another adjective: blue38# Enter an animal: penguin39# Enter a verb ending in 'ing': dancing40# Enter another verb: sing41# Enter a place: library42# Enter a number: 4243#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
Function | Purpose | Example |
---|---|---|
print() | Display output to the user | print("Hello") |
input() | Get text input from the user | name = input("Name: ") |
int() | Convert string to integer | age = int(input("Age: ")) |
float() | Convert string to decimal | price = float("10.99") |
Related Tutorials
Learn about different types of data and how to store them in Python.
Learn moreMaster string manipulation in Python.
Learn moreLearn about if statements, loops, and control flow in Python.
Learn more