Topic 33 of 64
print & input
Overview
print() and input() are the primary tools for console interaction. Knowing their parameters (sep, end, file, flush) and how to handle input type conversion is essential for scripts and interview exercises.
Syntax
python
# print() parameters
print("Hello", "World", sep=", ", end="!
")
# Hello, World!
print("Loading...", end="", flush=True)
# input() always returns a string
name = input("Enter your name: ")
age = int(input("Enter your age: ")) # convert to intCommon Pitfalls
- input() always returns a string — forgetting to convert with int() or float() causes subtle TypeErrors in arithmetic.
- Use try/except ValueError around int(input()) to handle non-numeric user input gracefully.
- Interview tip: In competitive programming contexts, use sys.stdin.readline() for faster input than input().
Real-World Example
Simple interactive CLI calculator
example
python
def calculator():
try:
a = float(input("First number: "))
op = input("Operator (+, -, *, /): ")
b = float(input("Second number: "))
operations = {"+": a + b, "-": a - b, "*": a * b}
if op == "/" and b == 0:
print("Error: division by zero")
else:
result = operations.get(op, "Unknown operator")
print(f"Result: {result}")
except ValueError:
print("Invalid number entered")
calculator()