-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.")

6
  • No this isn't recursion; you need something lie a function that calls itself for recursion Commented Mar 30, 2017 at 10:15
  • No, this is not an example of recursion. Recursion requires a function calling itself. Commented Mar 30, 2017 at 10:15
  • while loop is not recursion. Commented Mar 30, 2017 at 10:15
  • Recursion is just having a function recall itself WITHIN the function, example def something(): print('a'); something() . Commented Mar 30, 2017 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. Commented Mar 30, 2017 at 10:17

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.