Home > OS >  Any way to make these if statements more succinct? [duplicate]
Any way to make these if statements more succinct? [duplicate]

Time:09-17

I made a small python program to tell whether a given number is positive or negitive, I'm trying to find a way to simplify it.

Input :

Number = int(input("Enter your number: "))
if Number>0:
    Value = 'Positive'
if Number<0:
    Value = 'Negitive'
if Number == 0:
    Value = 'Zero'

print (Value)

Output:

Enter your number:  5
Positive

Process finished with exit code 0

CodePudding user response:

A hack with a dictionary:

d = {-1: 'Negative', 0: 'Zero', 1: 'Positive'}

Number = int(input("Enter your number: "))

Value = d[Number and Number / abs(Number)]
>>> Number=5; d[Number and Number / abs(Number)]
'Positive'

>>> Number=-8; d[Number and Number / abs(Number)]
'Negative'

>>> Number=0; d[Number and Number / abs(Number)]
'Zero'

Obviously the right answer is given by @mozway and @sj95126.

>>> Value = 'Positive' if Number>0 else 'Negative' if Number<0 else 'Zero'

CodePudding user response:

Firstly your code is quite simple, Secondly You have used Multiple if's instead of an else-if-structure, but the other two checks should be in a elif & else block. Because the nature of a number can be either Negative, Positive or Zero but not more than 1 state.

You can have a ternary expression using the ternary operator, & you can handle assigning value to a variable in one line! Here is a function:

def checkNumberNature(n):
   value = "Positive" if n > 0 else "Negative" if n < 0 else "Zero"
   print(value)
  • Related