-2

I was trying to make a progam that reads "raiz"(means square root) and writes ""(1/2)**" Just wanted to have 24 as result, but occurs an error saying that i can't convert "(1/2)**576" into a float/int.

def main(args):
    a = input("Qual expressão quer simplificar? \n")
    i = 0
    x = ""
    while i < len(a):
        c = a[i]
        r = a[i: i + 5]
        b = a[i: i + 4]
        g = a[i: i + 8]
        h = a[i: i + 7]
        if g == "raiz de ":
            c = "(1/2)**"
            i += 7
        elif h == "raiz de":
            c = "(1/2)**"
            i += 6
        elif b == "raiz":
            c = "(1/2)**"
            i += 3
        if r == "vezes":
            c= "*"
            i += 4
        i += 1
        x += c
    z = float(x)
    print(z)


    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))
    enter code here
  • I think its helpful: https://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string – Masoud Jul 06 '19 at 23:41

1 Answers1

1

If the question is why are you receiving this error, it is because of the line z = float(x). You are passing in x, which is a string with non-decimal characters. In one case you are trying to convert "(1/2)**" into a float.

float() takes a number or a string, but the string must be digits.

float('(1/2)**')
# ValueError: could not convert string to float: (1/2)**

float('2.5')
# 2.5

float(4/2)
# 2.0
8888
  • 1,534
  • 1
  • 14
  • 30