Concatenation means joining strings together. In Python, you use the + operator to concatenate strings:
print("Hello" + " " + "world")
This outputs: Hello world
You can also print strings and numbers together by separating them with commas in the print() function:
print("I am a student and I am aged", 15)
print("2 + 2 =", 2 + 2)
Note the difference:
+ operator concatenates strings (joins them with no space)print() separate multiple values (adds a space between them)You cannot concatenate a string and a number directly with +. This will cause an error:
print("I am " + 14 + " years old") # Error!
You must convert the number to a string first using str():
print("I am " + str(14) + " years old")
Or use commas instead:
print("I am", 14, "years old")
Can you spot and fix the errors in each of these lines?
print("hello " + "world)Missing closing quote. The correct version is:
print("hello " + "world")
print("I am Jerry, and I am ", 14 years old")Missing opening quote before 14. The correct version is:
print("I am Jerry, and I am", 14, "years old")
print('I\'m Jerry and I\'m' + 14 + 'years old')Cannot concatenate strings and integers with +. The correct version is:
print("I'm Jerry and I'm " + str(14) + " years old")