Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • šŸ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • šŸ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • šŸ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • šŸ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • šŸ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • šŸ“ For Each Assignments
    • šŸ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • šŸ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • šŸ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • šŸ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • šŸ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • šŸ“ Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • šŸ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • šŸ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • šŸ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • šŸ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • šŸ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • šŸ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • šŸ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • šŸ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • šŸ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • šŸ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • šŸ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • šŸ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • šŸ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • šŸ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

šŸ“¤ Python print() Function: Complete Guide

Python print() Function - Output Formatting

The print() function is your program's voice — it's how your code talks to the user.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
šŸ“‘ On this page:
  • What is Output in Python?
  • Syntax of print()
  • Basic print() Usage
  • The sep Parameter
  • The end Parameter
  • The file Parameter
  • Output Formatting
  • String Modulo Operator (%)
  • The format() Method
  • f-strings (Formatted Strings)
  • Best Practices
  • Try It Yourself
  • Quick Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
šŸ“š What You'll Learn Here
  • What output is — how programs display information to users
  • The print() function — syntax and parameters
  • Understanding sep and end — controlling separators and line endings
  • Output formatting — making output look professional
  • f-strings — modern string formatting
  • Best practices — writing clean, readable output
  • Hands-on practice with the interactive editor

What is Output in Python?

Output is the information your program displays to the user. It's the result of all your hard work — the answer, the report, the message that tells the user what happened. In Python, the print() function is the primary way to produce output.

Think of print() as your program's voice. Just as you use your voice to communicate with others, your program uses print() to communicate with the user. Without it, your program would be silent — it would do its work, but you'd never know what it accomplished.

šŸ’” Why output matters: Output is how your program answers questions, reports results, and tells the user what's happening. It's the difference between a program that works silently and one that keeps you informed every step of the way.

The print() function takes any number of arguments — text, numbers, variables — and displays them on the screen. It's flexible, powerful, and one of the first functions you'll learn as a Python programmer.

Syntax of print()

# Complete Syntax
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

# Simple Usage
print("Hello, World!")

šŸ“– Breaking it down: The print() function accepts multiple arguments. *objects means you can pass any number of items to print. sep controls what goes between items (space by default). end controls what goes at the end (newline by default). file lets you print to a file instead of the screen, and flush forces the output to be written immediately.

1. Basic print() Usage

At its simplest, print() displays text. You can pass strings, numbers, variables — even expressions — and Python will display them all.

# Basic print() Examples
print("Hello, World!")
print(42)
print(3.14159)
print(10 + 5)

# Multiple arguments
print("The answer is", 42)

# Output:
# Hello, World!
# 42
# 3.14159
# 15
# The answer is 42

šŸ’” Important: When you pass multiple arguments, print() automatically adds a space between them. This is the default behavior, but you can change it using the sep parameter.

2. The sep Parameter

By default, print() places a space between multiple items. But what if you want something else? A comma, a dash, or even nothing at all? That's where the sep parameter comes in.

The sep parameter lets you define exactly what goes between your items. It's a small change that can make a big difference in how your output looks.

# The sep Parameter
print(10, 11, 12)                 # Default: space between
print(10, 11, 12, sep='*')        # Asterisk between
print(10, 11, 12, sep='-')        # Dash between
print(10, 11, 12, sep='')         # No separator

# Output:
# 10 11 12
# 10*11*12
# 10-11-12
# 101112

šŸ’” Real-world use: sep is perfect for formatting output like CSV files, log entries, or any situation where you need a specific separator between values.

3. The end Parameter

When you use print(), it automatically adds a newline at the end. That's why each print() appears on its own line. But sometimes you want something different — maybe a space, a comma, or nothing at all.

The end parameter controls what gets printed at the end of your output. By default, it's \n (newline), but you can change it to anything you want.

# The end Parameter
print(11, 12, sep='#', end='%')
print(13, 14, sep='#')

# Output:
# 11#12%13#14

# Printing without newline
print("Hello", end=" ")
print("World!")

# Output:
# Hello World!

šŸ’” Why this matters: The end parameter is essential for creating progress bars, building strings incrementally, or any situation where you want to control how your output lines are structured.

4. The file Parameter

Normally, print() sends output to the screen. But what if you want to send it to a file instead? The file parameter lets you redirect output to any object that has a write() method.

# The file Parameter
import sys

# Print to screen (default)
print("Hello, World!")

# Print to standard error
print("Error: Something went wrong!", file=sys.stderr)

# Print to a file
with open("output.txt", "w") as f:
    print("This goes to the file", file=f)

šŸ’” Real-world use: The file parameter is used for logging, writing reports, and any situation where you need to save output rather than just display it.

5. Output Formatting

Sometimes, basic output isn't enough. You want your output to look professional — clean columns, aligned numbers, consistent formatting. Python offers several ways to achieve this.

Output formatting is about making your program's output more readable and visually appealing. It's the difference between a raw data dump and a polished report.

5.1 String Modulo Operator (%)

The string modulo operator % is one of the oldest ways to format strings in Python. It's still widely used and supported.

# String Modulo Operator (%)
print("Empno: %2d, Avg Rating: %5.2f" % (1, 6.433))
print("Total Employees: %3d, Managers: %2d" % (2400, 100))
print("%7.3o" % (25))    # Octal
print("%10.3E" % (356.08977))  # Exponential

# Output:
# Empno:  1, Avg Rating:  6.43
# Total Employees: 2400, Managers: 100
#     031
# 3.561E+02

5.2 The format() Method

The format() method is a more powerful and flexible way to format strings. It uses curly braces {} as placeholders and lets you control exactly how values are inserted.

