Q4. Python Program to Check Positive Negative or Zero | 7 Methods with Explanation

Hi friends Welcome back to DailyCodeHub.

I still remember the day I was preparing for my first Python interview. My interviewer asked me this simple question - write a program to check if a number is positive, negative, or zero. I know the answer, but I only know one method at that time. 

Today I do not want you to be in the same situation. So in this post I have explained 7 different methods to solve this program. whether you are a complete beginner or preparing for a senior-level interview, you will
Find a method that suits your level here.

I have also explained each method  step by step so that even if you are completely new to Python, you can understand everything easily. Let us get started

 
Before we start—let us understand the basics :

Before writing the program, let me quickly explain what positive, negative, and zero mean.
A positive number is any number that is greater than zero. When you think about it in real life, positive numbers are like money you have in your pocket. For example, 1, 5, 10, and 100 are all positive numbers.

A negative number is any number that is less than zero. Think of negative numbers like money you use something on. For example, -1, -5, -10, and -100 are all negative numbers.

Zero is a special number. It is neither positive nor negative. it is the point between positive and negative numbers. "Zero" simply means nothing or empty.

Now that we understand the basics, let us write the programs.


Question :

Write a Python program to check if a number is positive, negative, or zero.


Method 1: Using if, elif, else | Level: Beginner | Best for : Freshers and beginners 

This is the first method every Python beginner should learn . it uses the most basic concept in Python, which is if, elif, else. If you are a fresher preparing for TCS, Infosys or Wipro this is the method you must know.

Code :

# Method 1 : Using if elif else
# Level : Beginner
n = int(input("Enter a number: "))
if n > 0:
    print(n, "is Positive")
elif n < 0:
    print(n, "is Negative")
else:
    print(n, "is Zero")

Output:

Enter a number: 10
10 is positive

Enter a number: -5
-5 is Negative

Enter a number: 0 
0 is Zero

How it works step by step :

First we ask the user to enter a number using the input( ) function. since input( ) always returns a string we use int( ) to convert it to an integer.

Then we check the first condition which is if n > 0. if the number is greater than zero we immediately print that the number is positive and skip the remaining conditions.

If the first condition is false we move to elif n < 0. if the number is less than zero we print that the number is negative.

If both conditions are false it means the number must be zero. so we go to the else block and print zero.

This method is  simple clean and easy to understand which is the  most popular method for beginners.


Method 2 : using function | Level : Beginner | Best for : Understanding functions

The second method uses a function. when i first learned about functions in Python this was one of the programs i used to practice. A function is a block of reusable code . you write it once and you can use it many times in your program.

Code :

# Method 2 : Using Function
# Level : Beginner
def check_number(n):
    if n > 0:
        return "Positive"
    elif n < 0:
        return "Negative"
    else:
        return "Zero"

n = int(input("Enter a number: "))
print(n, "is", check_number(n))

Output: 

Enter a number: 10
10 is Positive

Enter a number: -5 
-5 is Negative

Enter a number: 0
0 is Zero


How it works step by step :

We define a function called check_number using the def keyword. this function takes one parameter called n which is the number we want to check.

Inside the function we check the conditions just like Method 1 . but instead of printing directly we use return to send the result back to where the function was called.

Outside the function we take input form the user and pass it to the  check_number function. the function returns the result and we print it.

The biggest advantage of this method is reusability. if you need to check a number at 10 different places in your program you just called check_number( ) each time instead of writing the if/elif/else again and again.


Method 3 : Using Ternary operator | Level : Intermediate | Best for : Writing short and clean code

The ternary operator is one of my favorite features in python. it allows you to write an if else condition in just one line. When I first learned this I was amazed at how much shorter the code became.

Code :

# Method 3 : Using Ternary Operator
# Level : Intermediate
n = int(input("Enter a number: "))
result = "Positive" if n > 0 else "Negative" if n < 0 else "Zero"
print(n, "is", result)

Output:

Enter a number: 10
  10 is Positive

Enter a number: -5
  -5 is Negative

 Enter a number: 0 
0 is Zero

How it works step by step :

The ternary operator follows this pattern : value_if_true  if condition else value_if_false.

In our code we first check if n > 0. if this is true the result becomes positive.

If n > 0 is false we move to the next part. we check  if n < 0. if this is true the result becomes negative.

If both conditions are false the result becomes zero. 

The entire logic that look 5 th line in method 1 is now written in just 1 line. this is the power of the ternary operator.


Method 4: Using Lamda function | Level : Intermediate | Best for : Understanding Lambda

Lambda functions are also called anonymous functions in python. they are small functions that are written in just one line without using the def keyword. this is a very useful concept that is asked in many intermediate-level interviews.

Code :

# Method 4 : Using Lambda Function
# Level : Intermediate
check = lambda n: "Positive" if n > 0 else "Negative" if n < 0 else "Zero"

n = int(input("Enter a number: "))
print(n, "is", check(n))

Output: 

Enter a number: 10 
10 is Positive 

Enter a number: -5 
-5 is Negative

Enter a number: 0 
0 is Zero


How it works step by step :

We create a lambda function and store it in a variable called check . the lambda keyword is used to create the anonymous function.

The lambda function takes n as input and uses the ternary operator to check if the number is positive negative or zero.

We then call the lambda function just like a normal function by writing check (n) and print the result.

The difference between a normal function and a lambda function is that lambda is shorter and written in one line. however for complex logic a normal function is better.



Method 5 : Using abs( ) function | Level : Intermediate | Best for : understanding abs( ) function

This is a very unique and creative method. it uses the abs( ) function in clever way. when you show this method in an interview it leaves a very good impression on the interviewer because it shows that you think differently

Code :

# Method 5 : Using abs() Function
# Level : Intermediate
n = int(input("Enter a number: "))
if n == 0:
    print(n, "is Zero")
elif n == abs(n):
    print(n, "is Positive")
else:
    print(n, "is Negative")

Output:

Enter a number: 10 
10 is Positive

Enter a number: -5
-5 is Negative

Enter a number: 0 
0 is Zero
 

How it works step by step :

The abs( ) function in python always returns the absolute value of a number which means it always returns a positive value. for example : abs(10) returns 10 and abs(-10) also returns 10.

First we check if n is equal to zero. if yes we print zero.
 
Then we check if n equals abs(n). if a number is positive it will always equal its absolute value. for example :10 equals abc(10) which is 10. So if n equals abs(n) the number is positive.

If a number is negative it will not equal its absolute value. for example : - 5 does not equal abs(-5) which is 5. so if n does not equal abs(n) the number is negative.


Method 6 : Using list and loop | Level : Advanced | Best for : Checking Multiple numbers at once

sometimes in real projects you do not have just one number to check. you might have a whole list of numbers and you need to check all of them. this method is perfect for that situation.

Code :

# Method 6 : Using List and Loop
# Level : Advanced
numbers = [10, -5, 0, 20, -3]

for n in numbers:
    if n > 0:
        print(n, "is Positive")
    elif n < 0:
        print(n, "is Negative")
    else:
        print(n, "is Zero")

Output:

10 is Positive

-5 is Negative

0 is Zero

20 is Positive

-3 is Negative

How it works step by step :

We create a list called numbers that contains five numbers including positive negative and zero values.
 
We use a for loop to go through each number in the list one by one. the variable n takes the  value of each number in the list on each iteration.

For each number we apply the same if, elif, else logic  from method 1 to check whether it is positive,negative or zero and print the result.

This method is very efficient when you need to process a large number of values because you only need to write the checking logic once and the loop handles the rest. 


Method 7 : Using Dictionary | Level : Advanced  | Best for : Senior Level Interviews

This is the most advanced and most creative method in this post. It uses a mathematical trick combined with a dictionary to find the answer in just one line. This method will definitely impress your interviewer in a senior-level interview.

Code :

# Method 7 : Using Dictionary
# Level : Advanced
n = int(input("Enter a number: "))
result = {1: "Positive", -1: "Negative", 0: "Zero"}
print(n, "is", result[(n > 0) - (n < 0)])

