'How to fix this function? Results in Error
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
Solution 1:[1]
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:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
