Home Blogs All Courses
python c OA ( Online Assessment ) Amazon Web Services (AWS) leetcode dsa algorithms java Machine learning
Get Referral
Login Sign Up

Python print() Function: Complete Guide with sep, end, f-strings & Examples


The very first line of code almost every programmer writes is print("Hello, World!"). But print() is much more powerful than it looks. It can control spacing, line endings, formatting of numbers, alignment of tables, and can even write directly into files.

In this guide you will go from beginner to pro with the print function — with runnable examples, a "Predict the Output" quiz, practice challenges and a self-check list. Watch the video first, then use this blog as your notes.

How to use this blog: Open the Python shell (type python in your terminal) or any online Python editor and type every example yourself. Change the values and watch how the output changes.

1. What is the print() Function?

print() is a built-in function that displays output on the screen (the console). You don't need to import anything — it is always available.

print("Hello, World!")
# Output: Hello, World!

Think of print() as your program's voice. Without it, your program may calculate the right answer, but it can never tell you.

Python 2 vs Python 3: In Python 2, print was a statement: print "Hello". In Python 3 it is a function, so parentheses are compulsory: print("Hello"). Writing the old style in Python 3 gives a SyntaxError.

2. Complete Syntax of print()

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
ParameterDefaultWhat it does
*objects—Any number of values to print (strings, numbers, lists, variables...)
sep' ' (a space)The separator placed between values
end'\n' (new line)What is printed at the end of the output
filesys.stdoutWhere to send the output (screen, a file, error stream)
flushFalseIf True, forces the output to appear immediately

Let's master each one with examples.

3. Printing Different Types of Values

print("Coding Battle")     # string
print(2026)                # integer
print(3.14)                # float
print(True)                # boolean
print([1, 2, 3])           # list
print({"name": "Riya"})    # dictionary
print(10 + 5)              # expression -> 15

Notice: Python evaluates the expression first, then prints the result. So print(10 + 5) shows 15, not 10 + 5.

print("5" + "5", 5 + 5)    # 55 10
print("Ha" * 3)            # HaHaHa

"5" + "5" joins two strings, while 5 + 5 adds two numbers. Same symbol, different behaviour!

4. Printing Variables and Multiple Values

Separate values with commas. Python automatically puts a space between them and converts numbers to text for you.

name = "Riya"
age = 17

print("Name:", name)
print("Age:", age)
print(name, "is", age, "years old")
# Riya is 17 years old

Common error: Using + to join a string and a number fails: print("Age: " + 17) raises TypeError: can only concatenate str (not "int") to str. Fix it with a comma, str(17), or an f-string.

5. The sep Parameter — Control the Separator

By default, values are separated by a space. Use sep to change it.

print("Python", "is", "fun")              # Python is fun
print("Python", "is", "fun", sep="-")     # Python-is-fun
print("2026", "10", "23", sep="/")        # 2026/10/23
print("a", "b", "c", sep="")              # abc
print(1, 2, 3, sep="\n")                  # each value on a new line
# 1
# 2
# 3

Real-world use: building dates, file paths, CSV lines (sep=",") and email addresses.

print("phool", "codingbattle.in", sep="@")   # phool@codingbattle.in

6. The end Parameter — Control the Line Ending

Every print() adds a new line (\n) at the end by default. That is why each print appears on a new line. Change it with end.

print("Loading", end="...")
print("Done")
# Loading...Done

for i in range(1, 6):
    print(i, end=" ")
# 1 2 3 4 5

Using sep and end together

print("Hello", "World", sep="***", end="!\n")
# Hello***World!

Remember: sep goes between values, end goes after the last value. Both must be passed as keyword arguments.

7. Escape Sequences — Special Characters

A backslash \ gives the next character a special meaning inside a string.

Escape sequenceMeaningExampleOutput
\nNew lineprint("Line1\nLine2")Line1
Line2
\tTab spaceprint("Name\tAge")Name    Age
\\Backslashprint("C:\\Users")C:\Users
\'Single quoteprint('It\'s Python')It's Python
\"Double quoteprint("He said \"Hi\"")He said "Hi"

Raw strings — ignore escape sequences

Prefix the string with r to print backslashes exactly as written. Very useful for Windows paths and regular expressions.

