The basics of syntax

INPUT · Slides

Joining text together

01 / 06

Text joins up with + as well

+ is the symbol for adding, but put it between two pieces of text and it sticks them together.

With numbers it adds, with text it joins. The same symbol changes job depending on what it is given.

print("Good" + "bye")

Result

Goodbye

02 / 06

You put the gaps in yourself

Joining does not add a space. If you want one, you write one.

A piece of text with nothing but a space in it, " ", is perfectly good text.

print("Sato" + " " + "Keita")

Result

Sato Keita

03 / 06

Repeat text with *

Use * on text and you get that many copies of it in a row.

Handy for drawing a dividing line, or a bit of decoration.

print("ha" * 3)print("-" * 10)

Result

hahaha
----------

04 / 06

Text and numbers will not add

Here is the first real wall. Join text and a number with + and you get an error.

Python will not guess whether you meant to add or to join. Rather than decide for you, it stops and says so.

print("we have " + 3)

Result

TypeError: can only concatenate str (not "int") to str

05 / 06

Commas let you line things up

So how do you show text and a number together? Separate them with a comma , inside the brackets of print.

What you separate with commas comes out in order with one space between each. It does not mind that they are different kinds of thing.

print("we have", 3, "dogs")

Result

we have 3 dogs

06 / 06

How + and , differ

They look similar and they are not, so let us sort that out now.

  • + … sticks text to text. No space. Will not mix with a number
  • , … hands several things to print. A space goes in between. Different kinds are fine

If you are unsure, reach for ,. Later you will meet another way (the f-string) that gives you more freedom still.

print("a" + "b")print("a", "b")

Result

ab
a b