Topic 7 of 58
Input & Output
Overview
Input and Output (I/O) are the primary ways a program communicates with the user or the terminal. print() writes data to standard output, allowing you to format text with custom separators and endings. input() halts execution, displays a prompt, and waits for the user to type something and press Enter, always returning the user's response as a string.
Syntax
python
# Output formatting
print("Hello", "World", sep="-", end="!!!\n")
# Output: Hello-World!!!
# Input collection
user_name = input("Enter your username: ")
# Input ALWAYS returns a string, so you must cast it for math
raw_age = input("Enter your age: ")
age = int(raw_age)
print(f"Next year, {user_name} will be {age + 1}")Common Pitfalls
- Assuming
input()returns a number if the user types a number. It always returns a string.x = input(); print(x * 2)with input '5' will output '55'. - Using
print()to output highly sensitive data in a production web server, which can accidentally leak secrets into standard log files.
Interview Questions
Q:
How do you prevent the
print() function from adding a newline character at the end of the output?A:
You can override the default end parameter. By default, end='\n', but you can change it to end=' ' or end='' to keep the next print statement on the same line.
Real-World Example
Creating an interactive command-line interface (CLI) menu.
example
python
def run_menu():
while True:
print("\n--- SYSTEM MENU ---")
print("1. View Status")
print("2. Reboot Server")
print("3. Exit")
choice = input("Select an option (1-3): ").strip()
if choice == "3":
print("Shutting down...")
break
elif choice == "1":
print("All systems operational.")
else:
print("Invalid input.")Check Your Knowledge
Test your understanding of Input & Output with these quick questions.