1.7. Don’t Mix and Match Variables Types#
It’s important to know that you can’t mix and match operations between different data types and that it doesn’t always make sense to apply mathematical operations to strings.
print("red" - "blue")
However, if you use the + operator between two strings, you’ll find that it actually
concatenates (joins) the strings together.
print("red" + "blue")
This means that there is a difference between the number 3 and the
string '3'.
Another slightly odd behaviour is that you can multiply a string with a number. This results in the string being repeated.
x = "red"
y = 3
print(x * y)
Question 1
What do you think the output of the following code will be?
x = 3 y = 4 print(x + y)Solution
7
Question 2
What do you think the output of the following code will be?
x = '3' y = '4' print(x + y)Solution
Solution is locked
Question 3
Which of the following code snippets are valid? Select all that apply.
x = '1'
y = '2'
print(x - y)
x = '1'
y = '2'
print(x + y)
x = '1'
y = 2
print(x + y)
x = 1
y = 2
print(x * y)
x = '1'
y = 2
print(x * y)
lock
This solution is locked.
Solution
Solution is locked