calling a function recursively for user input

  • Last Update :
  • Techknowledgy :

The way you do this is simple: while there is invalid input, prompt again. I'm using a modified version of this in the vein of the "while True break" style; it accomplishes the same goal. We loop indefinitely, and if the condition we want is valid, we return; otherwise, we prompt for input and loop again.

def player1():
   while True:
   x = raw_input("please select: Rock(r)/Paper(p)/Scissors(s): ").lower()
if x == 'r'
or x == 'p'
or x == 's'
or x == 'rock'
or x == 'paper'
or x == 'scissors':
   return x[0]
else:
   print "Error - wrong input!"

As an alternative to that if statement, there is a slightly more clean way to express it via the in operator.

if x in ('r', 'p', 's', 'rock', 'paper', 'scissors'):

If you absolutely must, and again I strongly advise against doing this, then you simply have to return from your iterative case.

def player1():
   x = (raw_input("please select: Rock(r)/Paper(p)/Scissors(s): ")).lower()
if x == 'r'
or x == 'p'
or x == 's'
or x == 'rock'
or x == 'paper'
or x == 'scissors':
   return x[0]
else:
   print "Error - wrong input!"
return player1() #I know I can run a While loop, but I need to run it this way.

print(player1())

An improved version of @Makoto's example:

def player1():
   x = raw_input("please select: Rock(r)/Paper(p)/Scissors(s): ").lower()
while True:
   if x in ['r', 'p', 's', 'rock', 'paper', 'scissors']:
   return x[0]
else:
   print "Error - wrong input!"
x = raw_input("please select: Rock(r)/Paper(p)/Scissors(s): ").lower()

Example: (reusable, non-recursion:)

#!/usr/bin/env python


from __future__
import print_function # For Python 2 / 3 compat

try:
input = raw_input # For Python 2 / 3 compat
except NameError:
   pass

def prompt(prompt = "Enter: ", valid = None):
   s = input(prompt)
while valid and s not in valid:
   print("Invalid input! Please try again. Valid inputs are {0:s}".format(" ".join(valid)))
s = input(prompt)
return s

x = prompt("Enter action ([r]ock, [p]aper, [s]cissors): ", ["r", "p", "s", "rock", "paper", "scissors"])

Demo:

$ python foo.py
Enter action([r] ock, [p] aper, [s] cissors): a
Invalid input!Please
try again.Valid inputs are r p s rock paper scissors
Enter action([r] ock, [p] aper, [s] cissors): foo
Invalid input!Please
try again.Valid inputs are r p s rock paper scissors
Enter action([r] ock, [p] aper, [s] cissors): r

$ python foo.py
Enter action([r] ock, [p] aper, [s] cissors): a
Invalid input!Please
try again.Valid inputs are r p s rock paper scissors
Enter action([r] ock, [p] aper, [s] cissors): foo
Invalid input!Please
try again.Valid inputs are r p s rock paper scissors
Enter action([r] ock, [p] aper, [s] cissors): rock

I'm adding this answer for completeness sake, as you do ask for a recursive solution. Here is my solution that is closest to yours:

def player1():
   x = (raw_input("please select: Rock(r)/Paper(p)/Scissors(s): ")).lower()
if x == 'r'
or x == 'p'
or x == 's'
or x == 'rock'
or x == 'paper'
or x == 'scissors':
   return x[0]
else:
   print "Error - wrong input!"
return player1()

As you can see, all you've forgotten is a return statement. A more readable way might be:

def player1():
   playerInput = None
while playerInput not in ('r', 'p', 's', 'rock', 'paper', 'scissors'):
   if playerInput is not None:
   print("Error - wrong input!")
playerInput = raw_input("please select: Rock(r)/Paper(p)/Scissors(s)").lower()
return playerInput[0]

Suggestion : 2

Last Updated : 03 Aug, 2022

What is the base condition in recursion? 
In the recursive program, the solution to the base case is provided and the solution to the bigger problem is expressed in terms of smaller problems. 
 

int fact(int n) {
   if (n < = 1) // base case
      return 1;
   else
      return n * fact(n - 1);
}

Why Stack Overflow error occurs in recursion? 
If the base case is not reached or not defined, then the stack overflow problem may arise. Let us take an example to understand this.

