lundi 28 septembre 2020

could not convert string to float: ' ' [closed]

ive looked at other questions and they seem to have to do with text more than a space (''). my error im getting is

could not convert string to float

I'm confused on how to make the previous answer equal to num1 when num2 doesnt get an answer. so lets say you do addition, 5+5, now prevAnswer is 10, when doing lets say subtraction next and make num1 = 5, it will calculate 5-10 instead of 10-5. i have no idea what to try and play around with values and position of code because when i do that it just creates more errors.

def isExitCommand(userInput):
return (userInput == 'exit' or userInput == 'stop' or userInput == 'Exit' or userInput == 'EXIT' or userInput ==
        'Stop' or userInput == 'STOP')


def calc_exponent(num, pow):
result = 1
for i in range(pow):
    result = result * num
return result


while True:
operator = str(input("Would you like to add(+), subtract(-), multiply(*), divide(/) or use exponents(**)? "))

if isExitCommand(operator):
    break

num1 = input("Enter number 1: ")
if isExitCommand(num1):
    break
else:
    num1 = float(num1)

num2 = input("Enter number 2: ")
if num2 == '':
    num1 = num2
    num1 = prevAnswer

if isExitCommand(num2):
    break

else:
    num2 = float(num2)

    if operator == 'add' or operator == '+':
        answer = num1 + num2
        print(num1, '+', num2, '=', answer)

    elif operator == 'subtract' or operator == '-':
        answer = num1 - num2
        print(num1, '-', num2, '=', answer)

    elif operator == 'multiply' or operator == '*':
        answer = num1 * num2
        print(num1, '*', num2, '=', answer)

    elif operator == 'divide' or operator == '/':
        answer = num1 / num2
        print(num1, '/', num2, '=', answer)

    elif operator == 'exponents' or operator == '**':
        num1 = int(num1)
        num2 = int(num2)
        answer = calc_exponent(num1, num2)
        print(num1, '**', num2, '=', answer)
    else:
        print('Please type a valid operator...')

    prevAnswer = answer

print('Program has exited due to user input.')

Aucun commentaire:

Enregistrer un commentaire