DigitalOcean Referral Badge
Udit Vashisht
Author: Udit Vashisht


Chapter 4 - Print function

Chapter 4 - Print function

  • 5 minutes read
  • 118 Views
Chapter 4 - Print function

    Table of Contents

How to use Python print() function?

In the early days of your python learning, one function that you are going to use the most is the print() function. So, I have decided to add it in the opening chapter of this tutorial. In addition to the print function, you will be learning about commenting out and escape characters too.

As you would have seen in the last chapter, the basic syntax of using print function is:-

print()

Note- In python 2.7 you didn’t need to use the parenthesis but for python 3 and above, you must add parenthesis.

The syntax for the print() function is:-

print(object(s), sep=sep, end=end, file=file, flush=flush)

This could be quite overwhelming for a new-comer, but in the beginning, we will not be using most of the parameters above. But, you must know what each parameter means:-

1. object(s) : Any object(s) be it string, int, list, etc.
2. sep : how to separate the objects, Default='', Optional.
3. end       : what to print at the end, Default='\n' (line end), Optional.
4. file      : object with a write method, Default='sys.stdout', Optional.
5. flush     : Boolean, True for output is flushed, False for buffered, Default ='False', Optional.

Normal usage

For printing out a string, you can use both ‘single quotes’ and “double quotes”.

print('This is printed using single quotes.')
print("This is printed using double quotes.")

The output will be:-

This is printed using single quotes.
This is printed using double quotes.

You can virtually print anything using the print() function, be it a string, int, boolean, list, dictionary, tuple etc. Create a file ‘print_example.py’ and add following lines to it:-

print(8)
print("A string")
print(True)
print(False)
print([1,2,3])
print((1,2,3))
print({'key1': 'data1', 'key2': 'data2' })

On running this file, you will get the following output:-

python print_example.py

SaralGyaan_learn_python_in_hindi_for_absolute_beginners_print_function_in_python_3.png

The print() function can take more than one objects of the same or different kind. You can print a string with an int, a list with a tuple etc. by using a “,” (comma) in between. Each “comma” will add whitespace between the two objects.

print("hello", "world")
print("hello", 5)
print(3, "hello")
print(3, 5)
print([1, 2, 3], 5)
print("hello", "list", "tuple", "[]", "()", 5)

The output will be:-

SaralGyaan_learn_python_in_hindi_for_absolute_beginners_print_function_in_python_3__.png

How to print variables in python?

Till now, we were printing the values directly, but you can also print certain value using its variable name. In that case, you won’t be needing to add quotes to the variable name e.g.:-

a_number = 5
a_string = "A String"

print(a_number)
print(a_string)

The output will be:-
5
A String

Using escape character

The escape character in Python is backslash (\). It comes handy when you have to print a string which has quotes in itself e.g. if you need to print ‘I’ll be there.’ then using the single quotes will throw a syntax error:-

