- Count positive and negative numbers in a list in Python program
- Approach 1 − Brute-force approach using iteration construct(for)
- Example
- Output
- Approach 2 − Brute-force approach using iteration construct(while)
- Example
- Output
- Approach 3 − Using Python Lambda Expressions
- Example
- Output
- Conclusion
- Python Program to Check if A Number is Positive, Negative, or Zero
- 1. What is Number and When is it Positive or Negative?
- 2. Program to Check if A Number is Positive, Negative, or Zero
- 3. Check if Any Number is Positive, Negative, or Zero using Exception Handling
- 4. Conclusion
- Recommended -
- Positive and negative indices in Python?
- What Are List Indexes?
- Tuple Indexing
- Example 1
- Output
- Example 2
- Output
- Example 3
- Output
- Example 4
- Output
- Zero-Based Indexing in Python
- Example 5
- Output
- Negative Indexing
- Example 3
- Output
- Example 4
- Output
- Tuple index() Method
- Syntax
- Example 5: Removing Elements With Negative Index
- Output
- Example 6: Finding the index of an element
- Output
- Advantages of Using Negative Indexing in Python List
- Conclusion
- Python: Check if a number is positive, negative or zero
- Visualize Python code execution:
- Visualize Python code execution:
- Visualize Python code execution:
- Python: Tips of the Day
Count positive and negative numbers in a list in Python program
In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given a list iterable, we need to count positive and negative numbers in it and display them.
Approach 1 − Brute-force approach using iteration construct(for)
Here we need to iterate each element in the list using a for loop and check whether num>=0, to filter the positive numbers. If the condition evaluates to be true, then increase pos_count otherwise, increase neg_count.
Example
list1 = [1,-2,-4,6,7,-23,45,-0] pos_count, neg_count = 0, 0 # enhanced for loop for num in list1: # check for being positive if num >= 0: pos_count += 1 else: neg_count += 1 print("Positive numbers in the list: ", pos_count) print("Negative numbers in the list: ", neg_count)
Output
Positive numbers in the list: 5 Negative numbers in the list: 3
Approach 2 − Brute-force approach using iteration construct(while)
Here we need to iterate each element in the list using a for loop and check whether num>= 0, to filter the positive numbers. If the condition evaluates to be true, then increase pos_count otherwise, increase neg_count.
Example
list1 = [1,-2,-4,6,7,-23,45,-0] pos_count, neg_count = 0, 0 num = 0 # while loop while(num < len(list1)): # check if list1[num] >= 0: pos_count += 1 else: neg_count += 1 # increment num num += 1 print("Positive numbers in the list: ", pos_count) print("Negative numbers in the list: ", neg_count)
Output
Positive numbers in the list: 5 Negative numbers in the list: 3
Approach 3 − Using Python Lambda Expressions
Here we take the help of filter and lambda expressions we can directly differentiate between positive and negative numbers.
Example
list1 = [1,-2,-4,6,7,-23,45,-0] neg_count = len(list(filter(lambda x: (x < 0), list1))) pos_count = len(list(filter(lambda x: (x >= 0), list1))) print("Positive numbers in the list: ", pos_count) print("Negative numbers in the list: ", neg_count)
Output
Positive numbers in the list: 5 Negative numbers in the list: 3
All the variables are declared in the local scope and their references are seen in the figure above.
Conclusion
In this article, we have learned how to count positive and negative numbers in a list.
Python Program to Check if A Number is Positive, Negative, or Zero
In this Python example, we will discuss how can we check if any given number is positive, negative, or zero with explanation and implementation. Let’s get started.
1. What is Number and When is it Positive or Negative?
A number is a mathematical object used to count, measure, and label.
– Wikipedia
In simple words, we can say that number can be an arithmetical value, which can be expressed using different ways like word, symbol, or figure, representing a particular quantity and used for counting and can make the computation possible.
When any given number is greater than zero (0) then the number is said to be a positive number and when any given number is lesser than zero(0) then the number is said to be a negative number.
Example: Input : 4 Output : The number is positive Input : -5 Output : The number is negative
Some of the topics which will be helpful for understanding the program implementation better are:
2. Program to Check if A Number is Positive, Negative, or Zero
As discussed above, when the number is greater than zero then it is positive, and negative when it is lesser than zero and when it is equal to zero then the number is zero.
Hence, for the program implementation, we will use the if…else… condition along with the relational operator.
Let’s implement the code and see how it works.
#Python Program to Check is Number is >0 or 0: print("The given number is Positive number") elif num == 0: print("The given number is Zero") else: print("The given number is Negative number")
Output Enter any Number: 56 The given number is Positive number
In the above program, the given input is greater than zero so the output for the positive number was displayed.
3. Check if Any Number is Positive, Negative, or Zero using Exception Handling
Now, in the above program, we have covered the most basic way of implementation.
We can use the exception handling method if the user provides any other input rather than float value. Let’s use the exception handling method for the same problem and find out the working.
# Python Program to Check is Number is >0 or 0: print("The given number is Positive number") elif num == 0: print("The given number is Zero") elif num < 0: print("The given number is Negative number") except ValueError: print("Sorry, Your Input is Invalid")
Output Enter any Number: 67er Sorry, Your Input is Invalid
In the program, we have taken the input inside the try block and if the input cannot be converted to float then ValueError would have been given as output, but we have raised the exception for ValueError and handled the exception successfully.
4. Conclusion
In this article, we have learned how can we check if any provided number is negative, positive, or zero and also implemented the exception handling in case the output is not a number.
Helpful Links
Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.
Also for examples in Python and practice please refer to Python Examples.
Complete code samples are present on Github project.
Recommended Books
An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding
Do not forget to share and Subscribe.
Happy coding!! ?
Recommended -
Python Program to Check if A Number is Positive, Negative, or Zero was last modified: September 19th, 2021 by Garvit Parakh
Positive and negative indices in Python?
By indexing, we can access items in Python sequence data types. Strings, lists, tuples, and range objects are sequence data types. In this tutorial, we'll go over-indexing in further detail.
What Are List Indexes?
Any linear data structure in any programming language is built around indexing. The default index for each machine starts at 0 and continues up to n-1. In this case, n represents the overall number of items in the corresponding data structure. Types include
- Positive indexing − Increases from 0 to 1.
- Negative indexing − each traversal moves from tail to head, starting with the last element.
These facilitate our ability to access the many components of this data structure. Let's examine the procedures in the next part.
Tuple Indexing
Similar to how we access elements in lists and strings, we can access elements in tuples. So, indexing and slicing are the only methods we need to access items. Additionally, indexing is straightforward, beginning at index zero, just like in lists. In addition, the figure we put within the square bracket represents the tuple's index. Let's see a few instances of tuple indexing being used to retrieve a tuple's elements.
Example 1
tup1 = (10, 3, 4, 22, 1) # for accessing the first element of the tuple print(tup1[0])
Output
Example 2
tup1 = (10, 3, 4, 22, 1) # accessing the third element of the tuple print(tup1[2])
Output
Example 3
tup1 = (10, 3, 4, 22, 1) print(tup1[10]) # gives an error as the index is only up to 4
Output
IndexError: tuple index out of range
Example 4
tup1 = (10, 3, 4, 22, 1) print(tup1[1+3]) # the expression inside the square brackets results in an integer index 4. Hence, we get the element at the 4th index.
Output
Zero-Based Indexing in Python
In Python, positive zero-based indexing is the fundamental method for accessing iterable items.
As a result, an index starting at 0 may refer to any element in the iterable.
The first element in zero-based indexing has an index of 0, the second has an index of 1, and so on.
Example 5
myList = [1, 2, 3, 4, 5] # NORMAL INDEXING print(myList[0]) print(myList[1]) print(myList[2]) # NEGATIVE INDEXING (STARTS FROM THE LAST ELEMENT IN THE LIST) print(myList[-1]) print(myList[-2]) print(myList[-3]) print(myList[-3:])
Output
Negative Indexing
If we wish to print the components starting at the end, we may also use negative indexes. Additionally, by specifying the index number with a negative sign, we may carry out negative tuple indexing (-). As a result, this suggests that the compiler starts thinking about the elements in reverse order, beginning with the element that comes last in the tuple.
Example 3
tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1) print(tup[-4])
Output
Now, we can use negative indexes in slicing also.
Example 4
tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1) print(tup[-4:-1])
Output
Tuple index() Method
The tuple index() function aids in locating an element's index or location within a tuple. Essentially, this function serves two purposes −
Giving the tuple's first instance of each element.
If the indicated element is absent from the tuple, throwing an error.
Syntax
Example 5: Removing Elements With Negative Index
Using the pop() function and giving -1 as a parameter inside it, we can remove the last element of that list, and we get a new list.
my_list = [45, 5, 33, 1, -9, 8, 76] my_list.pop(-1) print(my_list)
Output
Example 6: Finding the index of an element
tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1) print(tup.index(45)) print(tup.index(890)) #prints the index of elements 45 and 890
Output
Advantages of Using Negative Indexing in Python List
- Fewer lines of code are needed, and a reversal is done in one line.
- Simplifies difficult processes.
- Operates quickly while requiring little complexity
Conclusion
In summary, Python allows positive indexing starting at zero and negative indexing starting at -1. In Python, negative indexing denotes that the indexing process begins at the end of the iterable. The final element is located at index -1, the next-to-last at index -2, and so on. Negative indexing is supported in arrays in the Python computer language but not in most other programming languages. This means that the index value of -1 offers the final element, and -2 gives the second last element of an array. The array's end is where the negative indexing begins.
Python: Check if a number is positive, negative or zero
Write a Python program to check if a number is positive, negative or zero.
Positive Numbers: Any number above zero is known as a positive number. Positive numbers are written without any sign or a '+' sign in front of them and they are counted up from zero, i.e. 1, + 2, 3, +4 etc.
Negative Numbers: Any number below zero is known as a negative number. Negative numbers are always written with a '−' sign in front of them and they are counted down from zero, i.e. -1, -2, -3, -4 etc.
Always look at the sign in front of a number to check if it is positive or negative. Zero, 0, is neither positive nor negative.
Pictorial Presentation:
Sample Solution-1:
Python Code:
num = float(input("Input a number: ")) if num > 0: print("It is positive number") elif num == 0: print("It is Zero") else: print("It is a negative number")
Input a number: 150 It is positive number
Visualize Python code execution:
The following tool visualize what the computer is doing step-by-step as it executes the said program:
Sample Solution-2:
Python Code:
n = float(input('Input a number: ')) print('Number is Positive.' if n > 0 else 'It is Zero!' if n == 0 else 'Number is Negative.')
Input a number: 0 It is Zero!
Visualize Python code execution:
The following tool visualize what the computer is doing step-by-step as it executes the said program:
Sample Solution-3:
Python Code:
n = float(input("Input a number: ")) if n >= 0: if n == 0: print("It is Zero!") else: print("Number is Positive number.") else: print("Number is Negative number.")
Input a number: -150 Number is Negative number.
Visualize Python code execution:
The following tool visualize what the computer is doing step-by-step as it executes the said program:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Follow us on Facebook and Twitter for latest update.
Python: Tips of the Day
How to lowercase a string in Python?
The official 2.x documentation is here: str.lower()
The official 3.x documentation is here: str.lower()
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook