Home > Blockchain >  Find the reciprocal of an integer between 1 and 10
Find the reciprocal of an integer between 1 and 10

Time:05-15

so I need to write a program that requests an integer from 1 through 10 and calculates its reciprocal.

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

CodePudding user response:

You can use assert to check if the number is in the range of 1 and 10. Also, in my opinion, you shouldn't be using break because you want to get the integer forever. :

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

Output:

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

CodePudding user response:

Assuming OP doesn't consider try/except to contravene the requirement of not using any "conditional structure" then:

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

CodePudding user response:

By virtue of the fact that bool value is integer:

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

So your problem can be solved as follows:

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

CodePudding user response:

You are really close! The only thing to change is how the output is formatted, try something like this:

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