Joining strings with +
A greeting and the user's name usually belong on the same line. To build that line, join strings with +. Putting strings end to end like this is called concatenation:
name = input("Your name: ")
print("Welcome, " + name + "!")
AdaYour name: Ada
Welcome, Ada!Python first builds one string out of the three parts: "Welcome, ", the value of name and "!". Then print prints that string. You can join as many parts as you need, and you can use the same variable several times in one line.
Spaces are your job
+ puts nothing between the strings it joins, not even a space. Any space you want must be inside the quotes:
animal = input("Animal: ")
print("The" + animal + "is asleep.")
print("The " + animal + " is asleep.")
catAnimal: cat
Thecatis asleep.
The cat is asleep.In the second line, the space after The and the space before is are part of the strings, so the words come out apart.
Storing a joined string
The result of + is a new string, and you can store it in a variable like any other value:
word = input("Word: ")
loud = word + "!!!"
print(loud)
print(loud + " " + loud)
yesWord: yes
yes!!!
yes!!! yes!!!A missing +
Every part needs a + between it and the next one. Without it, Python can't read the line at all:
name = input("Your name: ")
print("Hi " name)
File "main.py", line 2
print("Hi " name)
^^^^^^^^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?This is a syntax error, so nothing runs, not even the input on line 1. Python guesses a missing comma. Commas do work in print, as the next step shows, but here the missing piece is a +.