我对Python验证有问题。我想知道是否有一种简单的方法可以对两个输入号进行验证以检查一些事情:
如果输入是ints
如果两个输入都不等于某个数字,则它们无效。(例如,这意味着其中一个必须为5。因此a = 1
b = 4
,a = 3
b = 2
,a = 1
CC_5不起作用)
如果两个数字与所需的数字相同,则它将无法工作(例如,如果a = 5 b = 5将无法正常工作,因为5是所需的数字,但是a = 1 b = 5会起作用,因为5仅一次输入一次)。
while True:
a = input("Enter first input: ")
b = input("Enter second input: ")
try:
val = int(a)
val1 = int(a)
if val1 != 5 or val != 5:
print("I'm sorry but it must be a pos int and equal 5")
continue
break
except ValueError:
print("That's not an int")
这是我要做的,但我认为我可能会糟糕透露吗?
任何帮助!
谢谢。
逻辑xor
如果恰好一个a
和b
等于5,则应继续循环。这意味着您需要逻辑xor
。需要Parens避免将a
与5 ^ b
进行比较:
while True:
a = input("Enter first input: ")
b = input("Enter second input: ")
try:
a = int(a)
b = int(b)
if (a != 5) ^ (b != 5):
print("I'm sorry but it must be a pos int and equal 5")
continue
break
except ValueError:
print("That's not an int")
可能不是很可读。
计数5的
您可以计算等于5的INT数:
while True:
a = input("Enter first input: ")
b = input("Enter second input: ")
try:
a = int(a)
b = int(b)
count5 = [a, b].count(5)
if count5 == 1:
break
else:
print("Exactly one input should be equal to 5.")
except ValueError:
print("That's not an int")
如果要区分错误:
while True:
a = input("Enter first input: ")
b = input("Enter second input: ")
try:
a = int(a)
b = int(b)
count5 = [a, b].count(5)
if count5 == 2:
print("Inputs cannot both be equal to 5.")
elif count5 == 0:
print("At least one input should be equal to 5.")
else:
break
except ValueError:
print("That's not an int")
这是一个示例:
Enter first input: 3
Enter second input: 1
At least one input should be equal to 5.
Enter first input: 5
Enter second input: 5
Inputs cannot both be equal to 5.
Enter first input: 3
Enter second input: 5
逻辑...如果是真的,则断开,然后打印错误消息...
两件事...您想要逻辑独家或true true ^ true = false您不是存储b。您要打印的文字无法解释发生了什么。
while True:
a = input("Enter first input: ")
b = input("Enter second input: ")
try:
a = int(a) # like the readable code using a not val1...
b = int(b)
if (a != 5) ^ (b != 5): # added parens as suggested
break
else:
print("I'm sorry but it must be a pos int and equal 5")
continue
except ValueError:
print("That's not an int")
输出
Enter first input: 5
Enter second input: 5
I'm sorry but it must be a pos int and equal 5
Enter first input: 1
Enter second input: 5
runfile('...')
Enter first input: 5
Enter second input: 5
I'm sorry but it must be a pos int and equal 5
您可以使用:
(a == 5 and b != 5) or (a != 5 and b == 5)
或以下:
(a == 5) != (b == 5)
( !=
是bitwise xor等效的布尔)