Python Output & Comments
print() is how your program talks to you, and comments are how you talk to the next person who reads your code. Both look simple, but a few options make them far more useful.
- Print several values at once
- Control separators with sep and end
- Print variables neatly with f-strings
- Write comments and docstrings that help
The print() function
print() writes text to the screen and then moves to a new line. You can give it any value: text, numbers, lists or the result of a calculation.
print("Hello, Python")print(42)print(3.5 * 2)print([1, 2, 3])print() # an empty lineprint("after the blank line")Hello, Python 42 7.0 [1, 2, 3] after the blank line
Print several values
Separate values with commas. print() converts each one to text and puts a space between them, so you can mix text and numbers without converting anything.
name = "Asha"tests = 12print("Tester:", name, "ran", tests, "tests")Tester: Asha ran 12 tests
Change the separator: sep
sep sets what goes between the values. The default is a single space.
print("2026", "11", "02", sep="-")print("a", "b", "c", sep="")print("login", "search", "checkout", sep=" | ")2026-11-02 abc login | search | checkout
Change the line ending: end
end sets what is printed after the last value. The default is a newline ("\n"), so each print() starts a new line. Change it to keep printing on the same line.
for step in range(1, 4): print("step", step, end=" -> ")print("finished")step 1 -> step 2 -> step 3 -> finished
Print variables with f-strings
An f-string starts with f before the quote. Anything in { } is replaced by its value. This is the clearest way to build output.
item = "keyboard"price = 1499.5qty = 2print(f"{qty} x {item} = {price * qty}")print(f"Price with 2 decimals: {price:.2f}")print(f"{qty=}")2 x keyboard = 2999.0 Price with 2 decimals: 1499.50 qty=2
{qty=} prints both the name and the value, which is handy while debugging. The String Formatting lesson covers alignment, padding and number formats.
Escape characters
A backslash inside a string starts an escape sequence:
| Escape | Prints |
|---|---|
\n | a new line |
\t | a tab |
\\ | one backslash |
\" | a double quote inside a double-quoted string |
print("Name\tScore")print("Asha\t91")print("Line one\nLine two")print("She said \"hi\"")print("C:\\tests\\report.txt")Name Score Asha 91 Line one Line two She said "hi" C:\tests\report.txt
Print to a file
print() can write to a file instead of the screen with the file argument. The File Handling lesson explains open() in detail.
with open("log.txt", "w") as log: print("test started", file=log) print("test passed", file=log) print(open("log.txt").read())test started test passed
Comments
A comment starts with #. Python ignores everything from # to the end of the line. Use comments to explain why the code does something, not what it obviously does.
# Prices are stored in paise to avoid rounding errors with floatsprice_paise = 149950 discount = 0.10 # 10% festival discount, ends 15 Novfinal = price_paise * (1 - discount)print(final / 100)1349.55
Multi-line comments
Python has no special multi-line comment. Put # at the start of each line. Most editors do this for a selection with Ctrl+/.
# Step 1: read the users file# Step 2: keep only active users# Step 3: print their namesusers = [("asha", True), ("ravi", False), ("meena", True)]print([name for name, active in users if active])['asha', 'meena']
Docstrings
A string written as the first line of a function, class or module is a docstring. Unlike a comment, Python keeps it, and help() shows it.
def area(width, height): """Return the area of a rectangle.""" return width * height print(area(3, 4))print(area.__doc__)12 Return the area of a rectangle.
A triple-quoted string on its own in the middle of code is not a comment. Python creates the string and throws it away. It works, but # is the correct tool for comments.
Check your understanding
Predict the output
print("a", "b", sep="*", end="!")print("c")a*b!c
sep="*" joins a and b, and end="!" replaces the newline, so the next print continues on the same line.
Quick quiz
1. What is the default value of sep in print()?
Values are separated by one space unless you pass sep.
2. Which line prints Total: 5 when n = 5?
Only an f-string fills in {n}. Adding a string and an int raises TypeError.
3. How do you write a comment in Python?
# starts a comment that runs to the end of the line.
Exercise: print a receipt line
Print one receipt line from these variables, with the price to 2 decimal places and | between the fields.
item = "Mouse", qty = 3, price = 349.5
Mouse | 3 | 1048.50
Hint 1
Use an f-string and the format :.2f for the total.
item = "Mouse"qty = 3price = 349.5print(item, qty, f"{qty * price:.2f}", sep=" | ")Mouse | 3 | 1048.50
sep=" | " puts the bar between the three values. The f-string multiplies quantity by price and formats the result with exactly two decimals.
Program Practice
40 Python Basic Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
Python print and comments FAQ
How do I print without a newline in Python?
Pass end="" (or any other text) to print(), for example print("Loading", end="").
How do I print a variable with text?
Use an f-string, for example print(f"Total: {total}"), or pass several values: print("Total:", total).
How do I write a multi-line comment in Python?
Start each line with #. Triple-quoted strings are for docstrings, not comments.
What is the difference between a comment and a docstring?
Python ignores comments completely. A docstring is a real string stored on the function, class or module, and tools such as help() and IDEs display it.