Data Types

Python is a programming language with strong typing. But what does this mean?

Imagine you need to display the result of an arithmetic operation. For example, the sum of two numbers. Displaying just a number isn’t very exciting, so let’s add some text, like “The result is ‘. The ‘+’ operator adds two numbers and can also concatenate two strings. But what if we need to concatenate a string and a number?

result = 10 + 15
text = "The result is " + result
print(text)

This program won’t work and will show the following error:

TypeError: Can't convert int to str implicitly

This error means Python cannot concatenate a number with a string because they are different data types. Strong typing means data must be converted to the same type for operations to work correctly.

Besides strings and integers, Python has many other data types. However, to understand the concept, strings and numbers are enough. To convert a number to a string, use the built-in str function. This program will work and display what we want:

result = 10 + 15
text = "The result is " + str(result)
print(text)

What if we want to add numbers that the user inputs?

a = input('Enter the first number: ')
b = input('Enter the second number: ')
result = a + b
text = "The result is " + str(result)
print(text)

The output of this program might seem strange, but it worked as it should! If the user enters 1 and 2, the program will display:

The result is 12

This happened because the input function gets strings. So, even though the user entered numbers, they were treated as strings. The same would happen in this program:

result = "10" + "15"
text = "The result is " + result
print(text)

Here, the numbers are “concatenated” as strings.

To make everything work as we want, the strings entered by the user must be converted to numbers. The int function will help with this:

a = input('Enter the first number: ')
b = input('Enter the second number: ')
result = int(a) + int(b)
text = "The result is " + str(result)
print(text)