Don’t Mix and Match Variables Types

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, 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 will result in an error? Select all that apply.

  1. x = '1'
    y = '2'
    print(x - y)
    
  2. x = '1'
    y = '2'
    print(x + y)
    
  3. x = '1'
    y = 2
    print(x + y)
    
  4. x = 1
    y = 2
    print(x * y)
    
  5. x = '1'
    y = 2
    print(x * y)
    
Solution

Solution is locked