1. Output (Print Statement):
The print()
function is used to display output to the console.
name = "Alice"
age = 25
# Displaying variables
print("Name:", name)
print("Age:", age)
# Concatenation in print
print("Name:", name, "Age:", age)
# Formatted output (using f-strings in Python 3.6 and later)
print(f"Name: {name}, Age: {age}")
2. Input:
The input()
function is used to get user input from the console. Note that input()
returns a string, so you might need to convert it to the desired data type.
# Getting user input
user_name = input("Enter your name: ")
# Displaying the input
print("Hello, " + user_name + "!")
3. Formatted Output (String Formatting):
You can format strings using placeholders or the format()
method.
Using Placeholders:
name = "Bob"
age = 30
# Placeholder formatting
print("Name: %s, Age: %d" % (name, age))
Using format()
Method:
# Using format method
print("Name: {}, Age: {}".format(name, age))
4. Formatted Output (f-strings):
f-strings (formatted string literals) provide a concise way to embed expressions inside string literals.
# Using f-strings
print(f"Name: {name}, Age: {age}")
5. File Input and Output:
You can read from and write to files using the open()
function.
Writing to a File:
# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, Python!")
Reading from a File:
# Reading from a file
with open("example.txt", "r") as file:
content = file.read()
print(content)
6. Separator and End Parameters in print()
:
The print()
function allows specifying the separator between printed items and the ending character.
# Separator and end parameters
print("apple", "banana", "orange", sep=", ", end=".\n")
7. Formatted Output with Precision:
Control the precision of floating-point numbers when printing.
pi_value = 3.141592653589793
# Formatting with precision
print(f"Value of pi: {pi_value:.2f}")
8. Redirecting Output to a File:
You can redirect the print()
output to a file by changing the sys.stdout
stream.
import sys
# Redirecting output to a file
with open("output.txt", "w") as file:
sys.stdout = file
print("This will be written to the file.")
sys.stdout = sys.__stdout__ # Resetting the stream
9. Error Output:
The print()
function can be used to output to the standard error stream (sys.stderr
) for error messages.
import sys
# Error output
print("Error: Something went wrong.", file=sys.stderr)
Understanding input and output operations is fundamental for creating interactive and dynamic Python programs. In the next sections, we’ll explore how to use these concepts in various scenarios and applications.