To fix the “TypeError: can’t multiply sequence by non-int of type ‘float'” error, convert the string into a floating-point number using “round()”, “math.floor()”, or “math.ceil()” function before multiplying it with a float. To multiply a sequence by a user-entered number, you need to convert the input to an integer or float first and then, if necessary, round or truncate the float to an integer.
Python raises the TypeError: can’t multiply sequence by non-int of type ‘float’ error when you use the “input() function, which takes user input”. By default, the input() function returns user input as a “string”.
Reproduce the error
user_input = input("Please enter your age: ")
print(user_input * 0.5)
Output
Please enter your age: 18
TypeError: can't multiply sequence by non-int of type 'float'
You can see that even though I entered an integer, the return data type is of type string, and if it tries to multiply the string to a floating-point number, it throws the TypeError.
How to fix the error
You can use the “round()”, “math.floor()”, or “math.ceil()” function to convert the string data type to float and then multiply with a float value.
import math
# Get user input and convert it to a float
user_input = float(input("Please enter your age: "))
int_val_round = round(user_input)
int_val_floor = math.floor(user_input)
int_val_ceil = math.ceil(user_input)
result_round = 0.5 * int_val_round
result_floor = 0.5 * int_val_floor
result_ceil = 0.5 * int_val_ceil
print("Rounded:", result_round)
print("Floor:", result_floor)
print("Ceil:", result_ceil)
Output
Please enter your age: 18
Rounded: 9.0
Floor: 9.0
Ceil: 9.0
In this code, we first convert user input into a float.
Then, we converted the float to an integer using round(), math.floor(), or math.ceil(), depending on the desired behavior.
Finally, we multiply 0.5 by the resulting values.
This way, you avoid the TypeError: can’t multiply sequence by non-int of type float error when working with user input.