Printing and formatting statements#

Programming for Geoscientists Data Science and Machine Learning for Geoscientists

Basic printing#

Printing text#

A line of code in Python is a statement:

print("Hello world!")

print() is a function in Python that takes an argument in brackets () and prints it out to the terminal.

print("Hello World!")
Hello World!

print() function can also print multiple lines, using \n as a line separator in your text. Notice that you do not need to add spaces around \n in the text:

print("Hello world!\nThis is my first code.\nI love coding.")
Hello world!
This is my first code.
I love coding.

Multiple lines can be also achieved by triple apostrophe """text""":

print("""Hello world! 
This is my first code.
    I love coding.""") # This # is a comment that has no effect on code

# Note how added spaces in the last line are reflected in the printed statement
Hello world! 
This is my first code.
    I love coding.

Printing numbers#

Apart from text, which we call a string, print() function can also take numbers and variables:

print("10")     # Print a string '10'
print(10)       # Print number 10
print(10+5-3)   # Calculate 10+5-3
print(10*5+3/2) # Multiply with *, divide with /
print(10**3)    # To take powers, use **, here 10 to the power of 3

a = 45
print(a)

# Finally more difficult calculation, brackets matter in order of calculation!!

print(5.0*0.6+(100.0+15)/5.0) # With brackets
print(5.0*0.6+100.0+15/5.0)   # Without brackets
10
10
12
51.5
1000
45
26.0
106.0

String formating#

Sometimes we want to insert certain texts (strings) or numbers into print statements.

Inserting:

  • use %s in the statement where you want to insert text

  • use %g in the statement where you want to insert numbers, Python decides here how many significant figures are needed

  • use %.xf, where x is a number of significant figures you want displayed for your number

The syntax (coding rules) for inserting numbers/text into print statement is:

print("Text %s text text text" % ("text"))

An example below:

# Print your name and age inserted into text

print("My name is %s and I am %g years old." % ("<insert your name>", 18))

# Work out your height in meters, provided you are 5 ft 4 in and insert into text
# 1 foot = 0.3048 m
# 1 inch = 0.0254 m

print("I am %.2f m tall." % (5*0.3048 + 4*0.0254))
My name is <insert your name> and I am 18 years old.
I am 1.63 m tall.

Format() method and f-strings:#

This method allows to specify positions of the objects we want to insert into a string. For example:

print("I like {0} and {1}.".format('dinosaurs', 'brachiopods'))
print("I like {1} and {0}.".format('dinosaurs', 'brachiopods'))
I like dinosaurs and brachiopods.
I like brachiopods and dinosaurs.

We can also specify a variable name that will go into the string:

print("I like {0}, {1} and {other}.".format('dinosaurs', 'brachiopods', other = 'ammonites'))
I like dinosaurs, brachiopods and ammonites.

Recent versions of python also support f-strings which allow us to do the above in a more simple way. They are called f-strings because they require f to be written in front of the quotation marks:

a = 'dinosaurs'
b = 'brachiopods'
c = 'ammonites'

print(f"I like {a}, {b} and {c}.")
I like dinosaurs, brachiopods and ammonites.

Apart from strings, we can also insert numbers:

print(f"This fossil is {0:d} cm long and {1:.2f} cm wide.".format(12, 5.05))
print(f"This fossil is {0:g} cm long and {1:.4f} cm wide.".format(12.0, 5.05))
print(f"This fossil is {0:g} cm long and {1:8.4f} cm wide.".format(12.0, 5.05))
This fossil is 12 cm long and 5.05 cm wide.
This fossil is 12 cm long and 5.0500 cm wide.
This fossil is 12 cm long and   5.0500 cm wide.

All methods are valid so you can use whichever one suits you better!

Exercises#


  • Print the following:

Veni vidi vici

  • Print the following:
    HINT: There are ‘\t’ and ‘\n’ which you might find useful

First line
Second line
	BOOM!

  • Some characters in printing statements can be a bit tricky to handle. Think about the following:

“John is a great fan of Shakespeare, so he decided to reference the famous “Be of not the be?” from ‘The Hamlet’ is his latest essay”

This confuses the Python parser because quotation marks are reserved for the beginning and end of a string. So we use backslash e.g. \" to escape certain characters (like we do with \n and \t). Print the sentence from the example.


  • Printing can be art! Use some characters to show your creativity! Try a triangle for example:

    HINT: What about printing the backslash?

    /\  
   /  \
  /    \  
 /      \  
 --------

If you want more inspiration, google ASCII art.

        __  _-==-=_,-.
        /--`' \_@-@.--<
        `--'\ \   <___/.  
             \ \\   " /  
              >=\\_/`<
  ____       /= |  \_|/
_'    `\   _/=== \___/
`___/ //\./=/~\====\
    \   // /   | ===:
     |  ._/_,__|_ ==:        __
      \/    \\ \\`--|       / \\
       |    _     \\:      /==:-\
       `.__' `-____/       |--|==:
          \    \ ===\      :==:`-'
          _>    \ ===\    /==/
         /==\   |  ===\__/--/
        <=== \  /  ====\ \\/
        _`--  \/  === \/--'
       |       \ ==== |
        -`------/`--' /
                \___-'