Data types, pt. 1
[vocab] integer
Published in
3 min readFeb 4, 2018
→ Lab Assignment: “Integers + Strings” on repl.it
1. Let’s run the following in IDLE shell
Remember:
- Lines that start with
#
are comments (don’t type them) >>>
← this is the shell’s prompt for a new command. Press ‘Enter’ to run each command.
# concatenating strings>>> a = "20">>> b = "18">>> print(a + b)2018######################## adding integers>>> a = 20>>> b = 18>>> print(a + b)38
2. Now let’s try this:
>>> string = "The year is ">>> integer = 2018>>> print(string + integer)
.
.
.
What happens? We get this error:
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
print(string + integer)
TypeError: must be str, not int
We can’t add an integer to a string, because they are different data types!
So we need to convert the integer → string, using str()
:
🤖 str()
is a function that turns any value into a string
3. Try calling str() on the integer
variable:
>>> str(integer)
'2018'
4. Now let’s use it to print the whole statement:
>>> print(string + str(integer))
The year is 2018
Great! Now let’s look at an example where we need to convert the other way, from string → integer
5. Define the following input variable:
>>> age = input("How old are you? ")
Because this is the shell, it will immediately ask you for the input afterwards. Type your age and press ‘Enter’.
6. To check the value of your variable, just type its name + press ‘Enter’:
>>> age
'27'
It should return the value immediately after.
As you can see, it returns a string.
🤖 * An input is always a string *
Remember this ^
7. Let’s try to find out how old you will be in 25 years:
>>> print(age + 25)
.
.
.
What happens? We get this error:
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
age + 25
TypeError: must be str, not int
We can’t add an integer to a string, because they are different data types!
So we need to convert the string → integer, using int()
:
🤖 int()
is a function that turns a value into an integer
8. Try calling int()
on the age variable:
>>> int(age)
27
9. Now let’s add 25 years:
>>> print(int(age) + 25)
52
No error this time! 😎