-1

I want to get only positive numbers in python .

and if the user enter a negative number the program show an error message .

should I code lots of conditions like

if this : do this

if that : do that

and so on .

or is there another way for this ?

The Epic
  • 137
  • 5
main raise
  • 29
  • 1
  • 3

4 Answers4

0

Use abs(x) Python native function.

EDIT: if you want to raise an error, instead, I would make use of assertions (example taken from here:

x = 0
assert x > 0, 'Only positive numbers are allowed'
print('x is a positive number.')
Andrea Nicolai
  • 349
  • 1
  • 3
  • 12
0

You can use just an if statement like the code below:

n = float(input("Enter a positive number: "))
if num <= 0:
    raise ValueError("Please enter only positive numbers")

If the number is not a positive one you can manage as you prefer. In the example I put a raise, but you can also use a print statement with the message or an assertion.

Giordano
  • 5,422
  • 3
  • 33
  • 49
0

Not sur to understand your question,

you only need to do if x >= 0: if you want to check if x is positive or negative

0

Simple options to achieve this can be

  • if input_num < 0
  • if abs(input_num) == input_num
    In 1st case, you check if given number is less than 0 (it is negative)
    In 2nd case, you use abs() function which gives a positive number from a negative or positive number. e.g. abs(-2) # returns 2