Home > Software design >  How to check that a input is Positive Integer?
How to check that a input is Positive Integer?

Time:12-12

a part of my code is as follow I want to raise a errorvalue if the user doesnt enter a Positive integer for x & Y when I dont check a positive input this code act ok for raising value error incase of inputing Float Number instead of a Integer but when I add if for checking x and y for beign positive this code is not running anymore

the mentioned part of my code is:

while True:
    try:
        A, B = moudle(x=int(input('x:')), y=int(input('y:')))
        print('The x is '   str(x))
        print('The y is '   str(y))
        break 
    except ValueError:
        print("insert Positive Integer Number.  Try again...")
while True:
    try:
        A, B = moudle(x=int(input('x:')), y=int(input('y:')))
        print('The x is '   str(x))
        print('The y is '   str(y))
        break 
    except ValueError:
        print("insert Positive Integer Number.  Try again...")

CodePudding user response:

To check if x and y are positive integers, you can add an if statement to check their values before passing them to the moudle function. Here is an example of how you can do this:

while True:
    try:
        # Get input for x and y
        x = int(input('x: '))
        y = int(input('y: '))

        # Check if x and y are positive integers
        if x <= 0 or y <= 0:
            raise ValueError("insert Positive Integer Number. Try again...")

        # Pass x and y to the moudle function
        A, B = moudle(x=x, y=y)

        # Print the values of x and y
        print('The x is '   str(x))
        print('The y is '   str(y))
        break 
    except ValueError as err:
        print(err)

In the code above, we check if x and y are positive integers before passing them to the moudle function. If they are not positive integers, we raise a ValueError with a message asking the user to insert positive integers. If a ValueError is raised, the code in the except block is executed, which prints the error message and asks the user to try again. This continues until the user inputs valid positive integer values for x and y.

CodePudding user response:

Here is the solution to your problem; just use conditional statements for it:

num = int(input("Enter the number \n "))
if num >= 0:
    print("The number is positive")

elif num < 0:
   print("The number is negative")
  • Related