- What Input/Output is ā how programs communicate with users
- The input() function ā accepting user input
- Type conversion ā converting input to different data types
- The print() function ā displaying output to users
- Print formatting ā controlling how output appears
- f-strings ā modern string formatting
- Escape sequences ā special characters in strings
- File I/O ā reading and writing files
- Hands-on practice with the interactive editor
What is Input/Output in Python?
Input/Output (I/O) is how a program communicates with the outside world. In Python, input refers to data that comes from the user (via keyboard, files, or other sources), while output refers to data that the program sends out (to the console, files, or other destinations).
Think of a program like a conversation. The program asks questions (output), you respond (input), and the program processes your response and responds back (output). This interaction is the foundation of interactive programming.
# Simple Input/Output Example
name = input("What's your name? ") # Input
print("Hello, " + name + "!") # Output
š” Key insight: Python has two built-in functions for basic I/O: input() for accepting user input and print() for displaying output. These are your program's "voice" and "ears."
1. The input() Function
The input() function is used to accept user input from the keyboard. It reads a line of text from the user and returns it as a string.
# Basic input() usage
name = input("What is your name? ")
print("Nice to meet you, " + name + "!")
# Output:
# What is your name? (user types: Alice)
# Nice to meet you, Alice!
ā ļø Important: The input() function always returns a string, even if the user enters a number. You must convert the data to the appropriate type using int(), float(), etc.
2. Type Conversion with input()
Since input() always returns a string, you need to convert it to the desired data type for numerical operations.
# Converting input to integer
age = int(input("Enter your age: "))
print("Next year you will be", age + 1)
# Converting input to float
price = float(input("Enter the price: "))
print("Price with 10% tax:", price * 1.10)
# Output:
# Enter your age: 25
# Next year you will be 26
# Enter the price: 50.50
# Price with 10% tax: 55.55
# Multiple inputs in one line
x, y = input("Enter two numbers: ").split()
x = int(x)
y = int(y)
print("Sum:", x + y)
# Output:
# Enter two numbers: 10 20
# Sum: 30
3. The print() Function
The print() function is used to display output to the console. It can accept multiple arguments and automatically adds a space between them.
# Basic print() usage
print("Hello, World!")
# Print with multiple arguments
print("The answer is", 42)
# Print with variables
name = "Python"
version = 3.12
print("Language:", name, "Version:", version)
# Output:
# Hello, World!
# The answer is 42
# Language: Python Version: 3.12
4. Print Formatting
Python provides several ways to format output. Let's explore the most common and modern approaches.
a. f-strings (Formatted String Literals)
f-strings are the most modern and recommended way to format strings in Python. They are introduced in Python 3.6 and are both readable and efficient.
# f-string examples
name = "Python"
version = 3.12
year = 2024
print(f"Language: {name}, Version: {version}, Year: {year}")
# With expressions
radius = 5
print(f"Area of circle: {3.14 * radius * radius:.2f}")
# Output:
# Language: Python, Version: 3.12, Year: 2024
# Area of circle: 78.50
b. The format() Method
The format() method is another way to format strings. It uses placeholders {} in the string and passes values to them.
# format() examples
name = "Python"
version = 3.12
print("Language: {}, Version: {}".format(name, version))
# Positional formatting
print("Name: {0}, Age: {1}".format("Alice", 25))
# Named formatting
print("Name: {name}, Age: {age}".format(name="Bob", age=30))
# Output:
# Language: Python, Version: 3.12
# Name: Alice, Age: 25
# Name: Bob, Age: 30
5. Escape Sequences
Escape sequences are special characters used to control how text is displayed. They begin with a backslash \.
\n
Newline
\t
Tab
\\
Backslash
\"
Double quote
\'
Single quote
\r
Carriage return
# Escape sequence examples
print("Line 1\nLine 2")
print("Column 1\tColumn 2")
print("She said, \"Hello!\"")
print("Path: C:\\Users\\Documents")
# Output:
# Line 1
# Line 2
# Column 1 Column 2
# She said, "Hello!"
# Path: C:\Users\Documents
6. File Input/Output
Python can read from and write to files using the open() function. This allows you to store data permanently.
# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, Python!\n")
file.write("This is a second line.")
# Reading from a file
with open("example.txt", "r") as file:
content = file.read()
print(content)
# Output:
# Hello, Python!
# This is a second line.
# Reading line by line
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
# Output:
# Hello, Python!
# This is a second line.
Try It Yourself!
Experiment with input and output directly in your browser. Modify the code and see the results in real time.
BASIC INPUT/OUTPUT
========================================
What's your name? (user types: Alice)
Hello, Alice! Nice to meet you!
========================================
TYPE CONVERSION
========================================
Enter your age: 25
Next year you will be 26
Enter a price: 50.50
Price with 10% tax: 55.55
========================================
PRINT FORMATTING
========================================
Language: Python
Version: 3.12
Area of circle (r=7): 153.86
========================================
ESCAPE SEQUENCES
========================================
Line 1\nLine 2: shows newline
Column 1\tColumn 2: shows tab
ā Explore different I/O operations!
š You've Mastered Python Input/Output!
You understand input(), print(), type conversion, f-strings, formatting, escape sequences, and file I/O. These are essential skills for interactive Python programs.
Quick Quiz ā Test Your Knowledge
Let's see what you've learned about Python Input/Output:
input() function always return?Frequently Asked Questions
š¤ What's the difference between print() and return?
ā¼
print() displays output to the console, while return sends a value back from a function. print() is for user communication; return is for function communication.
š§ How do I prevent print() from adding a new line?
ā¼
end parameter: print("Hello", end="") or print("Hello", end=" ") to add a space instead of a newline.
š What does the with statement do in file I/O?
ā¼
with statement automatically closes the file when the block is exited. It's the recommended way to work with files because it handles cleanup even if an error occurs.
š What's the difference between f-strings and format()?
ā¼
format() is older but still widely used. f-strings are recommended for Python 3.6+.
š Where to Go From Here
Now that you understand Python Input/Output, here are some related topics to explore:
āØļø Accept Input
Deep dive into the input() function
š¤ Output Formatting
Master print() and formatting
š File Handling
Learn advanced file operations