Print() in Python


Here are a few examples of using print() in Python. I encourage you to do more research and practice on your own. Of course you can copy and paste the code into your own environment. I’m using Jupyter Notebook.

x = 7
name = 'Bob'
print(x)
print(name[0])
print(name)

The output is:

7
B
Bob

print('My name is {} and my number is {}.'.format(name,x))

Here is the output:

My name is Bob and my number is 7.
# one and two are variables
print('My name is {one} and my number is {two}.'.format(one=name,two=x))

Here is the output:

My name is Bob and my number is 7.
print('{:.2f}'.format(123.456))  # two decimal places

Here is the output:

123.46
print('{:.2f}'.format(123.456))  # two decimal places

Here is the output:

123.46
print('{:.1f}'.format(123.456))

Here is the output:

123.5
print('{:.2%}'.format(0.451))  # the % multiplies by 100 and formats

Here is the output:

45.10%

Here’s a good use case for formatting a number as a percent. We have a dataset as a pandas DataFrame called df. We wnat to know the percent of rows that are duplicated. Here how we can do that and put the number into a string. Notice that the first element of shape gives us the number of rows in the dataset. The second element represents the number of columns in the dataset.

perc = df0.duplicated().sum() / df0.shape[0]
print('{:.2%}'.format(perc) + ' is duplicated')
# output will look something like: 20.05% is duplicated

If you want to print some of your text in bold, have a look at this article called How to print Bold text in Python [5 simple Ways].

If you are using Jupyter Notebook and you need to write some text to perhaps help explain your project, you can put that text into a Markdown vell instead of a code cell. In markdown, if you want to make some text bold, surround the text with two asterisks (stars above the 8 key on the keyboard).

Leave a Reply