所以我需要编写一个程序来请求一个从 1 到 10 的整数并计算它的倒数。
while True:
try:
integer = int(input("Enter an integer between 1 to 10 "))
parameter = integer in range(1,10)
equation = 1/integer
print(equation)
break
except ValueError:
print("not int")
回答1
您可以使用 https://stackoverflow.com/questions/5142418/what-is-the-use-of-assert-in-python 来检查数字是否在 1 和 10 的范围内。另外,在我看来,您不应该使用 break
因为您想获取整数永远。 :
while True:
try:
integer = int(input("Enter an integer between 1 to 10 "))
parameter = integer in range(1,10)
assert parameter # asserts the condition and checks if its True or False
equation = 1/integer
print(equation)
except ValueError:
print("not int")
except AssertionError: # if assertion is False then an AssertionError is raised
print("not between 1-10")
输出:
Enter an integer between 1 to 10 12
not between 1-10
Enter an integer between 1 to 10 2
0.5
Enter an integer between 1 to 10 val
not int
回答2
假设 OP 不考虑 try/except 违反不使用任何“条件结构”的要求,那么:
try:
integer = int(input("Enter an integer between 1 to 10: "))
1 / (integer in range(1, 11))
print(1 / integer)
except (ValueError, ZeroDivisionError):
print('Input not an integer in specified range')
回答3
由于 bool value 是整数这一事实:
>>> a = -1
>>> a = (0, a)[a in range(1, 11)]
>>> try:
... print(1 / a)
... except ZeroDivisionError:
... print('not in 1 to 10')
...
not in 1 to 10
所以你的问题可以解决如下:
while True:
try:
integer = int(input("Enter an integer between 1 to 10 "))
integer = (0, integer)[integer in range(1, 11)]
print(1 / integer)
except ValueError:
print("not int")
except ZeroDivisionError:
print("not between 1 to 10")
回答4
你真的很亲近!唯一要改变的是输出的格式,试试这样的:
while True:
try:
integer = int(input("Enter an integer between 1 to 10 "))
parameter = integer in range(1, 10)
equation = 1 / integer
print("The reciprocal of " + str(integer) + " is 1/" + str(integer) + " or " + str(1/integer))
break
except ValueError:
print("Not an integer, please try again.")