提问人:Spec _ 提问时间:8/31/2023 更新时间:8/31/2023 访问量:29
Python > 检查一个 int 是否介于另外两个 int 之间
Python > Check an int is between two other int
问:
有问题的功能
def IsInRange(lr,hr,num):
return lr < num < hr
稍后,我们要求输入。
lr = floaterror('Provide your low range number, please: ')
hr = floaterror('Provide your high range number, please: ')
num = floaterror('Provide number to range find, please: ')
作业要求我们说它是否在范围内。所以,我做到了:
if IsInRange(lr, hr, num) == False:
print(num, "is not in range.")
elif IsInRange(lr, hr, num) == True:
print(num, "is in range.")
它有效。但是,让我们说,
lr = 1
hr = 1
num = 1
它说 1 不在范围内......我想创建一个例外,如果发生这种情况,它会打印“您的检查值不能等于您的范围”而不是“#不在范围内”。但我正在为此苦苦挣扎。我无法更改每个赋值返回的 IsInRange 函数。我确信这是其中的一部分,也是我编写的完整代码。我把它包括在下面。
def add(num1,num2):
return num1+num2
def sub(num1,num2):
return num1-num2
def mlt(num1,num2):
return num1*num2
def dvd(num1,num2):
return num1/num2
def IsInRange(lr,hr,num):
return lr < num < hr
end = True
print("Basic Math Function and In-Range Checker")
while end == True:
user = input('Please press Enter to continue with a simply mathtastical time, or "q" to quit. ')
if user == 'q':
print('You chose to avoid the math! Exiting!')
break
else:
keep_on_rolling = True
while keep_on_rolling:
#1st exception to catch invalid entries, that is, not integers.
#You'll be prompted to enter a correct value.
def floaterror(one):
while True:
try:
return float(input(one))
except ValueError:
print("Numbers only, please. Try again, with digits!")
#End 1st catch
num1 = floaterror('Give us your first number and press enter, please: ')
num2 = floaterror('Give us your second number and press enter, please: ')
lr = floaterror('Provide your low range number, please: ')
hr = floaterror('Provide your high range number, please: ')
num = floaterror('Provide number to range find, please: ')
print('The result of', num1, 'added with', num2, 'is', add(num1,num2))
print('The result of', num1, 'subtracting', num2, 'is', sub(num1,num2))
print('The result of', num1, 'multiplied by', num2, 'is', mlt(num1,num2))
#2nd error catch, tryig to destroy the universe by dividing by zero.
try:
print('The result of', num1, 'divided by', num2, 'is', (dvd(num1,num2)))
except ZeroDivisionError:
print("Uff da. We don't divide by zero in this house.")
#End 2nd catch.
else:
if IsInRange(lr, hr, num) == False:
print(num, "is not in range.")
elif IsInRange(lr, hr, num) == True:
print(num, "is in range.")
break
我没有保留任何失败的代码。 但是我尝试在 else 下添加一个异常:你不能这样做,我尝试了 if lr == num == hr 来打印我想要的答案。我尝试在有问题的函数出现的地方添加一个异常。我尝试在输入后添加异常。但是不断出现语法错误,或者如果没有错误,它似乎根本没有出现。我还尝试定义一个使用输入的新函数,但仍然一无所获。
答:
0赞
Лев Жаров
8/31/2023
#1
enter code here
if (not IsInRange(lr, hr, num)) and (not lr == hr and not num == hr):
print(num, "is not in range.")
elif IsInRange(lr, hr, num):
print(num, "is in range.")
else:
print("Your check value cannot equal your range.")
if your
lr = 1
num = 1
hr = 1
print - "Your check value cannot equal your range."
评论
if lr == num == hr: raise ValueError("<Error message>")