mardi 12 février 2019

python if-else recursive function returns undesired value

I'm facing a conditional logic problem here.

I want a value from user, but it should only be confined to either

'ABC','DEF' or'XYZ'

If not provided with one of the above, program should give the user another chance to enter until it gets the input only from it's expected values

My snippet is as follows:-

def foo():
    inp_val=raw_input("Enter value\n>> ")
    if inp_val.upper() not in {'ABC','DEF','XYZ'}:
        print("Invalid Input")
        foo()
    return inp_val
inp = foo()

Output

Enter value
>> 42342d*@r2
Invalid Input
Enter value
>> abc

Checking inp in python console:-

>> inp
ABC #(Expected)
42342d*@r2 #(Actual)

Why is this happening?

I tried the reverse logic too:-

def bar():
    inp_val=raw_input("Enter value\n>> ")
    if inp_val.upper() in {'ABC','DEF','XYZ'}:
        return inp_val
    else:
        print("invalid input")
        bar()
inp = bar()

Output:

Enter value
>> 42342d*@r2
Invalid Input
Enter value
>> abc

In console:

>> inp
ABC #Expected
    #(Actual)

How do I get the actual value?

Aucun commentaire:

Enregistrer un commentaire