Input and output operations are fundamental in Python programming, allowing interactive applications that can take user input and display results or messages. Here’s an in-depth look at using the input()
and print()
functions in Python with several examples.
The print()
Function
The print()
function is used to send data to the output, typically the console. It can handle multiple arguments of different data types, separated by commas. Python converts all arguments to strings and writes them to the standard output.
Basic Usage:
1 |
print("Hello, World!") |
Printing Multiple Items:
1 2 3 |
name = "Alice" age = 30 print(name, "is", age, "years old.") |
Formatting Output: You can format strings in several ways, such as f-strings (formatted string literals) introduced in Python 3.6, str.format()
, and the %
operator.
Using f-strings:
1 |
print(f"{name} is {age} years old.") |
Using str.format()
:
1 |
print("{} is {} years old.".format(name, age)) |
Using %
operator (less recommended, but still used):
1 |
print("%s is %d years old." % (name, age)) |
Specifying End and Separator:
1 2 3 4 5 6 |
# Use end parameter print("Hello,", end=" ") print("World!") # Use sep parameter print("2023", "02", "08", sep="-") |
The input()
Function
The input()
function allows your program to pause and wait for the user to type something from the keyboard. Once the user presses Enter, the function returns what was typed as a string.
Basic Usage:
1 2 |
user_name = input("Enter your name: ") print(f"Hello, {user_name}!") |
Using Input with Integer Values: Since input()
returns a string, you must convert it to an integer or float when you need to work with numbers.
1 2 3 |
age = input("Enter your age: ") age = int(age) # Convert string to integer print(f"You are {age} years old.") |
Combining input()
and print()
for Interactive Scripts:
1 2 3 4 5 |
# Simple calculator num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) sum = num1 + num2 print(f"The sum of {num1} and {num2} is {sum}.") |
Handling Multiple Inputs:
1 2 3 |
# Splitting input string into multiple variables first_name, last_name = input("Enter your first and last name: ").split() print(f"Hello, {first_name} {last_name}!") |
These examples showcase the versatility of input()
and print()
functions in Python, allowing for a wide range of interactive applications, from simple scripts to more complex programs requiring user interaction. By mastering these basic I/O functions, you can enhance the interactivity and usability of your Python programs.