How to Fix the "Python TypeError: can't multiply sequence by non-int of type float"
If you are facing a Python Type Error that says Python TypeError: can't multiply sequence by non-int of type float. This article can help you understand why this error occurs and how to fix this.
Why does "Python TypeError: can't multiply sequence by non-int of type float" occurs?
The "Python TypeError: can't multiply sequence by non-int of type float" occurs when we are trying to multiply a string with a floating-point number value.
In Python, there are 2 types of numbers which are integer and floating-point numbers. The Integer is a positive or negative whole number including zero while floating-point numbers are numbers that have a decimal point and can also be positive or negative. Multiplying in Python sometimes confusing especially to beginners because in this language, we can multiple stings with the integer that result in a repeating sequence of characters. For example:
- value1 = "SourceCodester \n"
- value2 = 2
- print(value1 * value2)
- # The result will output something like
- # Sourcecodester
- # Sourcecodester
The script above will result in the following image:
Because of that, it is possible for some developers to forget or unintentionally write a code something like the following script:
- value1 = "20"
- value2 = 2
- print(value1 * value2)
Which results in the following image:
If did not notice this and proceed execution of the code like the following:
- value1 = "20"
- value2 = 5.5
- print(value1 * value2)
It will raise a Python Type Error that says "can't multiply sequence by non-int of type 'float'" like the image below:
Solution
The TypeError: can't multiply sequence by non-int of type 'float' error can be easily fixed by converting the string into an integer or float. Then, when it was successfully converted the multiplication equation that we want to execute will return the correct product.
Here is an example of the fixed Python script:
- value1 = "20"
- value2 = 5.5
- print(int(value1) * value2)
- #output: 110.0
Or
- value1 = "101.5"
- value2 = 25.5
- print(float(value1) * value2)
- #output: 2588.25
There you go! That is we can fix the "Python TypeError: can't multiply sequence by non-int of type 'float'" and prevent this from occurring in your future projects.
That's it! I hope this article helps you to understand the Python Type Error that says can't multiply sequence by non-int of type 'float' and you'll find this useful for your current and future Python Projects.
Explore more on this website for more Tutorials and Free Source Codes.
Happy Coding =)
- 253 views