0
x = input("Enter state 1")
y = input("Enter state 2")
z = input("Enter state 3")

# The three states are strings among a list

For example:
    state_1 = ['Light', 'Medium', 'Heavy']
    state_2 = ['Small', 'Medium', 'Large']
    state_3 = ['Blue', 'Red', 'Black']

If x != 'Light' or 'Medium' or 'Heavy':
    print("Wrong input")
else:
    x = pre_defined_function(x) #let's say

# Same to be done with other states, output given only if all three states are entered correctly

I have tried doing try and except, but couldn't get it:

Please help me in identifying the correct method for this validation

  • 3
    Possible duplicate of [Why does \`a == b or c or d\` always evaluate to True?](https://stackoverflow.com/questions/20002503/why-does-a-b-or-c-or-d-always-evaluate-to-true) – Thierry Lathuille Oct 15 '18 at 17:56
  • You are only doing a comparison of x against 'Light'. You have to check to see if x matches any of the strings in `state_1` Also, it is better to store your state list in a `set()` if you are only using it to compare your `x` string against. – Karl Oct 15 '18 at 17:56
  • @Karl The OP doesn't compare anything, the condition always evaluates to `True`, see the duplicate. – Thierry Lathuille Oct 15 '18 at 17:58
  • Perfect, got it...thanks people – Khurram Oct 15 '18 at 18:03

2 Answers2

0

Your problem is in the comparsion statement if x != 'Light' or 'Medium' or 'Heavy': which actually is only doing a check for x != 'Light' and then whether or not the string 'Medium' or 'Heavy' are true (which they will because strings greater then length 0 evaluate to True).

An easy way to check if a string matches any value from a list of strings, is to use set(). Since a set allows almost instant lookup time to see if a value is inside the set, instead of having to check x against every value.

Using a set to check if x matches any of the strings in state_1:

x = input("Enter state 1")
y = input("Enter state 2")
z = input("Enter state 3")

# Store states in sets
state_1 = {'Light', 'Medium', 'Heavy'}
state_2 = {'Small', 'Medium', 'Large'}
state_3 = {'Blue', 'Red', 'Black'}

if x not in state_1:
    print("Wrong input")
else:
    x = pre_defined_function(x)
Karl
  • 1,664
  • 2
  • 12
  • 19
0

Karl provided a great explanation. Your if statement is only checking to see if x != "Light". Since you're using or it will always pass as True because "Medium" and "Heavy" will always evaluate to True.

Something that may help out too is placing the statement in a while loop.

while x not in state_1:
    print("Wrong input")
    x = input("Enter state 1: ")
else:
    x = pre_defined_function(x)

this will loop continuously until valid input is entered.

Jenkins
  • 37
  • 11