Write a program to Check if a Number is Positive Negative or 0 in Python
Code:
1 2 3 4 5 6 7 8 9 | num = float(input("Enter a number: ")) if num > 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number") |
The code you provided is a simple Python program that checks whether a number entered by the user is positive, zero or negative, and prints a message accordingly.
The program starts by using the input()
function to prompt the user to enter a number. The user’s input is stored as a string, so it needs to be converted to a float using the float()
function. The variable num
is then assigned the value input by the user.
Then, the program uses an if-elif-else statement, which is a control flow statement that allows to check multiple conditions and execute different code based on which condition is true.
The if statement checks if the value of num
is greater than 0. If this condition is true, the program will execute the code within the if block and print “Positive number”
If the condition in the if statement is false, the program moves on to check the next condition using the elif statement, which is short for “else if”. This condition checks if the value of num
is equal to 0. If this condition is true, the program will execute the code within the elif block and print “Zero”
If both the conditions in the if and elif statements are false, the program will execute the code within the else block and print “Negative number”
The output will depend on the input provided by the user. For example, if the user inputs 15, the output will be “Positive number” if the user inputs -5, the output will be “Negative number” and if the user