3.1 print() and Formatted Output
The print() function is how a Python program talks to whoever is running it. By default it does two small but important things automatically:
- It adds a newline character (
\n) at the end of whatever you print (so the nextprint()starts on a fresh line — you can override this with theend=parameter). - It separates multiple items with a single space when you pass several to it at once (overridable with
sep=).
# sep and end parameters in action
print("Python", "Java", "C", sep=" | ")
# Output: Python | Java | C
print("Loading", end="...")
print("Done!")
# Output: Loading...Done!
The Power of f-Strings (Formatted String Literals)
For combining text and variables together, Python's cleanest and most modern tool is the f-string — a string literal prefixed with the letter f. Anything inside curly braces { } in an f-string is treated as a live Python expression and evaluated on the spot, which means you can embed not just variable names but full calculations, function calls, and more.
# F-STRINGS IN ACTION
name, age = "Asha", 22
print(f"{name} is {age} years old")
print(f"Next year: {age + 1}") # expressions work inside { } too
💡 Advanced f-String Specifiers for Placement Interviews
f-strings support concise formatting specifiers after a colon (:):
pi = 3.14159265
print(f"{pi:.2f}") # "3.14" (round to 2 decimal places)
salary = 1250000
print(f"{salary:_}") # "1_250_000" (thousands separator)
# Self-documenting expression debugging (Python 3.8+):
x = 42
print(f"{x=}") # "x=42"
3.2 input() for Reading User Data
The input(prompt) function displays the given prompt text, pauses the entire program, and waits until the person at the keyboard types something and presses Enter.
Here is the detail that catches almost every beginner at least once:
Whatever the user types is always returned as a string — even if they type "25", Python hands your program back the three characters "2", "5", not the number 25.
If you need a number, you must explicitly convert it yourself: age = int(input("Enter age: ")). Forgetting this is one of the most common early bugs, because comparing the string "25" to the number 25 with == will silently return False instead of raising an obvious error.
Reading Multiple Inputs on a Single Line
In coding interviews and competitive programming platforms, test cases often supply multiple space-separated numbers on one line. The standard idiom is combining split() with map():
# Reading space-separated integers on a single line:
a, b, c = map(int, input("Enter 3 numbers: ").split())
print(f"Sum = {a + b + c}")
Defensive Input Validation
If a user types non-numeric text like "twenty" when passed to int(), Python raises a ValueError. Production code handles this gracefully with a loop and try-except:
while True:
try:
age = int(input("Please enter your age: "))
break # Valid integer received!
except ValueError:
print("Invalid input! Please enter digits only.")