Home > database >  How to fix this function? Results in Error
How to fix this function? Results in Error

Time:01-26

I tried adding a function to this code, it is supposed to display a the inputted sentence in reverse and I thought I had no errors but it is always resulting in error.

def reversed(text):
    # display the sentence in reverse 
    for i in reversed(range(len(text))): 
        print(text[i],end="") 
    print() 

text=input("Enter a sentence\n") 

while True: 
    # display the title 
    print() 
    print() 

    print("The Word Food Processor") 
    print("=======================") 
    print() 


    # display the menu 
    print("Choose an option:") 
    print("1 - display sentence in reverse order") 


    # error trap user's choice 
    while True: 

        choice=int(input("Enter choice: ")) 
        if (choice>=1 and choice <=6): 
            break 
        print("That is not a valid choice") 

    if (choice==1):
       reversed(text)

It is always ending in the following error. I am trying to use the function but it won't work in a function. I had it out of one and it worked, but my teacher wanted for it to be a in function.

Traceback (most recent call last):
 File "main.py", line 47, <module> reversed(text)
 File "main.py", line 12, <module> reversed
  for i in reversed(range(len(text))):
 File "main.py", line 12, <module> reversed
  for i in reversed(range(len(text))):
 File "main.py", line 12, <module> reversed
  for i in reversed(range(len(text))):
[Previous line repeated 995 more times]
RecursionError: maximum recursion depth exceeded in comparison

CodePudding user response:

Currently you're experiencing conflicting function names. There is a built in function of Python, reversed, which takes a container and reverses it's contents.

You use this function in your custom made function, also named reversed, but Python thinks you're trying to call your custom made function instead of the built in one.

To solve, name your custom function something else.

CodePudding user response:

Python has a recursion limit, it prevents a function from calling on itself and by default i think that recursion limit is 1000

Though you can change its recursion limit using

import sys
sys.setrecursionlimit(2000)

Though you'll wanna be careful with setting new recursion limits

However the reason it's doing that is cause you're calling the function from inside the function which will make it loop indefinitely.

def reversed(text):
    # display the sentence in reverse 
    for i in reversed(range(len(text))):

Because the function itself and the function in the loop being called share the same name, its essentially the same as using while True:

  •  Tags:  
  • Related