Program to find whether number entered by user is positive or negative

This blog includes a program to find whether the number entered by user is positive or negative

Asking user to input number

num = int(input('Enter any number: '))

Using condition statement to check number entered by user is positive or negative. Number is positive if entered number is greater than or equal to 0. Number is negative if number is less than 0.

if num >= 0:
    print('Entered number %d is Positive'%num)
else:
    print('Entered number %d is Negative'%num)

Output

Enter any number: 9
Entered number 9 is Positive

Output

Enter any number: 0
Entered number 0 is Positive

Output

Enter any number: -7
Entered number -7 is Negative

Output (Alphanumeric characters)

Enter any number: ;m;m3
Incorrect number
try:
num = int(input('Enter any number: '))
if num >= 0:
print('Entered number %d is Positive'%num)
else:
print('Entered number %d is Negative'%num)
except ValueError:
print('Incorrect number')

There is a use of try and except. This is use to display message ‘Incorrect number’ in case user enter alphanumeric characters.

Advertisement

Leave a Comment

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 )

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