GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • C programming
  • C++ programming
  • Java programming
  • Python programming
  • HTML
  • CSS
  • Codenora IDE (opens in a new tab)
  • About us
  • Pricing
  • Contact us
  • Privacy policy
  • Terms of service
  • Refund and Cancellation

This view

  • Original page
  • New address

GeezerVison is showing www.dremendo.com — print() Function and its Use in Python Program | Dremendo

  • Dremendo
  • C
  • C++
  • Java
  • Python
  • HTML
  • CSS
  • More
    • Home
    • C Tutorial
    • C++ Tutorial
    • Java Tutorial
    • Python Tutorial
    • HTML Tutorial
    • CSS Tutorial
?>
profile image
Announcements
No new announcements.
mentora icon
Python Programming Tutorial
  • Python Basic Concepts
    • Introduction
    • Variable
    • Data Types
    • Naming Conventions
    • Typecasting
  • Operators in Python
    • Operators
    • Assignment Operators
    • Arithmetic Operators
    • Relational Operators
    • Logical Operators
    • Identity Operators
    • Membership Operators
    • Operator Precedence
  • Input and Output in Python
    • Environment Setup
    • print() Function
    • input() Function
    • Comments
  • Decision Making in Python
    • Decision Making
    • if Statement
    • if else Statement
    • if elif Statement
  • Mathematical Functions
    • Mathematical Functions
  • Loops in Python
    • Loops
    • for Loop
    • while Loop
  • String in Python
    • String
    • String Methods
  • Built-in Data Structures in Python
    • Lists
    • Tuples
    • Sets
    • Dictionaries
  • Arrays in Python
    • Arrays
  • Searching in Python
    • Linear Search
    • Binary Search
  • Sorting in Python
    • Bubble Sort
    • Selection Sort
    • Insertion Sort
  • Function in Python
    • Function
    • Recursive Function
    • Lambda Function
    • Closures
    • Decorators
    • Generators
  • OOPs in Python
    • Classes and Objects
    • Instance Variables
    • Instance Methods
    • Class Variables
    • Static Methods
    • Inheritance
    • Types of Inheritance
    • MRO
    • Polymorphism
    • Abstract Classes
  • User-Defined Data Structures in Python
    • Stack
    • Queue
    • Circular Queue
    • Double Ended Queue
    • Singly Linked List
    • Doubly Linked List
    • Stack using Linked List
    • Queue using Linked List
  • Modules in Python
    • Modules
    • Time Module
    • Datetime Module
    • OS Module
    • Shutil Module
    • Sys Module
    • JSON Module
    • Random Module
  • Regular Expression in Python
    • Regular Expression
  • Exceptions in Python
    • Exception Handling
  • File Handling in Python
    • Text File Handling
    • Binary File Handling
    • CSV File Handling

