简体   繁体   English

输入验证为字符串和异常

[英]Input Validation to be a string and exception

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 请帮助我确定此验证的正确方法

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 ). 您的问题出在比较语句中, if x != 'Light' or 'Medium' or 'Heavy':实际上仅检查x != 'Light' ,然后检查字符串'Medium''Heavy'为true(之所以这样,是因为长度大于0的字符串的值为True )。

An easy way to check if a string matches any value from a list of strings, is to use set() . 检查字符串是否与字符串列表中的任何值匹配的一种简单方法是使用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. 由于集合几乎允许立即查找时间来查看值是否在集合内,而不必对每个值都检查x

Using a set to check if x matches any of the strings in state_1 : 使用集合检查xstate_1中的任何字符串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 provided a great explanation. 卡尔提供了很好的解释。 Your if statement is only checking to see if x != "Light" . 您的if语句仅检查if x != "Light" Since you're using or it will always pass as True because "Medium" and "Heavy" will always evaluate to True. 由于您正在使用or它将始终作为True传递,因为“中”和“重”将始终评估为True。

Something that may help out too is placing the statement in a while loop. 可能也有帮助的是将语句放入while循环中。

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. 这将连续循环直到输入有效的输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM