Python provides simple and intuitive functions for handling input and output operations. The most commonly used functions are print()
for output and input()
for user input. This article explains their usage with examples.
print()
The print()
function is used to display messages or data on the screen. It supports displaying strings, numbers, and other objects.
# Example 1: Printing a message
print("Hello, World!")
Output:
Hello, World!
You can also print multiple values separated by commas:
# Example 2: Printing multiple values
name = "Alice"
age = 25
print("Name:", name, "Age:", age)
Output:
Name: Alice Age: 25
input()
The input()
function is used to get input from the user. The function returns the input as a string.
# Example 3: Taking input from the user
name = input("Enter your name: ")
print("Hello,", name)
If the user enters "Bob", the output will be:
Enter your name: Bob Hello, Bob
Since input()
returns a string, you may need to convert it to other data types for calculations or further processing.
# Example 4: Converting input to integer
age = input("Enter your age: ")
age = int(age) # Convert string to integer
print("Next year, you will be", age + 1, "years old.")
If the user enters "25", the output will be:
Enter your age: 25 Next year, you will be 26 years old.
print()
for Formatted OutputPython allows formatted output using f-strings or the format()
method.
# Example 5: f-strings for formatted output
name = "Alice"
age = 25
print(f"Name: {name}, Age: {age}")
Output:
Name: Alice, Age: 25
format()
:
# Example 6: Using the format() method
name = "Bob"
age = 30
print("Name: {}, Age: {}".format(name, age))
Output:
Name: Bob, Age: 30
print()
and input()
You can combine both functions to create interactive programs.
# Example 7: Interactive program
name = input("What is your name? ")
age = int(input("How old are you? "))
print(f"Hello, {name}! You are {age} years old.")
If the user enters "Charlie" and "20", the output will be:
What is your name? Charlie How old are you? 20 Hello, Charlie! You are 20 years old.
The print()
and input()
functions are fundamental tools for creating interactive Python programs. While print()
helps display output, input()
allows users to provide data to the program. Understanding these functions is essential for Python beginners.