validating an input not working properly (python)

Viewed 36
serviceType = ""

while serviceType != "R" or serviceType != "P":
    serviceType = input("Service type (R/P): ").upper()
    print(serviceType)
    if serviceType != "R" or serviceType != "P":
        print("Error: Invalid Entry \n")

Whenever I run the code above, the output, no matter what input I put into it, is the message "Error: Invalid Entry". Is there something I am doing wrong?

3 Answers

One of the conditions in your if condition is always True, therefore you always get the error.

Try this:

serviceType = ""

while serviceType != "R" and serviceType != "P":
    serviceType = input("Service type (R/P): ").upper()
    print(serviceType)
    if serviceType not in ["R", "P"]: # <- line changed
        print("Error: Invalid Entry \n")

Here's a more typical structure for this kind of pattern:

while True:
    serviceType = input('Service type (R/P): ').upper()
    if serviceType in ('R', 'P'):
        break # serviceType is either R or P
    print('Error: Invalid entry')

print(serviceType) # use the validated serviceType here

As per my understanding you want to build a program which takes service type from user and if the service type is not R or P, it return an invalid entry message and keep taking user input until user enter R or P. The following code works for me.

serviceType = ""

while serviceType != "R" and serviceType != "P":
    serviceType = input("Service type (R/P): ").upper()
    print(serviceType)
    if serviceType != "R" and serviceType != "P":
        print("Error: Invalid Entry \n")

Related