Finding whether the number entered by user is positive, negative or zero

In this blog , we will be creating a program to determine whether a number entered by user is positive, negative or zero. Program uses if elif and else statement.

We will start by creating a function called posneg() which include one parameter “num”. This num parameter will get value when the function is called. Function include if elif and else statement. If the number is greater than 0, printing ” Positive Number, if it is less than 0, printing “Negative Number” and if user enters 0 than printing “Zero Number”.

def posneg(num):
    if num < 0:
        print("Negative Number")
    elif num > 0 :
        print("Positive Number")
    else:
        print("Zero Number")

Next step is to prompt user to enter any number. We want user to enter only integer number and in case user enters string or alphanumeric character, printing “Please enter only integer number. This is done using try and except statement. We have use int() function along input() function to accept only integer number. If user enter some alphanumerical character it will be a error and the program print “Please enter only integer number” from except

try:
    value = int(input("Please enter any number: "))
    posneg(value)
except:
    print("Please enter only integer number")

Output 1

Please enter any number: 6
Positive Number

Output : User enters some alphanumeric characters

Please enter any number: jig9
Please enter only integer number

Output 3

Please enter any number: 0
Zero Number

Output 4

Please enter any number: -9
Negative Number

Complete Code

def posneg(num):
    if num < 0:
        print("Negative Number")
    elif num > 0 :
        print("Positive Number")
    else:
        print("Zero Number")

try:
    value = int(input("Please enter any number: "))
    posneg(value)
except:
    print("Please enter only integer number")

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s