Printing multiple things at the same time

So far, we've only seen one way to use print: we go print(<value>), and get the value printed to the screen. What if we want to print several things? We can go

In [1]:
print("ab," + "cd")
ab,cd

We are still printing one value there, it's just that the value "ab,cd" is computed before printing it by adding together (the term is concatenating) ths strings "ab," and "cd".

Here is another way to do this:

In [2]:
print("ab,", "cd")
ab, cd

We used a comma rather than a a plus there: we just told print to do two things: print "ab,", and then print "cd". Note that print inserted a space in between the two strings.

This is especially useful when we want to print both numbers and strings. The following doesn't work:

In [3]:
print("abc" + 123)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-f5858a0b6c25> in <module>()
----> 1 print("abc" + 123)

TypeError: Can't convert 'int' object to str implicitly

We cannot compute "abc" + 123, since you can't add a string and an integer: it doesn't make sense!. But there is no problem with asking print to print two things: first "abc", and then 123 (and also insert a space in between)

In [5]:
print("abc", 123)
abc 123

Note that the comma there is not printed. To print a comma, do what you would do to print any character, and put the comma inside quotes.

In [6]:
print("abc;", 123)
abc; 123
In [7]:
print("abc,", 123)
abc, 123