pythonmathintegeroperands

"unsupported operand type(s) for +: 'int' and 'str'"


Ive been trying to find a solution to this problem for a while now but I did not find a single way to fix my problem, it would be great if somebody helped me out here.

So basically I wanted to create a random math problem and then compare the User input with the solution to the math problem. The problem lies in the "solution" variable, I always get the error "TypeError: unsupported operand type(s) for +: 'int' and 'str'" and I don't know how to fix it.

import random
import pandas as pd

operator_list = [
    "*",
    "/",
    "+",
    "-"
]

number1 = random.randint(1,100)
number2 = random.randint(1,100)
number3 = random.randint(1,100)
operator1 = random.choice(operator_list)
operator2 = random.choice(operator_list)

def ask():
    print("Was ist die Loesung fuer -> ", number1, operator1, number2, operator2, number3, "? \n")
    x = int(input("Deine Antwort > "))
    solution = pd.eval(number1 + operator1 + number2 + operator2 + number3)
    if x == solution:
        print("OK")

ask()

Solution

  • Cast your numbers to strings before contatenating, like str(number1) + operator1 + str(number2) + operator2 + str(number3) or pd.eval(f"{number1}{operator1}{number2}{operator2}{number3}")