int fact(int n) {
   // wrong base case (it may cause
   // stack overflow).
   if (n == 100)
      return 1;

   else
      return n * fact(n - 1);
}

What is the difference between direct and indirect recursion? 
A function fun is called direct recursive if it calls the same function fun. A function fun is called indirect recursive if it calls another function say fun_new and fun_new calls fun directly or indirectly. The difference between direct and indirect recursion has been illustrated in Table 1. 

// An example of direct recursion
void directRecFun() {
   // Some code....

   directRecFun();

   // Some code...
}

// An example of indirect recursion
void indirectRecFun1() {
   // Some code...

   indirectRecFun2();

   // Some code...
}
void indirectRecFun2() {
   // Some code...

   indirectRecFun1();

   // Some code...
}

Now, let’s discuss a few practical problems which can be solved by using recursion and understand its basic working. For basic understanding please read the following articles. 
Basic understanding of Recursion.
Problem 1: Write a program and recurrence relation to find the Fibonacci series of n where n>2 . 
Mathematical Equation:  

n
if n == 0, n == 1;
fib(n) = fib(n - 1) + fib(n - 2) otherwise;

Recurrence Relation: 

T(n) = T(n - 1) + T(n - 2) + O(1)

Fibonacci series of 5 numbers is: 0 1 1 2 3

factorial of 5 is: 120

Suggestion : 3

In this tutorial, you will learn to create a recursive function (a function that calls itself).,In the above example, factorial() is a recursive function as it calls itself.,Every recursive function must have a base condition that stops the recursion or else the function calls itself infinitely.,When we call this function with a positive integer, it will recursively call itself by decreasing the number.

Example of a recursive function

def factorial(x):
   ""
"This is a recursive function
to find the factorial of an integer ""
"

if x == 1:
   return 1
else:
   return (x * factorial(x - 1))

num = 3
print("The factorial of", num, "is", factorial(num))

Output

The factorial of 3 is 6

Each function multiplies the number with the factorial of the number below it until it is equal to one. This recursive call can be explained in the following steps.

factorial(3) # 1 st call with 3
3 * factorial(2) # 2n d call with 2
3 * 2 * factorial(1) # 3 rd call with 1
3 * 2 * 1 #
return from 3 rd call as number = 1
3 * 2 #
return from 2n d call
6 #
return from 1 st call

Suggestion : 4

© 2007—2022  Ilya Kantor

pow(2, 2) = 4
pow(2, 3) = 8
pow(2, 4) = 16
function pow(x, n) {
   let result = 1;

   // multiply result by x n times in the loop
   for (let i = 0; i < n; i++) {
      result *= x;
   }

   return result;
}

alert(pow(2, 3)); // 8
function pow(x, n) {
   if (n == 1) {
      return x;
   } else {
      return x * pow(x, n - 1);
   }
}

alert(pow(2, 3)); // 8
              if n == 1 = x /
                 pow(x, n) = \
                 else = x * pow(x, n - 1)
function pow(x, n) {
   return (n == 1) ? x : (x * pow(x, n - 1));
}
function pow(x, n) {
   if (n == 1) {
      return x;
   } else {
      return x * pow(x, n - 1);
   }
}

alert(pow(2, 3));

Suggestion : 5

Therefore, we should make sure that every function call eventually hits the base case in order to avoid infinite recursion. Once we hit it, we can start taking function calls off the top of the stack and returning from them. , This idea can seem paradoxical when you're just getting started, so we'll go through an example of how the computer really handles it in order to explain away the paradox. The upshot is that we have the same function, yes, but it is one call of the function that in turn makes a separate call to the same function, but with different arguments. , In other words, it is the mechanism that stops this process of ever more recursive calls and an ever growing stack of function calls waiting on the return of other function calls. , The key take-away from this is that there is not contradiction in having multiple active calls to a function (like factorial). In particular:

int factorial(int n) {
   if (n == 1)
      return 1;
   else
      return n * factorial(n - 1);
}
int main() {
   int k = 4;
   int f = factorial(4);
   cout << f << endl;
   return 0;
}
1._
int factorial(int n) {
   if (n == 1)
      return 1;
   else
      return n * factorial(n - 1);
}
2._
int main() {
   int k = 4;
   int f = factorial(4);
   cout << f << endl;
   return 0;
}

Consider this function:

