Home > OS >  Issue when trying to add user validation
Issue when trying to add user validation

Time:11-08

Trying to add validation to user input.

So the code is:

print ('Does this service require an SFP Module? (y/n): ')
while True:
    sfpreq = input()
    if sfpreq != 'y' or 'n':
        print("You must enter either y or n")
        continue
    else:
        break

So even when the user enters 'n' it returns the "print("You must enter either y or n")" and continues the loop.

I have tried setting the variabl manually to and also tried another convention I found on realpython and also removed the if statement from the while loop:

sfpreq = "n"
if sfpreq != 'y' or sfpreq != 'n':
   print("You must enter either y or n")
else:
   print("Test")

Again it just returns:

admin@MacBook-Pro Learning Folder % python3 test22.py
You must enter either y or n

Am I just missing something very fundamental here?

CodePudding user response:

Problem with the logic

sfpreq = "n"
if sfpreq != 'y' or sfpreq != 'n':
   print("You must enter either y or n")
else:
   print("Test")

Here, when you enter the if loop, sfpreq != 'y' is validated as True and sfpreq != 'n' is validated as False.
Now True OR False statement in boolean algebra equates to True. So, the if loop gets executed and You must enter either y or n is printed. See, more about boolean algebra here

A better solution

sfpreq = "n"
if sfpreq not in {"y","n"}:
   print("You must enter either y or n")
else:
   print("Test")

So, here we are checking if y or n is not there in the set {"y","n"}. As in this case, sfpreq is there in that set so,the else statement gets executed.

  • Related