Python - calling a function from within

The code that I already have is for a bot that receives a mathematical expression and evaluates it. Right now I have this multiplication, division, subtraction and addition. The problem is that I want to build support for parentheses and parentheses in parentheses. For this to happen, I need to run the code that I wrote for expressions without parentheses for the expression inside the brackets. I was going to check "(" and add the expression inside it to the list until it reaches ")" , unless it reaches another "(" , in which case I would create a list inside the list. I would subtract, multiply and divide, and then the numbers that are left, I just add together.

So is it possible to call a definition / function from itself?

+5
source share
2 answers

Yes, this is a fundamental programming method called recursion , and it is often used in well-described parsing scripts.

Just make sure you have the base case, so that the recursion ends when you reach the bottom layer and you cannot endlessly call yourself.

(Also notice the easter egg when you google recursion: "Did you mean recursion?")

+8
source

Yes, since @Daniel Roseman said this is a fundamental programming method called recursion.

im gives you an example of this in python

 def recur_factorial(n): """Function to return the factorial of a number using recursion""" if n == 1: return n else: return n*recur_factorial(n-1) 
+1
source

Source: https://habr.com/ru/post/1215436/


All Articles