# format() Method
print('I love {} for "{}!"'.format('Python', 'Programming'))

# Positional arguments
print('{0} and {1}'.format('Python', 'Programming'))
print('{1} and {0}'.format('Python', 'Programming'))

# Keyword arguments
print('Hey! Welcome to {code}. Learn about {language}'.format(
    code='Coding', language='Python'
))

# Output:
# I love Python for "Programming!"
# Python and Programming
# Programming and Python
# Hey! Welcome to Coding. Learn about Python
# format() with variables
x = 30
y = 21
mul = x * y

print('The value of x is {} and y is {}'.format(x, y))
print('{2} is the multiplication of {0} and {1}'.format(x, y, mul))

# Output:
# The value of x is 30 and y is 21
# 630 is the multiplication of 30 and 21

5.3 f-strings (Formatted Strings)

f-strings, introduced in Python 3.6, are the most modern and recommended way to format strings. They're concise, readable, and fast.

# f-strings (Formatted Strings)
name = "Python"
version = 3.12
year = 2024

print(f"Language: {name}, Version: {version}, Year: {year}")

# With expressions
radius = 5
print(f"Area of circle: {3.14 * radius * radius:.2f}")

# With variables
x = 30
y = 21
mul = x * y
print(f"The product of {x} and {y} is {mul}")

# Output:
# Language: Python, Version: 3.12, Year: 2024
# Area of circle: 78.50
# The product of 30 and 21 is 630

šŸ’” Why f-strings are best: They're the most readable, the most efficient, and the most modern way to format strings. If you're using Python 3.6 or later, f-strings should be your first choice for string formatting.

6. Best Practices for print()

āœ… Use f-strings for Clean Formatting

f-strings are the most readable and efficient way to format strings. They let you embed expressions directly in your strings, making your code cleaner and easier to understand.

# GOOD: f-strings
name = "Alice"
score = 95
print(f"Student: {name}, Score: {score}")

# BAD: Manual concatenation
print("Student: " + name + ", Score: " + str(score))

āœ… Use sep and end for Clean Layout

The sep and end parameters give you fine control over output formatting. Use them to create clean, professional-looking output.

# Print items as CSV
print("Name", "Age", "City", sep=",")

# Print progress without newline
for i in range(5):
    print(i, end=" ")
print()  # Final newline

Try It Yourself!

Experiment with the print() function directly in your browser. Modify the code and see the results in real time.

Loading Pyodide... 0%
Python Code Editor
========================================
PRINT() FUNCTION
========================================

1. BASIC PRINT
Hello, World!
42
3.14159

2. MULTIPLE ARGUMENTS
The answer is 42

3. SEP PARAMETER
10 11 12
10*11*12
101112

4. END PARAMETER
11#12%13#14

5. F-STRINGS
Language: Python, Version: 3.12

6. NUMBER FORMATTING
Pi rounded: 3.14

āœ… Explore different print() features!
šŸ†

šŸŽ‰ You've Mastered Python print()!

You understand the print() function, its parameters, and how to format output professionally. These are essential skills for interactive Python programs!

Quick Quiz – Test Your Knowledge

1. What is the default separator between items in print()?
2. What does the end parameter do in print()?
3. Which is the modern recommended way to format strings in Python?

Frequently Asked Questions

šŸ¤” What's the difference between print() and return? ā–¼

print() displays output to the console. return sends a value back from a function. print() is for user communication; return is for function communication.

šŸ”§ How do I prevent print() from adding a new line? ā–¼

Use the end parameter: print("Hello", end="") or print("Hello", end=" ") to add a space instead of a newline.

šŸ“ Can I print multiple lines with one print()? ā–¼

Yes! Use \n for newlines: print("Line 1\nLine 2\nLine 3"). You can also use triple quotes for multi-line strings.

šŸ“Š What's the difference between sep and end? ā–¼

sep controls what goes between the items you print. end controls what goes at the very end of the output. They serve different purposes and can be used together.

⚔ How do I print to a file instead of the console? ā–¼

Use the file parameter: print("Hello", file=open("output.txt", "w")). Or better, use a with statement to ensure the file is properly closed.

šŸŽÆ What is the flush parameter used for? ā–¼

The flush parameter forces the output to be written immediately. This is useful in real-time applications like progress bars, log monitoring, and interactive programs where you want to see output immediately.

šŸ“š Where to Go From Here

Now that you've mastered the print() function, here are some related topics that will take your Python skills further:

āŒØļø Accepting User Input

You've learned how to speak — now learn how to listen! The input() function lets your programs accept data from users.

Learn Input →

šŸ“ I/O Assignments

Practice what you've learned with real-world coding challenges that combine input and output.

Start Practicing →

šŸš€ Simple Python Scripts

Combine input and output to build practical, real-world programs that solve actual problems.

Build Scripts →
šŸ“– Related Tutorials
  • āŒØļø Accepting User Input — Learn how to make your programs interactive
  • šŸ“ I/O Assignments — Practice with real coding challenges
  • šŸš€ Simple Python Scripts — Build practical programs
  • šŸ“‹ Variables and Identifiers — Strengthen your foundation
šŸ“– Interview & FAQ Resources
  • Python Syntax & Variables Interview Questions
  • SQL - Displaying Data from Multiple Tables FAQ
  • SQL Window Functions & Analytic Functions FAQ
  • Python Data Types Interview Questions
  • Python Tuples and Sets Interview Questions
  • Java Basic Input/Output Interview Questions
  • Java Advanced Threads and Concurrency Interview Questions
Previous: Accept Input Next: I/O Assignments →