Input and output (I/O) operations are fundamental aspects of any programming language, allowing programs to interact with users and other systems. Python provides straightforward and flexible methods for handling I/O operations, including reading from and writing to the console, files, and other external sources.
input()
FunctionThe input()
function is used to get user input from the console. It reads a line from input, converts it to a string, and returns it.
name = input("Enter your name: ")
print("Hello, " + name + "!")
Since input()
returns a string, you may need to convert it to other data types such as integers or floats.
age = int(input("Enter your age: "))
height = float(input("Enter your height in meters: "))
print("You are " + str(age) + " years old and " + str(height) + " meters tall.")
print()
FunctionThe print()
function is used to output data to the console. It can accept multiple arguments, which are converted to strings and printed with a space between them by default.
print("Hello, world!")
print("The sum of 2 and 3 is", 2 + 3)
Python offers several ways to format strings for output, including concatenation, the format()
method, and f-strings (formatted string literals).
name = "Alice"
print("Hello, " + name + "!")
format()
Methodname = "Alice"
print("Hello, {}!".format(name))
print("You are {} years old and {} meters tall.".format(age, height))
Introduced in Python 3.6, f-strings provide a concise and readable way to embed expressions inside string literals using curly braces {}
.
name = "Alice"
age = 30
height = 1.75
print(f"Hello, {name}!")
print(f"You are {age} years old and {height} meters tall.")