Learn how to print information in Python out onto a console.
Often when creating programs, we want to display information or data to users so that they are able to understand and use that information. In Python, the easiest way to display information to a user is by using a print()
statement. print
is used to display a variety of data types - like Strings, integers, and objects - to the terminal console. To use print
, we can simply include the value or variable we’d like displayed to the console as a parameter in the print
function:
In the program following, try using print
to print your name and hometown to the console!
print
can also take multiple values in the same call to print, and separate them using a default separator. The default separator spaces each parameter given to the print
statement by a single space:
We can override the default separator by adding the keyword sep
as the last parameter in our print statement, and set it equal to the value that we’d like to separate each value with:
In this case, the two variables name
and hometown
are being separated by the value " of "
. If we added a third value to the parameter list, it would also be separated with the same value:
See if you can correctly use the sep
keyword in the following exercise:
An exercise instructor wants to print out their workout instructions so their users can follow along. They find that they are repeating the phrase “1 and 2 and 3 and 4” over and over again as they give their instructions. Using only the print
statement and the word “and” only one time, try to print this phrase to the Python console.
As demonstrated in the first exercise, print
statements default to printing each statement on a new line in the console. We can override this behavior by including the end
keyword as a value in the parameter list:
Think you’ve mastered the print statement? See how well you do on this quiz:
Which Python code segment will display “Hello, world!” on the screen?
What does the following Python code display?
print("Hello") print("World")