0

Hi I was trying to check the inputs for Rock Papers Scissors game. Check function is supposed to return the input in lower case if the input is valid. Else new input to be taken and invoke the same check function. The code is working fine if the input is (R,P,S,r,p,s)

If first input not valid, new input is taken and checked till valid input is provided. However the function is returning None if the first input is wrong.

Simple check (print statement) before the return indicates that the value is being taken appropriately.

def check(x):
    x=str.lower(x)
    valid_input=['r','p','s']
    print("Input value: "+str(x)) #simple check before if-else
    if x in valid_input:
        return x                 #valid input, return x
    else:
        print("Wrong Input!!!")  
        x=input("Enter r/p/s:")  #taking new input
        check(x)                 #checking if the new input is valid
x=input("Enter choice: ")       #Input value
x=check(x)                      #Call check fucntion 
print(x)

Enter choice: A Output:

Input value: a

Wrong Input!!!

Enter r/p/s:s

Input value: s

None

The solution when i enter A which is invalid is as above. The function is taking new input and in sample check just before return statement also displays the new value (Input value: s)

Abhijith
  • 48
  • 4
  • You might want to read "[Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response)". Recursion is not the way to go here. – Matthias Sep 09 '19 at 07:44
  • Remember that recursion means that the entire stack of calling functions are each returning their own output. In your case, your `else` block isn't returning anything, so the function returns None by default if that else block executes. – Michael Sep 09 '19 at 07:45

1 Answers1

0

You need to return the value from the recursion

def check(x):
    x=str.lower(x)
    valid_input=['r','p','s']
    print("Input value: "+str(x)) #simple check before if-else
    if x in valid_input:
        return x                 #valid input, return x
    else:
        print("Wrong Input!!!")  
        x=input("Enter r/p/s:")  #taking new input
    ->  return check(x)          #checking if the new input is valid
x=input("Enter choice: ")       #Input value
x=check(x)                      #Call check fucntion 
print(x)
Ron Serruya
  • 3,988
  • 1
  • 16
  • 26