-1

So i have created a function and inside i had put an if command, to check for the answer, but when the answer is invalid i want to repeat the function so it asks again. It is supposed to ask for either input A or B but when for eg i put C it should call back on the function and repeat. How do i make it re-ask for the input? This is what i tried:

def function():
    data = input("A/B")
    if data == "A":
        print("A")
    elif data == "B":
        print("B")
    else:
        function()   #<-----problem here
daniel
  • 13
  • 3

4 Answers4

1

The sample code you posted works the way you have described you want it to. For more complicated functions involving returning values, I would recommend writing and calling it this way:

def function():
    data = input("A/B")
    if data == "A":
        return("A")
    elif data == "B":
        return("B")
    else:
        return(function())

print(function())

What this means:

return(function())

is that the function will return the result of the next call of the function. That next call may in turn return the result of the next call of the function. This concept is a major part of recursion which may be worth looking into for future use.

Simon
  • 855
  • 9
  • 24
0

try while loop:

ans="C"
while ans!="B" and ans!="A":
    ans=input("A/B")   
print(ans) 
Umbrelluck
  • 33
  • 1
  • 6
  • But your way is also correct...(I have tried to run it here: http://www.pythontutor.com/visualize.html#mode=display) – Umbrelluck Jul 20 '18 at 17:29
  • 1
    Don't initialize `ans` to `"C"`, if he wants to add `C` as a valid value in the future, this can lead to problems (use empty string for initialization `ans=""`). Also, with your code, inputting `a` would ask for input again which is probably not the wanted behavior. Use `while ans.upper() not in {"A","B"}:` instead. – scharette Jul 20 '18 at 17:30
0

This is a Recursive function. For building one just call with return:

Else:
    return function()

You can insert the function in a var:

var = function()

And call it:

return var
Wolfeius
  • 303
  • 2
  • 14
0

To solve this problem you don't need to call the function again as if the user inputs wrong answer too many time (some big number I forgot) it will reach the stack limit. To solve your problem you can simple use a while loop. The code below shows how this can be done:

def function():
    while True: 
        data = input("A/B") 
        if data == "A": 
            print("A") 
            return
        elif data == "B": 
            print("B")
            return

As you can see from the code above, we are using a infinite while loop which will keep looping untill user inputs 'A' or a 'B'. If you don't know the keyword return can be used to exist out of a function before hand.

Also I was using my phone to answer this question so if I made any mistakes sorry about that.

Kamil B
  • 95
  • 1
  • 4