validating an input not working properly (python)

Question:

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?

Asked By: temp116055

||

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")
Answered By: petezurich

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")

Answered By: Anchal

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
Answered By: Stuart
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.