bookmark
Table of Contents

    print() Function and its Use in Python Program

    In this lesson, we will understand what print() function is and how it works in Python programming with the help of some examples.

    What is print() Function

    The print() function in Python is used to output data to the standard output device, which is typically the console or terminal. It is one of the most commonly used functions for debugging and displaying information.

    Note

    In simple terms, a console is a screen or interface where you can see messages and type commands to interact with a computer.

    Video Explanation

    Click the button below to watch the explanation.

    Please wait while the video is loading....
    video image

    Let’s explore various examples to understand how the print() function works in Python.

    Example 1

    Python program to print the text Welcome to Dremendo on the screen.

    print('Welcome to Dremendo')
    print("Welcome to Dremendo")
    Output
    Welcome to Dremendo
    Welcome to Dremendo

    Here, we printed the text Welcome to Dremendo on the screen using the print() function. Whatever we place inside the parentheses (brackets) of the print() function will be displayed on the screen.

    You can use either single quotes or double quotes to print text using the print() function, as shown in the example above.

    Example 2

    Python program to print multiple items on the screen.

    print("Python", 3.9, 2024)
    Output
    Python 3.9 2024
    Example 3

    Python program to print Sunday and Monday on separate lines on the screen.

    print("Sunday")
    print("Monday")
    Output
    Sunday
    Monday

    You can see that we used the print() function twice to print Sunday and Monday on separate lines on the screen.

    Example 4

    Python program to print Sunday and Monday on separate lines using a single print() function.

    print('Sunday\nMonday')
    Output
    Sunday
    Monday

    You can see that we used a single print() function to print Sunday and Monday on separate lines. We included \n (the escape sequence for a new line) right after Sunday, so that after printing Sunday, the line breaks and Monday is printed on the next line.

    Note

    The \n character is used to break a line and move the cursor to the beginning of the next line.

    You can use multiple \n characters to break additional lines, as shown in the example below.

    Example 5
    print('\n\nSunday\n\n\nMonday')
    Output
    
    Sunday
    
    
    Monday

    In the example above, the line breaks twice before Sunday is printed on the screen. After that, the line breaks twice again, and then Monday is printed.

    Use of sep Parameter in print() Function

    The sep parameter in Python is commonly used in functions like print(), and it specifies the string that will be inserted between multiple arguments being printed.

    The sep parameter is used to format the output on the screen and it is available in Python from version 3.x or later.

    Note

    By default, the sep parameter is set to a space (' '), meaning if we print multiple items, they will be separated by a space.

    Example

    Python program to show the use of sep parameter in print() function.

    print("Sunday", "Monday", "Tuesday", sep=", ")       # Using a comma as a separator
    print("18", "06", "2020", sep="-")      # Using a dash as a separator
    print(1, 2, 3, 4, 5, sep=" | ")     # Using | separator with numbers
    print("Hello", "World", sep="")     # Using no separator
    Output
    Sunday, Monday, Tuesday
    18-06-2020
    1 | 2 | 3 | 4 | 5
    HelloWorld

    Use of end Parameter in print() Function

    The end parameter in Python is commonly used in functions like print(), and it specifies the string that will be printed at the end of the output. This parameter helps control the formatting of the output, allowing us to print items on the same line or follow a specific format.

    Note

    By default, end is set to '\n', which means that after the printed output, the cursor moves to the next line.

    Example: Default Behavior

    Python program to show the default behaviour of end parameter in print() function.

    print("Hello")
    print("World")
    Output
    Hello
    World
    Example: Changing the end Parameter

    We can change the end parameter to any string we prefer. Here are some examples to illustrate its use:

    print("Sunday", "Monday", end=" ")       # Using a Space
    
    print("\nLoading", end='... ')        # Using a Custom String
    print("Please wait.")
    
    print("Hello", end="")      # Using an Empty String
    print(" I am Learning", end="")
    print(" Python")
    Output
    Sunday Monday
    Loading... Please wait.
    Hello I am Learning Python
    Example: Use of sep and end parameters together in print() function

    Python program to show the use of end and sep parameters together in print() function.

    print("thomas", "wilson", sep="", end="@")
    print('dremendo.com')
    Output
    [email protected]

    You can see that we have used sep='' so thomas and wilson will be printed together without any space between them because the sep is blank. At the end of the line we have used end='@' as a result dremendo.com will be printed on the first line after @ character as shown in the output screen.

    Print Variable's Value using print() Function

    In Python, we can easily print the value of a variable using the print() function. This is often used for debugging or displaying values during program execution. To print the value of a variable, simply pass the variable as an argument to the print() function.

    Example

    Python program to print string, integer and a float data type values on the screen.

    name = "Alice"
    age = 30
    percentage = 86.32
    print(name)
    print(age)
    print(percentage)
    Output
    Alice
    30
    86.32

    We can print multiple variables at once by separating them with commas.

    Example

    Python program to print multiple variables on the screen.

    name = "Alice"
    age = 30
    city = "New York"
    
    print(name, age, city)
    Output
    Alice 30 New York

    We can use the sep parameter to customize the output.

    Example

    Python program to print multiple variables on the screen with a custom message.

    a = 10
    b = 20
    c = a + b
    
    print("Addition of ", a, " and ", b, " = ", c, sep="")
    
    print("a=", a, sep="")
    print("b=", b, sep="")
    print("c=", c, sep="")
    Output
    Addition of 10 and 20 = 30
    a=10
    b=20
    c=30

    Print Formatted String using % Operator

    The % operator in Python allows us to create formatted strings, meaning we can insert variables or expressions into specific placeholders within a string. This is called printf-style formatting, and it works similarly to the printf() function in C.

    Video Explanation

    Click the button below to watch the explanation.

    Please wait while the video is loading....
    video image
    Note

    The % operator is an older way to format strings in Python, but it’s still useful to learn because:

    • Many older Python programs and textbooks use it.
    • It’s similar to formatting in the C language (printf).
    • It helps you understand how modern formatting (like f-strings) evolved.

    Below are the list of symbols used with % operator for formatting outputs on the screen.

    Formatting Symbols Description
    %d Used for integer printing
    %f Used for decimal number (float) printing
    %c Used for character printing
    %s Used for string (text) printing
    %o Used for octal number printing
    %x Used for lowercase hexadecimal number printing
    %X Used for uppercase hexadecimal number printing
    Example
    name = "Alice"
    age = 30
    
    print("My name is %s and I am %d years old" % (name, age))
    Output
    My name is Alice and I am 30 years old

    In the program above, we use format specifiers like %s (for string) and %d (for integer) as placeholders in the string. The values inside the parentheses (name, age) replace the placeholders in the same order.

    We can control how many decimal places a floating-point number shows using .nf — where n is the number of digits after the decimal point.

    Example: Formatting a Float to 2 Decimal Places
    pi = 3.141592653589793
    
    print("Value of Pi = %.2f" % pi)
    Output
    Value of Pi = 3.14

    Here, .2f means to format the float with 2 decimal places.

    We can also format text alignment and width using % with width specifiers.

    Example: Padding and Alignment
    name = "Bob"
    print("|%-10s|%s|%10s|" % (name, name.center(20), name))
    Output
    |Bob       |        Bob         |       Bob|

    Here, %-10s means left-align the text and make it 10 characters wide, %s and name.center(20) means center-align the text and make it 20 characters wide, and %10s means right-align the text and make it 10 characters wide.

    Print Formatted String using format() Function

    The format() function in Python allows us to create formatted strings, which means we can insert variables or expressions into specific placeholders within a string. This method provides a flexible and readable way to format strings.

    Example
    name = "Alice"
    age = 30
    
    print("My name is {} and I am {} years old".format(name, age))
    Output
    My name is Alice and I am 30 years old

    In the program above, we use curly braces {} as empty spots in the string, and then we pass the values we want to insert into the format() function. These values will fill in the empty spots in the order we provide them in the format() function.

    We can control the order of the substitutions by using positional arguments in the placeholders:

    Example: Using Positional Arguments
    name = "Alice"
    age = 30
    
    print("Name: {1}, Age: {0}".format(age, name))
    Output
    Name: Alice, Age: 30

    In this case, {1} refers to the second argument (name), and {0} refers to the first argument (age).

    We can control how many decimal places a floating-point number shows using format() function.

    Example: Formatting a Float to 2 Decimal Places
    pi = 3.141592653589793
    
    print("Value of Pi = {:.2f}".format(pi))
    Output
    Value of Pi = 3.14

    Here, {:.2f} means to format the float with 2 decimal places.

    Using format() function we can format numbers with commas as thousands separators:

    Example: Formatting with Thousands Separator
    large_number = 1000000
    
    print("The number is: {:,}".format(large_number))
    Output
    The number is: 1,000,000

    We can also use format() function to specify padding and alignment of text and numbers.

    Left-align (<), center-align (^) and right-align (>).

    Example: Padding and Alignment
    name = "Bob"
    print("|{:<10}|{:^20}|{:>10}|".format(name, name, name))
    Output
    |Bob       |        Bob         |       Bob|

    Here, :<10 means left-align the text and make it 10 characters wide, :^20 means center-align the text and make it 20 characters wide, and :>10 means right-align the text and make it 10 characters wide.

    Print Formatted String using f-string

    The f-strings (formatted string literals) were introduced in Python 3.6 to make string formatting simpler, more readable, and faster. To use an f-string, prefix the string with f or F and place variables or expressions inside curly braces {}.

    Example
    name = "Alice"
    age = 30
    
    print(f"My name is {name} and I am {age} years old")
    Output
    My name is Alice and I am 30 years old
    Example: Formatting a Float to 2 Decimal Places
    pi = 3.141592653589793
    
    print(f"Value of Pi = {pi:.2f}")
    Output
    Value of Pi = 3.14
    Example: Formatting with Thousands Separator
    large_number = 1000000
    
    print(f"The number is: {large_number:,}")
    Output
    The number is: 1,000,000
    Example: Padding and Alignment
    name = "Bob"
    print(f"|{name:<10}|{name:^20}|{name:>10}|")
    Output
    |Bob       |        Bob         |       Bob|

    Print the Data Type of Variables using type() Function

    In Python, the type() function is used to determine the data type of a variable. We can use it to check the type of any object, such as integers, strings, lists, dictionaries, etc.

    Video Explanation

    Click the button below to watch the explanation.

    Please wait while the video is loading....
    video image
    Example: Use of type() function

    Python program to show the use of type() function.

    # Defining variables of different types
    name = "Alice"         # String
    age = 30               # Integer
    height = 5.7           # Float
    is_student = True      # Boolean
    hobbies = ["reading", "sports"]  # List
    person = {"name": "Alice", "age": 30}  # Dictionary
    
    # Printing the data types
    print("Data type of 'name':", type(name))
    print("Data type of 'age':", type(age))
    print("Data type of 'height':", type(height))
    print("Data type of 'is_student':", type(is_student))
    print("Data type of 'hobbies':", type(hobbies))
    print("Data type of 'person':", type(person))
    Output
    Data type of 'name': <class 'str'>
    Data type of 'age': <class 'int'>
    Data type of 'height': <class 'float'>
    Data type of 'is_student': <class 'bool'>
    Data type of 'hobbies': <class 'list'>
    Data type of 'person': <class 'dict'>

    Escape Sequence Character in Python

    Escape sequence characters are those that does not represent itself when used inside a character constant or string literal, but is translated into another character or a sequence of characters that may be difficult or impossible to represent directly.

    In Python, all escape sequences characters start with a backslash (\) followed by one or more characters that determine the interpretation of the escape sequence.

    Common Escape Sequences

    Here are some of the most common escape sequences in Python:

    Escape Sequence Meaning Description
    \n Newline Move the cursor to the next line.
    \t Horizontal tab Insert a horizontal tab space.
    \\ Backslash Insert a single backslash.
    \" Double quote Insert a double quote.
    \' Single quote Insert a single quote.
    \b Backspace Delete or overwrite the previous character by moving the cursor back one position.
    \r Carriage Return Moves the cursor to the beginning of the line. It may overwrite the text that was there before.
    Example
    print("Hello World\n");  # Newline
    print("Hello\tWorld");  # Horizontal tab
    print("\\");  # Backslash
    print("\"Hello\"");  # Double quote
    print("\'Hello\'");  # Single quote
    print("Hell\bo World\b");  # Backspace
    print("Carriage return \rHello");  # Carriage return
    Output
    Hello World
    
    Hello	World
    \
    "Hello"
    'Hello'
    Helo World
    Helloage return
    Note

    On Windows terminal, the \b escape sequence moves the cursor back one space but does not delete the character. Any characters printed after the backspace overwrite previously written characters.

    Test Your Knowledge

    Attempt the questions in the exercise to check whether you have understood the lesson clearly.

    Exercise
    Test Your Knowledge
    Previous Next

    We care about your privacy

    Dremendo uses cookies and similar technologies that are necessary for the site to work properly, understand how you interact with our website, and measure the effectiveness of our marketing. By clicking Accept All, you consent to the use of non-essential cookies and similar technologies for analytics, advertising, and ad measurement, as described in our Privacy Policy.

    Cookie Preferences

    Choose which types of cookies Dremendo may use.

    Necessary Cookies

    Required for essential website functionality and security.

    Allow
    Analytics Cookies

    Help us understand how visitors use Dremendo.

    Allow
    Marketing Cookies

    Help us measure advertising performance and understand interactions with our advertisements.

    Allow
    Mentora Question Asked: 0 / 20

    Hi, I’m Mentora!

    I’m your personal AI tutor from Dremendo. Ask me anything, and I’ll help you understand it in a simple and easy way.

    You are visitor 01402503 — GeezerVison does not store the pages you look up.
    Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.