Python print() function tutorial
In Python, the print function is a powerfully useful tool if you know how to utilize it. The
print() function is used to have statements written into the terminal of a program.
However, do you know how many different ways there are to use the
There is so much you can do with this function that it is almost scary! It’s easy to overlook such a simple function within such a powerful language, but Python’s flexibility allows you to use simple functions, powerfully.
I want to discuss some of the features you can learn with Python
print() function including how to print multiple lines, print to a file and a logger, print in color font and backgrounds, in non-English languages, and more.
Let’s go over how it works, and give you some code you should practice on your own so you too can implement these practices on your own. In this article, I am going to be using Python 3.9 and the Python IDLE to test all of the code will be testing.
Table of Contents
Print to Terminal
Starting as simply as possible, to use the
print() function in Python you need to insert a parameter or arguments you need inside of the () after the print keyword.
Remember, in Python, everything is an object, you will be able to manipulate all kinds of information in your
print() functions if you do it correctly.
You can print an integer (also known as a whole number, in any combination using 0-9, including negative numbers), a float (that’s any number with a decimal in it), a string(a line of text) or
input() from a user once you have asked for it. This is the easiest use of
Below I will give you an example of each data type and how they are printed.
Pay attention to what data type you are using, it’s easy to get an error statement from carelessness, when you go to concatenate objects in Pythons
When printing an integer, whether positive or negative:
print(-1) the output is going to be either: 1 or -1.
When you are printing a string you want to wrap the string in single quotes (‘ ‘) or double quotes(” “).
print("You can print a sentence like this using double quotes(" ") ")
print('Even a sentence like this is accepted in Python with single quotes(' ').')
The output is as follows:
You can print a sentence like this using double quotes(" ")
Even a sentence like this is accepted in Python with single quotes(' ').
What you want is to be careful of when you are writing strings inside of your print function is if the sentence inside the parenthesis has single and double quotes together.
It’s hard for Python to decide where to start and end. What you’re output becomes is a
SyntaxError: invalid syntax. Nothing is printed out and your program crashes until you fix the error.
There are 2 ways to handle this and both are fairly simple to use. The first is by changing your single quotes wrapping the string into double quotes.
Now when you write your print function Python will have a better idea of what it’s printing. Another way to do this is to use an escape character i.e. the backslash( \ ).
This clever little escape character allows for you to place it in front of a character for example, “( \’ ) ” is the single quote character. For example, the function:
is output as:
It’s super handy to have these little shortcuts in the back of your mind when you are developing your code.
When you’re printing a float or if you are printing the divisible number, you will get a float. Such as:
print(6 / 3)
the output will be 2.0 printed to the terminal.
Make a note when you are working in mathematics in Python, it is only numbers that are being divided will return a float automatically.
Otherwise, you will have to be specific by inserting a type change inside of the print function or else enter the float itself into the function.
So you can enter the following into Python IDLE:
print(12.0 * 3) to receive an output of
36.0. Another way to do this is to convert the integers into a float. What you do is insert the keyword
float() into the
print() function. Now what you see is:
print(float(12*3)) with an output of:
The output is the same but the methods are different. Now that we have covered the basics of the
print() function, let’s look at some more advanced beginner uses of this function you can utilize in your development.
Print to Terminal without New Line (Multiple Print statements)
There are 2 ways to do this in Python and neither is difficult. Just remember to keep your styling the same each time you go to print multiple lines in your script.
Changing the way you print can cause problems in reading your code with other developers. The simplest, yet most tedious way to print multiple lines is to copy and paste the
print() function for as many lines necessary for your code.
As simple as this is, I honestly would recommend against it. It only causes your script to become chunky, hard to manage, and difficult for other developers to read.
The second way to do this is by using triple single quotes
(''' ''') with your print function. This is called multiline printing.
Between the triple quotes, you can easily insert the block of text that needs printing in neat lines and Python will print everything between those triple quotes.
Here in this example, I have placed a sentence with a blank line above and below the sentence to emphasize where the blank lines are located.
Here, I have placed the code you will need to use in order to do this.
print("Below this statement are two new lines.") print() print() print("I'm the final print line! ^ Above me, are two new empty lines!")
or you can do it this way.
print(''' "There's a blank line above me and a blank line below me." ''')
Honestly, this is the best way to get multiple lines printed neatly in your Python script. It’s much easier to manage and read whether it’s a large comment box or a large block of text being added to your script.
You can also use escape characters here as well such as \t for tab or \r for a carriage return in your
print() function. This will also make it look nice once it’s displayed on the screen.
Print to Terminal in Color and Background Colored Text
There are at least 4 ways for you to learn how to print in color with Python. I am going to list them all here but I am only going to use 1 module as an example.
This is both for simplicity and to not cause you any confusion on learning how to print in pretty colors. This is another useful tool in the Python arsenal you can exploit.
Once you learn how to automate emails, adding custom colors to your text will be a cinch if you want people to pay attention to certain parts of your content.
The 4 modules I will be touching on will be Colorama, Termcolor, Ansi, and Colored. All of these modules can be found on the Pypi website, for you to browse at your leisure.
Today, I am going to be working with Colorama. Very much like Ansi, it hosts minimal colors, the syntax is fairly easy to follow, and you will be able to work with them in your terminal!
After installing Colorama, I am going to call it to print in several colors inside of my Python terminal so you can easily see the color changes in my text when it is printed to the console.
As you can see here, I imported OS and the sys module and then asked the os.system to make my text colored. Whenever you run Colorama do not forget to have the
init() called to make it run.
This will filter ANSI escape sequences out of any text sent to stdout or stderr, and replace them with equivalent Win32 calls.
You can see in my terminal that I started with white on black, moved from red on green, to black on yellow, to white on blue seamlessly then back to normal output.
Once you have achieved learning how to do this it will be very helpful in writing Error and Debugging Files. Here is the code you are going to need to do this.
import sys import os os.system('color') import colorama from colorama import init, AnsiToWin32, Fore, Back, Style colorama.init(wrap=False) print(Fore.RED, Back.GREEN + 'I can put Red text on a green background\n') print(Fore.BLACK, Back.YELLOW + 'I can even print Black on Yellow.\n') print(Fore.WHITE, Style.BRIGHT, Back.BLUE + 'Who can resist the nostalgic White on Blue?\n') print(Style.RESET_ALL)
You can always find something do to with Python and yes that does include animation. Would you like to have a sketch made?
You can use turtle in Python to create special designs, including an outline of Sherlock Holmes with his iconic hat and pipe!
You can download anime, create animations for games, tick wait time clocks, and even other libraries like my personal favorite, imageio, an amazing library for reading and writing a wide range of images, videos, scientific, and volumetric data formats with Python.
If you think you can build it, you should probably look at Pypi to help you with the basic building blocks.
In this example, I am going to show you how to build a spinning wait time wheel using the terminal-animation package. What it will do is show a “spinning wheel” in the terminal as a program is in the process of performing.
We need to import time module, os, and sys modules to use them for animation. I have a video that will show you the application loading, the lowercase letters going uppercase, and back again. Here is the code you will need to get started.
import time import sys import os #Function for implementing the loading animation def load_animation(): #String to be displayed when the application is loading load_str = "starting your console application... " ls_len = len(load_str) #used to keep track of animation = "|/-//" anicount = 0 #used to keep track of the duration of animation counttime = 0 #pointer for travelling the loading string i = 0 while(counttime != 100): #used to change the animation speed. Smaller the value, faster the animation time.sleep(0.075) #converting the string to list as string is immutable load_str_list = list(load_str) #x->obtaining the ASCII code x = ord(load_str_list[i]) #y->for storing altered ASCII code y = 0 #if the character is "." or " ", keep it unaltered, swtitch uppercase for lowercase and vice-versa if x != 32 and x != 46: if X>90: y = x + 32 else: y = x - 32 load_str_list[i] = chr(y) #for storing the resultant string res = '' for j in range(ls_len): res = res + load_str_list[j] #Displaying the resultant string sys.stdout.write("\r"+res+animation[anicount]) sys.stdout.flush() #Assigning loading string to the resultant string load_str = res anicount = (anicount + 1)% 4 i = (i + 1)% ls_len counttime = counttime + 1 if os.name == "nt": os.system('cls') if __name__ == '__main__': load_animation() #your desired code continues from here #s = input("Enter your name: ") s = Amber sys.stdput.write("Hello "+str(s)+"\n")
Check the following video to see this code in action:
Python has a very special way of translating one spoken language to another, allowing you to communicate with the world.
This comes in handy when you need to send emails to clients around the world!
Running a Python script to translate your emails, websites, or web applications and have it print in another language as naturally as possible is a huge benefit whether you are working for a company or freelancing your services while catering to an international audience.
To begin make sure you have installed idna and translate into your Python path. Idna is the Internationalized Domain Names in Applications. This allows for translate to be used by the application all around the world thanks to Unicode.
In my code, I have purposefully left my mistake of having
"Guten Morgen" printed 5 times and I will explain why with the same examples.
In this photo next to my output, I have done almost the same as the code that prints in multiple languages, except I forgot to use the true variable name used when translating to the other languages.
This is why the statement “Guten Morgen!” is printed 5 times!
Python simply read the first process and repeated the first process five times since it had information for that input only. The
translator.translate is where my mistakes are and why my other languages aren’t printed out.
Pay special attention to your variable names so you aren’t printing them in the same language multiple times. The code I am going to give you, however, is mistake-free so you can use it to practice.
import translate from translate import Translator translator = Translator(to_lang="German") translation = translator.translate("Good Morning!") print(translation) from translate import Translator translator2 = Translator(from_lang="german", to_lang="spanish") translation2 = translator2.translate("Guten Morgen!") print(translation2) from translate import Translator translator3 = Translator(from_lang="german", to_lang="japanese") translation3 = translator3.translate("Guten Morgen!") print(translation3) from translate import Translator translator4 = Translator(from_lang="german", to_lang="russian") translation4 = translator4.translate("Guten Morgen!") print(translation4) from translate import Translator translator5 = Translator(from_lang="german", to_lang="english") translation5 = translator5.translate("Guten Morgen!") print(translation5)
Python Not Printing to Terminal
There are a couple of reasons this could happen to you while you are working in Python. Most likely, you forgot to enter a necessary component into your function.
This can be anything from forgetting an open or closing parenthesis in which case you will get an EOF or an EOL warning, if it was a string, you have forgotten to add the quotation marks to make it so.
Python will throw a SyntaxError causing your program to crash until you fix it.
Even if your whitespace is off, or the indented bits of code aren’t indented correctly, your program may not print like it is supposed to causing your program to fail.
The best thing to do is run your program through an IDE such as Pycharm or Atom. This will help highlight your work and give you plenty of information on how to fix it.
It also helps to carefully go over your program, line by line. It may seem tedious, but it’s one way to get your program to act right.
Print to File
The input and output of file writing can seem tricky at first because there are many ways to get it done and for good reason!
There is a fundamental question you need to ask yourself. What are you trying to print? This question of course leads to several other questions that will lead you to the correct output of a program.
You can have data put into a human-readable format or have it saved to a file for a later date
There are of course several ways to do this like
sys.stderr for writing a file to save errors too and debug later on. It’s super helpful to have this in your developer arsenal when writing your Python program and finding bugs.
One way is to use the
open() function as defined in Python. This will open a file or create one if it doesn’t exist and saves it as a file.txt, like in the following example:
Now, it may seem like you have not created the file but look here! Before I ran my program, I looked for the file, and found it was not there, ran the program above to create this new file!
After opening the file, I found that what I have written is in my file from the program.
That was so easy! Now I can append to this file!
Have it save logging information for debugging,(We’re gonna touch on that in a minute.) or other important information that is helpful for keeping your program running as smooth as possible.
Files like this are important to keep documentation for your program for other developers as well when onboarding a team. Below, you can use this code to practice:
with open('read_data.txt', 'a+') as file: print(file.readlines()) file.write("test")
Print to stderr
First, you should have an understanding of what stderr is. Stderr (short for standard error stream) is used with stdout(standard output) specifically, when you want to print warnings and errors separately from each other, with predetermined messages by you.
Its prompts and error messages will go here, separately from the actual output. You will need to import the sys module before printing any stderr messages when testing and debugging your program.
These error messages are printed directly to the console for easy reading.
Python print to stderr takes input from stdin(standard input), stdout(standard output), and read from stdin to print its error message. For example, in the following code:
import sys sys.stderr.write("Error messages here:")
Here is an example of what should be printed on your console:
Following my blue pen mark, you can see where the stderr message is written on my terminal. Remember, this is a text file saved in your project folder.
This will help you debug anything that can go wrong, pinpoint it, and squash that bug quickly when used with its brothers
sys.stdin(standerd input) and
Redirect Print to Logger
Printing events that take place in your program is a good way to keep track of bugs. You can have a note of what happened but also have it timed stamped so you know exactly when it happened.
Below are some examples of how I have done it. Configuring the program to print warnings for me.
In the beginning, I created a file to hold the warnings. all of the logging information every time the program runs. I checked in my program for the new saved file ‘warning.txt’ I circled it in red here so you can see it easily.
As you can see here, I was able to produce what I wanted with the couple of lines I wrote for the logger. Afterward, I went into the text file to make sure what I wanted to have printed is actually in the file.
By deep-diving into this portion of the Python documentation, you will uncover all kinds of information about logging from multiple modules, logging variable data, including newer ways to format and how to do it!
It’s worth investing your time into taking a look at how logging can save you some really big headaches when you need to debug your program, what issues are happening, and when.
When you use this code below you should get the same output.
import logging logging.basicConfig(filename='warning.txt', encoding='utf-8', level=logging.DEBUG) logging.debug('This message should go to the log file') logging.info('I hold important information for you!') logging.warning('I hold potentional warnings slowing the program.') logging.error('I let you know the program has crashed and why!')
Arguments are placed inside of a function as predetermined values, meaning they don’t change and are passed when the function is called every time.
You can have multiple variables printed out provided you have the information needed to have it input into the arguments.
For now, let us look at placing one variable inside the function and having it print to the console. We will go over how to have Python print multiple variables later on.
The first thing we are going to do is define a function that has an argument that will be repeated each time the function is called.
Then we are going to run the program a few times so you can see the argument inside the function never changes even if the output does each time. Give your function a name that explains what is going to do.
As you can see from my image and my red pen marks, I was able to enter different names into my definition and each message was printed the same although somewhat personalized because of each name that is printed!
You can use the same argument for multiple variables. In my function, I used an
input() statement since I didn’t have the name of the person I wanted to say hello to.
This is an advanced beginner’s move but one worth knowing, for sure. Go ahead a give it a go by using this code below.
def Get_name(name): print('Hello from Python Power', name+ '!') Get_name(name=input('Enter your name\n'))
Print New Line
Just like with Multiple line print statements, there are 2 ways about getting this done.
You can either use the
print() function leaving the parenthesis empty for as many lines as you need for a new line to be printed, as shown above, here in this example, I have used the escape clause using
This will print a new line for each instance it was used. If you use the first method then you are again left with code that is chunky and hard to manage.
You want to keep it streamlined and manageable for yourself and with other developers so it is better to use the second method while following the PEP 8 guidelines.
As you can see here, I was able to produce two new lines above and below my sentence easily and kept my code neat. By using this code you will get what you see above.
print("\n\n I have two new lines above me and two new lines beneath me\n\n")
Make sure you enter \n and not /n the printed result will be:
/n/n I have two new lines above me and two new lines beneath me./n/n
It’s a common mistake, so don’t worry if it happens to you.
How to Print % to Python
The modulo operator (%) is more than just finding the remainder of a number in Python. This is also known as the formatting or interpolation operator. The (%) character is a unique built-in operation.
When it is used in this context, marks the start of a specifier. A conversion specifier will transform the % into a value predetermined by a dictionary in this case.
This is an old way to format strings in Python. It doesn’t nearly offer as much flexibility or readability when the information is incoming from a dictionary or a tuple.
There are other ways to get this done but for now, let’s stick with this first concept. It’s going to seem a little confusing at first but I am going to help you break it down.
Okay, I know what you are thinking! It’s too advanced or it’s too confusing, but I promise you it is easy.
In this particular example, I have used the modulo(%) operator to pull information from my variables and replaced it with the information I wanted.
Like how my sentence came about from what may seem like a whole bunch of noise in my print function. For right now, ignore the
I’ll explain this part of the operation much deeper in another article. The (%) searched my local variables seen here located above my print function(name, numb_of_books) and replaced it with the values(‘Wizard Kelly’, ’12’) as shown in the above code.
Notice after each of my (%), I placed indicators for Python to know what to expect from my variables.
These indicators or flags used in this case were for a string(%s) and a digit(%d). This operator is a great way to insert tuples and even dictionaries into your statements.
However, it can become tricky as your script grows larger and more complex due to the sheer size of input that can be inserted.
Use this code here to go ahead and get started in using the modulo string format.
name= "Wizard Kelly" numb_of_books = 12 print('%s has %03d books available.' %(name, numb_of_books))
In Python, you can print multiple arguments from input, a list, or even a dictionary if you know how to pass in arguments.
This way you can have data inserted automatically by placing the variables inside of your print statement. String formatting is one way of doing it, allowing you to take the information you have and pass it into a function.
However, what about the information you don’t have yet? What if I told you that all you need is the asterisk (*) key, for positional and keyword arguments?
This is how it works, if you know how many arguments are going to be used then you can insert it into the parentheses (here).
What happens if you don’t know how many arguments there are? The simplest thing do to is to use the *args. This allows you to have as many arguments as necessary.
This will allow you to insert default parameters, giving you more control over the flow of your functions. In my following examples, you will see that I have passed both a single (*) and a double (**) so you can see the difference in them both.
As you can see, I was able to print everything in the order presented to me. Some data was known, some were predetermined, and the rest came from a dictionary and was printed as a tuple.
Understand that a default argument is always given before a positional, and positional before keyword arguments. An (*) before the positional arguments is returned as a tuple while (**) before the keyword arguments are returned as tuples.
Give yourself a little practice with
args to see how it works using the different codes below.
def calculateTotalSum(*args): totalsum = 0 for number in args: totalSum += number print(totalSum) calculateTotalSum(15, 3, 7, 89, 2) ------------------------------------------------------- def knownarguments(**args): for arg in args.items(): print(arg) knownarguments(arg1 = 'I', arg2 = 'am', arg3 = 'known') --------------------------------------------------------------- def displayArguments(argument1, *argument2, **argument3): # displaying predetermined argument print(argument1) # displaying non keyword arguments for arg in argument2: print(arg) # displaying keyword arguments for arg in argument3.items(): print(arg) arg1 = "Welcome" arg3 = "Death" # function call displayArguments(arg1, "to", arg3, agr4 = "Blitz", arg5 ="Knaves!")
Print vs Return
Print or return, that is the question, but it doesn’t have to be! While print puts an output to the console, the return statement does not.
The return statement allows for the input of a variable to be stored until called. The return statement can be confusing to use at first because it is often used with print statements.
No matter how many times you call the function, whatever data is saved to the variable is what is “returned”.
My example here shows what data is put into the function, and how the data is returned whenever I call the function. I am going to define a function and have it return a value to me and print it to the console:
Now, of course, you can use the skill above where input is asked and the variable is saved and returned with the print statement.
Notice instead of using the word ‘name’, I used a string and inserted my name. I also didn’t require any type of parenthesis to make the return statement function.
This is because it is a function that returns data to a variable and then closes the program without any output to the console.
Use this code and play around with it. Remove the return statement or the print function and see what happens.
def greet(name): return "Hello " + name greeting = greet("Amber") print(greeting)
In conclusion, there are many ways for you to use the
print() function in your code. Remember,
print() is a keyword so it is best not to overwrite this important feature to mean anything else in your code.
I know some of you laugh but you would be surprised how often this happens in the wild with beginners trying out the functions and overwriting them without knowing the rules of engagement.
Now you know the many different ways you can use the
print() function, how you can change the data types, have multiple arguments and log inside your script to keep track of all the events that happen.
These many attributes of
print() can be life-saving when you are in a time crunch for a client or simply building your projects.
Remember to practice, even if it is only 1 line a day! Foundations are what make good developers, great!
You can read more about the print function from here:
Mokhtar is the founder of LikeGeeks.com. He works as a Linux system administrator since 2010. He is responsible for maintaining, securing, and troubleshooting Linux servers for multiple clients around the world. He loves writing shell and Python scripts to automate his work.