Python Tutorial › Getting Started › Output & Comments

Python Output & Comments

BeginnerLesson 6 of 4710 min read10 runnable examples

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.

Advertisement
In this lesson
  • 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.

Python
print("Hello, Python")print(42)print(3.5 * 2)print([1, 2, 3])print()                 # an empty lineprint("after the blank line")
Output
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.

Python
name = "Asha"tests = 12print("Tester:", name, "ran", tests, "tests")
Output
Tester: Asha ran 12 tests

Change the separator: sep

sep sets what goes between the values. The default is a single space.

Python
print("2026", "11", "02", sep="-")print("a", "b", "c", sep="")print("login", "search", "checkout", sep=" | ")
Output
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.

Python
for step in range(1, 4):    print("step", step, end=" -> ")print("finished")
Output
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.

Python
item = "keyboard"price = 1499.5qty = 2print(f"{qty} x {item} = {price * qty}")print(f"Price with 2 decimals: {price:.2f}")print(f"{qty=}")
Output
2 x keyboard = 2999.0
Price with 2 decimals: 1499.50
qty=2
Tip

{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:

EscapePrints
\na new line
\ta tab
\\one backslash
\"a double quote inside a double-quoted string
Python
print("Name\tScore")print("Asha\t91")print("Line one\nLine two")print("She said \"hi\"")print("C:\\tests\\report.txt")
Output
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.

Python
with open("log.txt", "w") as log:    print("test started", file=log)    print("test passed", file=log) print(open("log.txt").read())
Output
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.

Python
# 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)
Output
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+/.

Python
# 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])
Output
['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.

Python
def area(width, height):    """Return the area of a rectangle."""    return width * height print(area(3, 4))print(area.__doc__)
Output
12
Return the area of a rectangle.
Note

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")

Quick quiz

1. What is the default value of sep in print()?

2. Which line prints Total: 5 when n = 5?

3. How do you write a comment in Python?

Exercise: print a receipt line

Print one receipt line from these variables, with the price to 2 decimal places and | between the fields.

Input
item = "Mouse", qty = 3, price = 349.5
Expected output
Mouse | 3 | 1048.50
Hint 1

Use an f-string and the format :.2f for the total.

Program Practice

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.

Leave a Comment