Issue
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)
Solution
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)
Answered By - Ron Serruya
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.