求 1 到 10 之间的整数的倒数

Find the reciprocal of an integer between 1 and 10

所以我需要编写一个程序来请求从 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")

你真的很亲近! 唯一要改变的是输出的格式,尝试这样的事情:

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.")

由于bool值是整数:

>>> 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")

您可以使用 assert 来检查数字是否在 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

假设 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')