Welcome to Python! It’s a very fun language.
One of the cool things about Python is that you can change the type of thing you have inside your variable. For example, this is valid code:
# This variable is an integer
my_var = 45
# Now it's a float
my_var = 45.0
#Now it's a string
my_var = '45'
In some languages, the type (the sort of data) a variable holds can’t change over the course of your program. That is, if my_var
started out holding an integer, you couldn’t make it hold a string later.
But Python will let you change the type of your variables (e.g. change what sort of data your variable holds). Because of that, Python sometimes has to use context clues to figure out what to do.
In this code:
x = 2
y = 3
print(x+y)
Both x
and y
are integers, so it’s obvious that you want to add them together. Running this code will print 5
.
By the same token if you have this code:
x = 'apples and'
y = ' oranges'
print(x+y)
Python knows that both x
and y
are strings, so it’s obvious you want to concatenate (smoosh) them together. Running this code will print 'apples and oranges'
.
But what happens when you mix up variables? What if you have this code:
x = 2
y = ' oranges'
print(x+y)
What’s Python supposed to do now? The integer (x
) suggests you want arithmetic, but the string (y
) suggests you want concatenation. It can’t read your mind so it throws an error: TypeError: unsupported operand type(s) for +: 'int' and 'str'
. What does that mean?
Let’s break down the error message.
- TypeError: The error has to do with the type of data (e.g. string, list, integer)
- Unsupported operand type(s) for +: The problem is the plus sign you’re using
- ‘int’ and ‘str’: The error is occuring because you’re trying to mix an integer and a string
Okay, so how can you fix it? Does that mean you can never mix numbers and text? That wouldn’t be very useful.
In order to get around this, you just have to convert one type of variable to the other. In this example, there’s no number equivalent to the word ‘oranges’, so that means we’ll have to convert the number to a string. You can do it this way:
x = 2
y = ' oranges'
print(str(x)+y)
Now, you get 2 oranges
.
I hope this gets you started! One other note–you were really close, but you used an apostrophe and a quotation mark to try and surround your code. It’s three backticks, the little accent looking things above the Tab key on an English QWERTY keyboard. That’s how you make it look like code.