print("C:\new\test")     # \n and \t get converted -> broken path!
print(r"C:\new\test")    # C:\new\test

8. Single, Double and Triple Quotes

print('Single quotes work')
print("Double quotes work too")
print("It's easy to use an apostrophe inside double quotes")
print('She said "Python is awesome"')

print("""This is
a multi-line
message""")

Triple quotes (""" or ''') keep line breaks exactly as you type them — perfect for menus, banners and help text.

9. Formatting Output Like a Pro

Python gives you four ways to mix text and variables. Here they are from oldest to the modern recommended style.

name = "Riya"
age = 17

# 1. Comma (simple, adds spaces automatically)
print(name, "is", age, "years old")

# 2. % formatting (old C-style)
print("%s is %d years old" % (name, age))

# 3. str.format()
print("{} is {} years old".format(name, age))
print("{1} loves {0}".format("Python", "Riya"))   # Riya loves Python

# 4. f-strings (Python 3.6+)  <-- RECOMMENDED
print(f"{name} is {age} years old")

All four print: Riya is 17 years old. Use f-strings — they are the fastest, cleanest and most readable.

f-string formatting superpowers

price = 49.5
qty = 3
print(f"Total: {price * qty:.2f}")   # Total: 148.50   (2 decimal places)
print(f"{10/3:.3f}")                 # 3.333
print(f"{1234567:,}")                # 1,234,567       (thousand separator)
print(f"{0.8567:.1%}")               # 85.7%           (percentage)

name = "Riya"
print(f"{name:>10}|")                # '      Riya|'    (right align)
print(f"{name:<10}|")                # 'Riya      |'    (left align)
print(f"{name:^10}|")                # '   Riya   |'    (center)

x = 42
print(f"{x=}")                       # x=42  (debugging trick, Python 3.8+)
Format specMeaningExample → Output
:.2f2 decimal placesf"{3.14159:.2f}" → 3.14
:,Thousand separatorf"{1234567:,}" → 1,234,567
:.1%Percentagef"{0.8567:.1%}" → 85.7%
:>10Right align in 10 spacesf"{'Hi':>10}"
:<10Left alignf"{'Hi':<10}"
:^10Center alignf"{'Hi':^10}"
=Show variable name and valuef"{x=}" → x=42

10. Hidden Facts About print()

print() with no arguments prints a blank line

print("Line 1")
print()
print("Line 3")

print() returns None

print() only displays a value; it does not give anything back.

result = print("hi")   # prints: hi
print(result)          # None

Unpacking a list with *

nums = [1, 2, 3]
print(nums)              # [1, 2, 3]
print(*nums)             # 1 2 3
print(*nums, sep=", ")   # 1, 2, 3

11. The file Parameter — Print into a File

By default, output goes to the screen (sys.stdout). You can send it to a file instead.

with open("report.txt", "w") as f:
    print("Student Report", file=f)
    print("Name: Riya, Marks: 92", file=f)
# Nothing on the screen - the text is saved inside report.txt

You can also print error messages to the error stream:

import sys
print("Something went wrong!", file=sys.stderr)

12. The flush Parameter — Show Output Immediately

Python sometimes keeps output in a buffer and shows it later. flush=True forces it to appear right away — useful for progress bars and live logs.

import time

print("Downloading", end="", flush=True)
for _ in range(5):
    time.sleep(0.5)
    print(".", end="", flush=True)
print(" Complete!")
# Downloading..... Complete!   (dots appear one by one)

13. Mini Project: Print a Shopping Bill

Let's combine everything — loops, f-strings, alignment and "-" * 25 — to print a neat bill.

items = [("Notebook", 2, 45.0), ("Pen", 5, 10.0), ("Bag", 1, 799.0)]

print(f"{'Item':<10}{'Qty':>5}{'Price':>10}")
print("-" * 25)

total = 0
for item, qty, price in items:
    amount = qty * price
    total += amount
    print(f"{item:<10}{qty:>5}{amount:>10.2f}")

print("-" * 25)
print(f"{'Total':<15}{total:>10.2f}")

Output:

Item        Qty     Price
-------------------------
Notebook      2     90.00
Pen           5     50.00
Bag           1    799.00
-------------------------
Total              939.00

Try it yourself: Add a 5% GST line before the total, and print the final amount with a thousand separator.

14. Common Mistakes and How to Fix Them

MistakeErrorFix
print "Hello"SyntaxErrorprint("Hello")
print("Age: " + 17)TypeErrorprint("Age:", 17) or f"Age: {17}"
Print("Hi")NameErrorPython is case-sensitive — use lowercase print
print("Hi)SyntaxError (unterminated string)Close the quote: print("Hi")
print("a", "b", "-") to join with -Prints a b -Use sep="-"

15. Quiz: Predict the Output

Don't run the code yet! Write your answers in a notebook, then check the Answers section at the end.

Q1.

print("A", "B", "C", sep="")

Q2.

print("Hi", end=" ")
print("there")

Q3.

print(*[1, 2, 3], sep="-")

Q4.

x = print("Python")
print(x)

Q5.

print("5" + "5", 5 + 5)

Q6.

print("Age: " + 17)

Q7.

print(f"{7/2:.2f}", 7 // 2, sep=" | ")

16. Practice Challenges

Solve these from easy to tricky:

  1. Print your name, age and city on one line separated by | . (Hint: sep)
  2. Print numbers 1 to 10 on one line separated by commas — with no comma at the end. (Hint: *range())
  3. Print a right-angled triangle of stars with 5 rows. (Hint: "*" * i)
  4. Print the multiplication table of 7 with perfectly aligned columns. (Hint: :>2)
  5. Print this exact line: She said "Python's path is C:\Users"
  6. Print a countdown from 5 to 1 on the same line, ending with "Go!".

Solutions for challenges 2, 3, 4 and 5 are in the Answers section — try first, peek later!

17. Self-Check: Can You Do This?

Tick off each skill once you are confident:

18. Frequently Asked Interview Questions

Q: Is print a function or a statement in Python 3?
A function. In Python 2 it was a statement.

Q: What are the default values of sep and end?
sep=" " (a space) and end="\n" (a new line).

Q: What does print() return?
None. It only produces output as a side effect.

Q: Which string formatting method is best?
f-strings (Python 3.6+) — they are readable and the fastest.

Q: What is the difference between print() and return?
print() shows a value on the screen; return sends a value back from a function so it can be used later. (See our Python Functions blog for details.)

Q: How do you print without a new line?
Pass end="" (or any other string) to print().

19. Quick Revision Cheat Sheet

TaskCode
Basic printprint("Hello")
Multiple valuesprint(a, b, c)
Custom separatorprint(a, b, sep="-")
No new lineprint(x, end=" ")
Blank lineprint()
New line / tab\n / \t
Raw stringprint(r"C:\new")
f-stringprint(f"Hi {name}")
2 decimalsf"{x:.2f}"
Unpack listprint(*my_list)
Print to fileprint(x, file=f)
Print immediatelyprint(x, flush=True)

Answers

Quiz answers

  1. ABC – the separator is an empty string.
  2. Hi there – the first print ends with a space instead of a new line.
  3. 1-2-3 – * unpacks the list into separate values.
  4. Python on the first line, then None – print returns None.
  5. 55 10 – string joining vs number addition.
  6. TypeError – you cannot join a string and an int with +.
  7. 3.50 | 3 – 7/2 is 3.5 formatted to 2 decimals; 7//2 is floor division.

Challenge solutions

# Challenge 2
print(*range(1, 11), sep=", ")
# 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

# Challenge 3
for i in range(1, 6):
    print("*" * i)
# *
# **
# ***
# ****
# *****

# Challenge 4
for i in range(1, 11):
    print(f"7 x {i:>2} = {7 * i:>2}")
# 7 x  1 =  7
# ...
# 7 x 10 = 70

# Challenge 5
print("She said \"Python's path is C:\\Users\"")

Conclusion

The print() function is your first tool and your best debugging friend. You now know how to print any value, control spacing with sep and end, use escape sequences, format numbers and tables with f-strings, and even write output into files. Next step: solve all the challenges, then continue with Python Loops and Python Functions in this course.

If this blog helped you, watch the full video above, subscribe to the channel and share it with a friend who is learning Python. Happy coding!