提问人:unleasehed 提问时间:11/9/2023 最后编辑:unleasehed 更新时间:11/9/2023 访问量:95
如何检查多个条件
how to check for multiple conditions
问:
我需要检查 1) x 和 y 是否为数字 2) 高于零 3) y 是否大于 x。如果没有,请在不符合要求的特定条件下显示错误消息并结束程序。
检查条件 2 和条件 3 后,错误消息不会打印出来。
if x.isnumeric() and y.isnumeric():
st="both x and y are numeric"
else:
print("One or more of your inputs are not numeric!")
num1 = int(x)
num2 = int(y)
if num1 >0 and num2 >0:
st1 = "both x and y are greater than zero"
else:
print("One or more of your inputs are not greater than zero!")
if num2 > num1:
st2 = "y greater than x"
else:
print("You did not enter a value of y that is greater than x")
我能得到的输出是
请输入x的值:3 请输入 y: 2 的值
不显示任何错误消息。
答:
2赞
Tanishq Chaudhary
11/9/2023
#1
基本逻辑:如果不满足条件,请提前返回,并出现错误。
def validate(x, y):
# try converting the x and y values to ints
try:
x = int(x)
y = int(y)
# if can't, return early
except:
return "One or more of your inputs are not numeric!"
# condition 2
if not (x > 0 and y > 0):
return "One or more of your inputs are not greater than zero!"
# condition 3
if not (y > x):
return "You did not enter a value of y that is greater than x"
# return nothing to show all is fine
return
# take the inputs
x = input("Please enter the value of x: ")
y = input("Please enter the value of y: ")
# get the error (if any)
error = validate(x, y)
if error:
print(error)
另一个解决方案,建立在代码之上:
x = input("Please enter the value of x: ")
y = input("Please enter the value of y: ")
if (
(x.startswith("-") and x[1:].isnumeric())
or x.isnumeric()
and (y.startswith("-") and y[1:].isnumeric())
or y.isnumeric()
):
num1 = int(x)
num2 = int(y)
if num1 > 0 and num2 > 0:
if num2 > num1:
st2 = "y greater than x"
else:
print("You did not enter a value of y that is greater than x")
else:
print("One or more of your inputs are not greater than zero!")
else:
print("One or more of your inputs are not numeric!")
PS:检查下面的评论,在某些情况下将返回true,但转换为将出错。isnumeric()
int()
评论
0赞
unleasehed
11/9/2023
谢谢。在进入条件 2 之前,我需要确保满足条件 1,在进入条件 3 之前满足条件 2。例如:如果不满足条件 2,我需要打印出错误消息并结束程序。
0赞
Tanishq Chaudhary
11/9/2023
我已经更新了解决方案!
0赞
unleasehed
11/9/2023
感谢您的帮助,可以通过 if else 循环来做到这一点吗?我还没有学习你提供的语法。
1赞
slothrop
11/9/2023
很酷,看起来很有效。您也可以在 Python>=3.9 中执行此操作。x.removeprefix('-').isnumeric()
1赞
Codist
11/9/2023
尝试将字符串转换为 int 并处理任何异常是更好的方法。例如,“4²”.isnumeric() == True but int(“4²”) 将引发 ValueError 异常
评论
x
y
if
if