int f(int k) {
   int a = k * k;
   int b = f(k + 1);
   return a + b;
}
Q.
Answer: When k is zero.

Answer:

Yes.No matter how big the number in our initial call to sum, we
must eventually reach our base
case, because the argument to our recursive
calls keep getting smaller and smaller, until they
finally reach zero.
int sum(int k) {
   int p = 0, ans = 0;

   if (k == 0)
      return 0;

   p = sum(k - 1);
   ans = p + k;

   return ans;
}
Q.
Answer: When k is zero.

Answer:

Yes.No matter how big the number in our initial call to sum, we
must eventually reach our base
case, because the argument to our recursive
calls keep getting smaller and smaller, until they
finally reach zero.

For this problem, I'm asking what values of k are particularly easy to give the answer to? Of course, since we're assuming that k is positive, the easiest value for k is 1. If k is one we can just immediately return 1. So that gives us our base case.

// Base case
if (k == 1)
   return 1;

Suggestion : 6

By Bernd Klein. Last modified: 01 Feb 2022., 17 Oct 2022 to 21 Oct 2022

def factorial(n):
   if n == 0:
   return 1
else:
   return n * factorial(n - 1)
def factorial(n):
   print("factorial has been called with n = " + str(n))
if n == 1:
   return 1
else:
   res = n * factorial(n - 1)
print("intermediate result for ", n, " * factorial(", n - 1, "): ", res)
return res

print(factorial(5))
factorial has been called with n = 5
factorial has been called with n = 4
factorial has been called with n = 3
factorial has been called with n = 2
factorial has been called with n = 1
intermediate result
for 2 * factorial(1): 2
intermediate result
for 3 * factorial(2): 6
intermediate result
for 4 * factorial(3): 24
intermediate result
for 5 * factorial(4): 120
120
def iterative_factorial(n):
   result = 1
for i in range(2, n + 1):
   result *= i
return result

for i in range(5):
   print(i, iterative_factorial(i))
0 1
1 1
2 2
3 6
4 24
def fib(n):
   if n == 0:
   return 0
elif n == 1:
   return 1
else:
   return fib(n - 1) + fib(n - 2)

Suggestion : 7

Your sum is correct, just do not use sum as function name. You just need to make user input function, look code snippets section for examples.,Do not select code snippet from type of article but type for example to search box input snippet and to Forum Python. The limiting from menu to Code Snippet does not work same time with Forum selected.,I'm trying to design a function that accepts a list of numbers as an argument. I can get the program working when i put a list into the programme but I can't figure out how to allow a user to enter a series. What i've got so far is below. Any help would be appreciated., Reach out to all the awesome people in our software development community by starting your own topic. We equally welcome both specific questions as well as open-ended discussions.

I'm trying to design a function that accepts a list of numbers as an argument. I can get the program working when i put a list into the programme but I can't figure out how to allow a user to enter a series. What i've got so far is below. Any help would be appreciated.

def main():

   list = [2, 4, 6, 8, 9, 12, 6, 10, 9, 6, 7]

my_sum = sum(list)

# Display the sum
print "The sum of numbers in the list is", my_sum

def sum(list):
   if list == []:
   return 0
else:
   return list[0] + sum(list[1: ])

main()

For fun here is recursive function producing sum of numbers without remembering the numbers:

def my_sum():
   n = raw_input('Next number or empty to finish: ')
return (float(n) + my_sum()) if n
else 0

s = my_sum()
print "The sum of numbers is", s

Avoid using names like list and sum since they are internal to Python. Something like this will work:

mylist = []
prompt = "%d) enter an integer (-99 to stop): "
for k in range(1000):
   x = int(raw_input(prompt % (k + 1)))
if x == -99:
   break
mylist.append(x)

print(mylist) # test

''
'
1) enter an integer(-99 to stop): 4
2) enter an integer(-99 to stop): 66
3) enter an integer(-99 to stop): 7
4) enter an integer(-99 to stop): 12
5) enter an integer(-99 to stop): -99[4, 66, 7, 12]

''
'

For fun here is recursive function producing sum of numbers without remembering the numbers:

def my_sum():
   n = raw_input('Next number or empty to finish: ')
return (float(n) + my_sum()) if n
else 0

s = my_sum()
print "The sum of numbers is", s