In this tutorial, you will create a Python program to check if a number is positive, negative, or 0.
You can check this by checking if the number is greater than 0 or less than 0.
If a number is greater than 0 then it will be positive.
But if a number is less than 0 it will be negative.
If you are new to Python, to understand this code, you should first check:
- How to get basic input and output in Python
- If and else conditional statements in Python
- While loop in python
Simple Code
num = input('Enter a number to check its nature : ')
num = float(num)
if num > 1:
print('Positive.')
elif num < 1:
print('Negetive.')
elif num == 0:
print('zero')
Code with exception handling
while True:
try:
num = input('Enter a number to check its nature : ')
num = float(num)
if num > 1:
print('positive')
elif num < 1:
print('negetive')
elif num == 0:
print('zero')
break
except:
print('Invalid entry.')
Output
Enter a number to check its nature : 59
Positive.
Code with explanation
#take input from the user
num = input('Enter a number to check its nature : ')
#Convert the input to float, may be user entered some float value (This will work fine for integers as well)
num = float(num)
#checking if number is greater than 1, print Positive.
if num > 1:
print('positive')
#if the number is not greater than one, then check if it is less than one. If so, print negative
elif num < 1:
print('negetive')
#If first two conditions are wrong then check if it is equal to zero
elif num == 0:
print('zero')
Code with explanation (Exception handling)
#program will run until it is executed successfully!
while True:
#This try block will be executed first and if the user enter an interger, the result will be printed and program will end successfully
#But if the user enter wrong input such as an alphabet, program will throw an error and will run again
try:
#take input from the user
num = input('Enter a number to check its nature : ')
#Convert the input to float, may be user entered some float value (This will work fine for integers as well)
num = float(num)
#checking if number is greater than 1, print Positive.
if num > 1:
print('positive')
#if the number is not greater than one, then check if it is less than one. If so, print negative
elif num < 1:
print('negetive')
#If first two conditions are wrong then check if it is equal to zero
elif num == 0:
print('zero')
#this break command will end the program if it is executed successfully.
break
#But in some cases, the user may enter some alphabet or any other character. Then this error will be displayed and loop will run the program again
except:
print('Invalid entry.')
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.