How to fix TypeError: can't multiply sequence by non-int of type 'float'

One error that you might encounter in Python is:

TypeError: can't multiply sequence by non-int of type 'float'

This error occurs when you try to multiply a string by a float in Python.

The following tutorial shows an example that causes this error and how to fix it.

How to reproduce this error

The error happens anytime you try to multiply a string by a number with floating points. Suppose you run the following code:

input_x = "3"
input_y = 3.5

result = input_x * input_y

You’ll get this error:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    result = input_x * input_y
TypeError: can't multiply sequence by non-int of type 'float'

This error usually occurs when you ask for user input using the input() function.

The input() function always returns a string even when the user gives a number:

input_x = input("Put a number to multiply by 3.5: ")
input_y = 3.5

print(input_x * input_y)

You can see in the example below that the error still happens when a number is given:

Put a number to multiply by 3.5: 3

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    print(input_x * input_y)
TypeError: can't multiply sequence by non-int of type 'float'

How to fix this error

To resolve this error, you need to identify and convert the string type value into a float.

You can do this using the float() function as follows:

input_x = float("3")
input_y = 3.5

result = input_x * input_y

After accepting user response with the input() function, convert the response to float as follows:

input_x = input("Put a number to multiply by 3.5: ")

# Convert str to float:
input_x = float(input_x)

input_y = 3.5

print(input_x * input_y)

By converting the input_x value to float as shown above, there will be no error:

Put a number to multiply by 3.5: 3
10.5


Put a number to multiply by 3.5: 2
7.0


Put a number to multiply by 3.5: 9.4
32.9

You can multiply both integer and float values without any error.

I hope this tutorial is helpful. Happy coding! 👍

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.