Input And Output In Python
Python Input and Output (I/O)
Python provides simple and powerful functions to interact with the user and external files. Input allows a program to receive data, while output displays or stores the results.
Output using print()
The print() function is used to display information on the screen.
print("Welcome to TRC Tutorials")
Printing variables
name = "Student"
print("Hello", name)
Using f-strings (formatted strings)
print(f"Hello, {name}!")
Common print() Parameters
The print() function has optional parameters to control formatting.
sep: separator between values
print("Python", "is", "fun", sep="-") # Output: Python-is-fun
end: what to print at the end
print("Hello", end=" ")
print("World") # Output: Hello World
Input using input()
The input() function pauses the program and waits for the user to type something. It always returns the value as a string.
user_name = input("Enter your name: ")
print("Hello " + user_name)
Converting Input to Other Data Types
Since input is always a string, you often need to convert it.
Convert to integer
age = int(input("Enter your age: "))
print(f"You will be {age + 1} next year.")
Convert to float
price = float(input("Enter the price: "))
print("Price with tax:", price * 1.18)
Taking Multiple Inputs
You can take multiple values in a single line using split().
Input: 10 20
a, b = input("Enter two numbers: ").split()
print(a, b)
Converting to integers
x, y = map(int, input("Enter two numbers: ").split())
print(x + y)
Taking a List as Input
You can store multiple inputs as a list.
Input: 1 2 3 4 5
numbers = list(map(int, input("Enter numbers: ").split()))
print(numbers)
Formatted Output
Python provides different ways to format output.
name = "Alice"
score = 95
Using f-strings (recommended)
print(f"{name} scored {score} marks.")
Using format() method
print("{} scored {} marks.".format(name, score))
Controlling Decimal Places
You can control the number of decimal places in output.
pi = 3.14159
print(f"{pi:.2f}") # Output: 3.14