


Khusboo Tayal
Input and output (I/O) operations are essential for making interactive Python programs. This guide will explain how to use the built-in input() and print() functions to interact with users and display results.
The input() function is used to get input from the user. It always returns the input as a string, even if the user enters a number.
variable = input("Enter something: ")
name = input("Enter your name: ")
print("Hello, " + name + "!")
Output:
Enter your name: Alice Hello, Alice!
Since input() returns a string, you often need to convert it:
age = input("Enter your age: ")
age = int(age) # Convert string to integer
print("You are", age, "years old.")You can also use float() for decimal numbers and bool() for boolean values.
You can take multiple inputs using split():
x, y = input("Enter two numbers separated by space: ").split()
print("You entered:", x, "and", y)
Or using map() for type conversion:
a, b = map(int, input("Enter two integers: ").split())
print("Sum:", a + b)
The print() function displays text or variable values on the screen.
print(object(s), sep=separator, end=end, file=file, flush=flush)
name = "Alice"
print("Hello", name)Output:
Hello Alice
You can customize the output format using sep and end:
print("Python", "is", "fun", sep="-")
print("Hello", end=" ")
print("World")Output:
Python-is-fun Hello World
Python 3.6+ allows using f-strings for clean formatting:
name = "Khusboo"
age = 24
print(f"My name is {name} and I am {age} years old.")Another way to format output:
language = "Python"
print("I love {} programming.".format(language))By default, print() adds a new line. To print on the same line, change the end parameter:
print("Hello", end=" ")
print("World")
You can redirect output to a file:
with open("output.txt", "w") as f:
print("This will be written to a file.", file=f)Understanding input and output in Python is crucial for building interactive programs. The input() and print() functions are simple yet powerful tools to handle user interaction and display meaningful output.
Q1: Can I use input in Python 2?
Use raw_input() in Python 2 instead of input().
Q2: How to take input as a list?
Use:
numbers = list(map(int, input().split()))
Q3: Can I print multiple variables in one print statement?
Yes:
print("Name:", name, "Age:", age)Subscribe to our newsletter to get the latest Python tutorials, project ideas, and updates right to your inbox.
#python #pythoninput #pythonoutput #inputfunction #printfunction #pythonbeginners #learnpython #pythonbasics #pythonio #pythontutorial