Output:

Enter a number: 10 
10 is Positive

Enter a number: -5
-5 is Negative 

Enter a number: 0 
0 is Zero

How it works step by step :

We create a dictionary called result with three key values pairs. the keys are 1,-1 and 0 these values are positive , negative and zero.

Now the magic happens in the expression (n > 0) - (n < 0). in python when you compare two values the result is True or False . True equals 1 and False equals 0 in python.

For a positive number like 10: (10 > 0) is True which equals 1. (10 < 0) is False which equals 1. So, 1-0 equals 1. we look up key 1 in the dictionary and get positive.

For negative numbers like -5: (-5 > 0) is False which equals 0 . (-5 < 0) is True which equals 1. so 0-1 equals -1. we  look up key -1 in the dictionary and get negative.

For zero : (0 > 0) is False which equals 0. (0 < 0) is False which equals 0 . So 0 - 0 equals 0. we look up key 0 in the dictionary and get zero.

This is very clever trick that uses the mathematical properties of True and False in Python.


Methods summary table :

Method Technique Level Best For
Method 1 if elif else 🟢 Beginner All interviews
Method 2 Function 🟢 Beginner Function concept
Method 3 Ternary Operator 🟡 Intermediate Short code
Method 4 Lambda Function 🟡 Intermediate Lambda concept
Method 5 abs() Function 🟡 Intermediate abs() concept
Method 6 List and Loop 🔴 Advanced Multiple numbers
Method 7 Dictionary 🔴 Advanced Senior interviews



Key points to remember :

Any number greater than zero is a positive number.
 
Any number less than zero is a negative number.

Zero is neither positive nor negative number.

if , elif , else is the most basic and commonly used method.

The ternary operator writes if / elif / else in just one line.

A lambda is an anonymous function written in one line.

abs( ) always returns a positive value regardless of sign.

Dictionary methods uses True equals 1 and False 0 trick.

List and loop method is perfect for checking multiple numbers.

For freshers interviews method 1 is the best choice.

For senior interviews method 7 shows advanced knowledge.


Frequently Asked Questions :

Q. What is a positive number in python?

A) Any number greater than zero is called a positive number in python. examples include 1,5,10,100 and 999.
 
Q. What is a negative number in python?

A) Any number less than zero is called a negative number in python. examples include -1,-5,-10,-100 and -999.

Q. Is zero positive or negative in python?

A) Zero is neither positive nor negative in python. it is a netural number that stands between positive and negative numbers.

Q. Which method is best for fresher interview?

A) Method 1 using if elif else is the best method for fresher interviews. it is simple clean and easy to explain to the interviewer.

Q. What does the abs( ) function do in python?

A) The abs ( ) function returns the absolute value of a number. it always returns a positive value. for example abs(-5) returns 5 and and abs(5) also returns 5.

Q. Can we check multiple numbers at once?

A) Yes we can check multiple numbers at once using method 6 which uses a list and for loop. this is very useful when you have many numbers to check.


Related programs :
 
Q3 . Python program to check even or odd 👈[click here]
Q5 . Python program to find largest of three numbers ðŸ‘ˆ[clickhere]
Q6 . Python program to swap two numbers ðŸ‘ˆ[click here]
Q7 . Python program to find sum of digits ðŸ‘ˆ[click here]
Q8 . Python program to reverse a number ðŸ‘ˆ[click here]


That is all for today friends ! I hope this post helped you understand how to check if a number is positive negative or zero in python. i have tried my best to explain each method in the simplest way possible.

The most improtant method for your interview is method 1 . but if you want to impress your interviewer try to explain method 3 or Method 7 as well. Knowing multiple  methods always give you an advantages over other candidates.

If you found this post helpful please share it with your friends who are also preparing for python interviews. it will help them a lot.

If you have any question or if you know any other method to slove this program please leave a comment below. I would love to learn form you as well !

Keep coding keep learning and never give up . see you in the next post!

Happy coding ❤️

DailyCodeHub — dailycodehub.blogspot.com















No comments:

Post a Comment