Search code examples
pythonvalueerror

Why is ValueError showing up when I try to put in a float?


Why doesn't this work?

Traceback (most recent call last): File "/Users/ianyi/PycharmProjects/codehomework/calculator.py", line 23, in calnum1 = iof(input("Put the first number here: \n")) File "/Users/ianyi/PycharmProjects/codehomework/calculator.py", line 4, in iof if y != True: number = int(number) ValueError: invalid literal for int() with base 10: '123.123'

def iof(number):
    y = isinstance(number, float)
    if y != True: number = int(number)
    else: number = float(number)
    return number


def calculation(x:int, y:int, operator:str):
    if operator in ["+"]: sum = iof(x + y)
    elif operator in ["-"]: sum = iof(x - y)
    elif operator in ["*"]: sum = iof(x * y)
    elif operator in ["/"]: sum = iof(x / y)
    elif operator in ["%"]: sum = iof(100 * x / y)
    elif operator in ["^"]: sum = iof(x ** y)
    elif operator in ["√"]: sum = x ** 0.5
    return sum

mathmatical, calnum2 = [None, "+", "-", "*", "/", "%", "^", "√"], None
print("\nHello. This is a Calculator.")
for i in range(1):
    if calnum2 == None:
        calnum1 = iof(input("Put the first number here: \n"))
    choice = str(input(f'''Which mathmatical symbol?
    (+ = 1, - = 2, * = 3, / = 4)
    (% = 5, ^ = 6, √ = 7)\n'''))
    if choice == "x": choice = "*"
    if choice.isnumeric(): choice = mathmatical[int(choice)]
    if choice == "%": calnum2 = iof(input(f"{calnum1}% of? "))
    elif choice == "^": calnum2 = iof(input(f"{calnum1} raised to the power of: "))
    elif choice == "√": pass
    elif choice not in ["√", "%"]: calnum2 = iof(input(f"{calnum1} {choice} "))
    else: raise ValueError("um put the right numbers next time")
    sum = calculation(calnum1, calnum2, choice)
    print(sum)

Solution

  • The reason is because input returns str type and when you do isinstance(number, float), it will always be False. And then, you try to convert a string that is like a float to an int which makes it throw an error.