The TypeError: must be real number, not str error concerned with using a wrong type and a non-real number, particularly an str type.
When working with Python projects, this is one of the common errors or bugs to encounter.
So in this article, we will explore this error, understand what it means, and learn how to fix it.
But before we proceed to the solutions on how this error occurs, let’s understand first the key terms involved in this error.
In Python, TypeError is an error that is raised when an operation or function is applied to an object of an inappropriate type.
This error occurs when an object is not of the expected type, and the operation or function cannot be applied to that object.
Real numbers are those numbers that can be represented on the number line.
Additionally, real numbers include integers, decimals, and fractions. In fact, in Python, the float data type is used to represent real numbers.
In Python, str is a data type that is used to represent a string of characters. Further, a string is a sequence of characters enclosed within single or double-quotes.
Now, let us see how this error occurs.
How Typeerror must be real number not str occur?
The Typeerror must be real number not str is an error that occurs when the code attempts to perform a mathematical operation on a string instead of a numerical value.
This error is caused by a type mismatch between the expected data type and the actual data type of a variable or input.
So, let’s say we are working with the built-in input() function to take a number and work with the number in a simple mathematical expression.
number = input("Enter a Number: ")
print(number/12+ 12* number)
In this code, we will get the Typeerror message since the binding had a string data 2 instead of an integer or float number 2.
This output the following:
Enter a Number: 2
Traceback (most recent call last):
File “C:\Users\Windows\PycharmProjects\pythonProject1\main.py”, line 2, in <module>
print(number/12+ 12* number)
TypeError: unsupported operand type(s) for /: ‘str’ and ‘int’
However, the error that we have above is not the same as the TypeError: must be real number, not str error. The difference is in the process that’s occurring.
Now, we will use the math library in Python to round down the input number of the user.
Here is the snippet code:
import math
number = input("Enter a Number: ")
print(math.floor(number))
Output:
Enter a Number: 2
Traceback (most recent call last):
File “C:\Users\Windows\PycharmProjects\pythonProject1\main.py”, line 3, in <module>
print(math.floor(number))
TypeError: must be real number, not str
In this code, we will get a distinct error from above since we are parsing the number binding wherein it contains a string to the floor() method.
Additionally, the method requires a number float or integer.
This time let us see how to fix this error.
Solutions for Typeerror must be real number not str
Considering the given example above, to fix the error we need to convert the datatype value the user passes to the number binding to float or integer, depending on what we need.
Using float function
The most appropriate function to use in dealing with float numbers is the built-in float () function.
Given that we need decimal numbers to round up, we need the float() function.
import math
number = float(input("Enter a Number: "))
print(math.floor(number))
Output:
Enter a Number: 2.5
2
Using int() function
Another way to fix it is by using the int() function. This function can be useful in a case where the number required is a whole number.
Therefore, if the required numbers to be parsed to the sin() method is a whole number, int() method can be used.
import math
number = int(input("Enter a Number: "))
print(math.sin(number))
Output:
Enter a Number: 10
-0.5440211108893698
Apparently, this error is easier to fix since it is a simple case, but in some difficult and complex scenarios, it could be trickier.
Complex scenario
Let’s say we are working with randomized trigonometric calculator.
The best step to avoid the error is always to convert it immediately.
Particularly before the operation expression.
Here is an example of a mathematical operation.
import random, math
def create():
global sideA
sideA = format(random.uniform(1, 100), '.0f')
global sideB
sideB = format(random.uniform(1, 100), '.0f')
global angleA
angleA = format(random.uniform(1, 180), ',.3f')
global angleB
angleB = ANGLE_B()
return angleB
def ANGLE_B():
angle = format(math.asin(sideB*(math.sin(angleA)/sideA)), '.3f')
return angle
print(create())
Output:
Traceback (most recent call last):
File “C:\Users\Windows\PycharmProjects\pythonProject1\main.py”, line 19, in <module>
print(create())
File “C:\Users\Windows\PycharmProjects\pythonProject1\main.py”, line 11, in create
angleB = ANGLE_B()
File “C:\Users\Windows\PycharmProjects\pythonProject1\main.py”, line 16, in ANGLE_B
angle = format(math.asin(sideB*(math.sin(angleA)/sideA)), ‘.3f’)
TypeError: must be real number, not str
Based on the output above if you trace the error you can see it begins from print(create()).
Wherein it calls the ANGLE_B() function uses the binding sideA, sideB, and angleA.
This time the most responsible way to fix the code error is to convert the datatype before use in a mathematical expression.
Thus, we don’t need to change the value again.
Here is the example code:
import random, math
def create():
global sideA
sideA = float(format(random.uniform(1, 100), '.0f'))
global sideB
sideB = float(format(random.uniform(1, 100), '.0f'))
global angleA
angleA = float(format(random.uniform(1, 180), ',.3f'))
global angleB
angleB = ANGLE_B()
return angleB
def ANGLE_B():
angle = math.asin(sideB*(math.sin(angleA)/sideA))
return angle
print(create())
Output:
0.11130043721091433
Common mistakes leading to must be real number not str
Some common mistakes that lead to the TypeError: must be real number not str are:
- Forgetting to convert the user input to a float before performing a mathematical operation.
- Passing a string instead of a float to a function that expects a float.
- Using a string instead of a float as an index in a list.
Anyway, we have also additional resources you can consider when you encounter the error.
- Typeerror: unhashable type: ‘dataframe’
- Typeerror: ‘classmethod’ object is not callable
- Typeerror: failed to construct ‘url’: invalid url
Conclusion
The TypeError: must be real number not str is a common error that occurs when we try to perform a mathematical operation on a string instead of a float. In this article, we have explored this error, understood what it means, and learned how to fix it by converting the string to a float.
By avoiding common mistakes and applying the solutions provided in this article, we can write better code and avoid errors in our programs.
Thank you! 😊