-2

Hi I am struggling to understand exactly what recursion is, It is a requirement of the program I am writing(a snake game) and I cannot find a clear definition of what is classified as recursion. Could someone tell me if the code below is an example of this?

while True: #recieve input player_name = input("Enter a name between 0 and 20 characters: ") #if length is within boundaries the loop is stopped if len(player_name) > 0 and len(player_name) <= 20: break #if the name is outwith the boundaries a message is printed and the loop restarts print("Too long/short, try again.")

BoJ
  • 25
  • 8
  • No this isn't recursion; you need something lie a function that calls itself for recursion – Chris_Rands Mar 30 '17 at 10:15
  • No, this is not an example of recursion. Recursion requires a function calling itself. – Martijn Pieters Mar 30 '17 at 10:15
  • while loop is not recursion. – Kamran Mar 30 '17 at 10:15
  • Recursion is just having a function recall itself WITHIN the function, example `def something(): print('a'); something()` . – Wright Mar 30 '17 at 10:15
  • If you're required to write it, it must be for some sort of homework or something, and I bet there's some kind of instructional material that accompanies it - it should contain an explanation of recursion. – TigerhawkT3 Mar 30 '17 at 10:17
  • Search in google, may be you can find some examples to write recursive function. For e.g., look at here https://www.programiz.com/python-programming/recursion – manvi77 Mar 30 '17 at 10:17

2 Answers2

0

There are two types of looping:

1. Iteration:

Here you use for(), while(), do-while() loops to repeat a set of statements

2. Recursion:

Here you call a function which calls the same function from within.

Example:

def factorial(n):
if n == 0:
    return 1
else:
    return n * factorial(n - 1)

Here the function factorial() is calling itself until value of n becomes 0. The statement n==0 is called base/terminal condition which terminates the recursion.

Community
  • 1
  • 1
Arvindsinc2
  • 716
  • 7
  • 18
0

You have recursion when you define something in terms of itself. For example, the following definition of "walk staircase" is recursive:

"walk staircase" :=

if there's a step left: take a step and "walk staircase"
else if there's no step left: stop

In programming recursion is most often seen in the form of recursive function definitions, that is functions that call themselves.

Here's an example function that computes the sum 1 + 2 + 3 + ... + n for some number n > 0.

>>> def cumsum(n):
...     if n == 1:
...         return n
...     else:
...         return n + cumsum(n - 1)
... 
>>> cumsum(5)
15
>>> 1+2+3+4+5
15

What makes this function recursive is the fact that cumsum is used in the definition on cumsum itself.

Since you don't have any recursive calls in your code, it is not an example of recursion. Your while True loop is an example of iteration.

Community
  • 1
  • 1
timgeb
  • 76,762
  • 20
  • 123
  • 145