In Python, Input/Output (I/O) refers to how a program receives data from the user and displays results back to the screen. The two primary built-in functions for this are input() and print().
input() FunctionThe input() function is used to receive data from the user via the keyboard.
variable = input(prompt)
prompt — an optional string displayed to the user before they type.name = input("Enter your name: ")
print("Hello,", name)
Important: Even if the user types a number, input() returns it as a string.
Since input() always returns a string, you must convert (cast) it to the appropriate data type before performing calculations.
| Function | Converts To | Example |
|---|---|---|
int() | Integer | age = int(input("Enter age: ")) |
float() | Decimal | price = float(input("Enter price: ")) |
str() | String | s = str(input("Enter text: ")) |
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("Sum =", num1 + num2)
print() FunctionThe print() function is used to display output on the screen.
print(object1, object2, ..., sep=' ', end='\n')
print("Hello, World!") # Output: Hello, World!
print("Age:", 17) # Output: Age: 17
print(10 + 5) # Output: 15
print()sep ParameterSpecifies the separator between multiple objects. Default is a single space ' '.
print("Python", "is", "fun", sep="-")
# Output: Python-is-fun
print(1, 2, 3, sep=", ")
# Output: 1, 2, 3
end ParameterSpecifies what is printed at the end of the output. Default is a newline '\n'.
print("Hello", end=" ")
print("World")
# Output: Hello World (on the same line)
Escape sequences are special characters that begin with a backslash (\) and are used to format output.
| Escape Sequence | Meaning | Example Output |
|---|---|---|
\n | New line | Moves to next line |
\t | Horizontal tab | Adds a tab space |
\\ | Backslash | Prints \ |
\' | Single quote | Prints ' |
\" | Double quote | Prints " |
print("Name:\tAli")
# Output: Name: Ali
print("Line 1\nLine 2")
# Output:
# Line 1
# Line 2
print()You can combine variables and strings in output using:
name = "Sara"
age = 16
print("Name:", name, "Age:", age)
# Output: Name: Sara Age: 16
name = "Sara"
age = 16
print(f"Name: {name}, Age: {age}")
# Output: Name: Sara, Age: 16
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}")
Sample Run:
Enter first number: 5.5
Enter second number: 4.5
The sum of 5.5 and 4.5 is 10.0