M
M
max_1O2021-06-26 09:58:08
Python
max_1O, 2021-06-26 09:58:08

How to prevent infinite/long loop/recursion when solving a math problem in python?

Hello. I am writing a calculator in python tkinter. When you need to raise a number to a large power, like this - 5 ^ 55555, the program, as I understand it, will go into a long loop or recursion and hang. How will this be prevented? Thanks in advance. I will fix the condition script with exponentiation below, if necessary. The logic of the program is as follows: the user first dials a number from the buttons of the program, then selects an operand (+, -, *, /, ^) then another number and finally an equal sign to see the result

elif operation == "^":
        # command of power operand button
        result = int(first_num ** last_num)
        # there are 3 lbls, 1st on top for first num, 2nd on middle for operand, 3rd on bottom for last num
        # here when user push "=" button, 2nd and 3rd lbls will be cleared, instead of 1st num on 1st lbl there will be result
        operation_label.configure(text="")
        last_num_label.configure(text="")
        result_text = f"{first_num} ^ {last_num} = {result}"
        index = str(result_text).index("=") # this var will be used to adapt nums and symbols
        if len(result_text) > 32 and len(result_text) < 64: # lbls width is 33, height is 3, this clause for 2 lined result_text
            result_text = result_text[:index] + "\n" + result_text[index:]
        elif len(result_text) > 64 and len(result_text) < 96: # this for 3 lined result_text
            result_text = str(result_text[:index]) + "\n" + str(result_text[index:index+4]) + "e" + str(len(result_text[index+4:]))
        first_num_label.configure(text=str(result_text)) # print result on first lbl

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dmshar, 2021-06-26
@dmshar

I don't understand what's not working for you. We write an elementary script:

n = 5**55555
print(n)
ns=str(n)
len(ns)

The code runs almost instantly.
I won’t write here what the result is, but here is the last output that says how many digits in your number I will give: 38832.
So you don’t need to prevent an error, but simply limit the numbers you work with.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question