print('I'll be there')

  File "<stdin>", line 1
    print('I'll be there.')
              ^
SyntaxError: invalid syntax

Now you can correct this error in two ways, either by using a different kind of quotes or using the escape character:-

print("I'll be there") 
print('I\'ll be there')

output:-

I'll be there
I'll be there

Multi-line printing

We can also use the print() function to do multi-line printing. The beauty of Python is that few things can be done in multiple ways but always there is one way which is convenient and more pythonic. So, I will quickly go through all the ways of doing it:-

1 Using the New line (‘\n’) special character

multiline_string = "Hi,\nI am a multi-line string.\nThanks!"

print(multiline_string)

output:-

Hi,
I am a multi-line string.
Thanks!

2 Using the separator(sep)

print("Hi,", "I am a multi-line string", "Thanks!", sep="\n")

output:-

Hi,
I am a multi-line string.
Thanks!

3 Using triple quotes- Alternatively, you can do it as under:-

multiline_string = """Hi,
I am a multi-line string.
Thanks!"""

print(multiline_string)

output:-

Hi,
I am a multi-line string.
Thanks!

How to add comments in a Python code?

While coding, some-time we need that interpreter should ignore certain lines of code, or we need to add a comment to our script (There will be a detailed chapter on comments). In python, the same can be done using a pound key (#) at the beginning of the line or using triple quotes (“”“) for multi-line commenting-out:-

# This is a comment
# print("This will not be printed")

print("This will be printed")

"""
This is a multi-line comment
print( "This will not be printed")
print( "This will not be printed")
print( "This will not be printed")
"""
Output:-

This will be printed

**Note:- I strongly recommend using logging for debugging your code. Check out our detailed post on logging.

Table of Contents

Chapter 3 - Executing a Python Script

Chapter 5 - Indentation


Related Posts

Introduction to Python Language - Chapter 1
By Udit Vashisht

Introduction to Python

Curiosity and zeal to learn something new have probably brought you here. It doesn’t matter whether you are new to programming or switching from some other redundant or less useful language, you must be having a few very important questions in your mind. We will be answering ...

Read More
Matplotlib Stack Plots/Bars | Matplotlib Tutorial in Python | Chapter 4
By Udit Vashisht

Matplotlib Tutorial in Python

*Matplotlib Stack Plots/Bars | Chapter 4

In this chapter we will learn to create Matplotlib/Python Stack Plots/Bars.Stack Plots are also called area graphs/plots in general.

Matplotlib Tutorials in Python - Creating a Simple Stack Plot in Matplotlib

A good example of using a stack ...

Read More
How to create a Telegram Bot using Python?
By Udit Vashisht

Create a Telegram Bot using Python

In this article, we will learn to create a simple telegram bot using python. First of all, we will create the API token for our telegram bot.

Connect with FatherBot

We can do this by opening the BotFather bot on telegram. Yes, we ...

Read More
Search
Tags
tech tutorials automate python beautifulsoup web scrapping webscrapping bs4 Strip Python3 programming Pythonanywhere free Online Hosting hindi til github today i learned Windows Installations Installation Learn Python in Hindi Python Tutorials Beginners macos installation guide linux SaralGyaan Saral Gyaan json in python JSON to CSV Convert json to csv python in hindi convert json csv in python remove background python mini projects background removal remove.bg tweepy Django Django tutorials Django for beginners Django Free tutorials Proxy Models User Models AbstractUser UserModel convert json to csv python json to csv python Variables Python cheats Quick tips == and is f string in python f-strings pep-498 formatting in python python f string smtplib python send email with attachment python send email automated emails python python send email gmail automated email sending passwords secrets environment variables if name == main Matplotlib tutorial Matplotlib lists pandas Scatter Plot Time Series Data Live plots Matplotlib Subplots Matplotlib Candlesticks plots Tutorial Logging unittest testing python test Object Oriented Programming Python OOP Database Database Migration Python 3.8 Walrus Operator Data Analysis Pandas Dataframe Pandas Series Dataframe index pandas index python pandas tutorial python pandas python pandas dataframe python f-strings padding how to flatten a nested json nested json to csv json to csv python pandas Pandas Tutorial insert rows pandas pandas append list line charts line plots in python Django proxy user model django custom user model django user model matplotlib marker size pytplot legends scatter plot python pandas python virtual environment virtualenv venv python python venv virtual environment in python python decorators bioinformatics fastafiles Fasta python list append append raspberry pi editor cron crontab Cowin Cowin api python dictionary Python basics dictionary python list list ios development listview navigationview swiftui ios mvvm swift environmentobject property wrapper @State @Environm popup @State ios15 alert automation instagram instaloader texteditor youtubeshorts textfield multi-line star rating reusable swift selenium selenium driver requests-html youtube youtube shorts python automation python tutorial algo trading nifty 50 nifty50 stock list nifty50 telegram telegram bot dictionary in Python how to learn python learn python