Python program to print negative numbers in a list

Python program to print negative numbers in a list

Let's create a tutorial to retrieve and print negative numbers from a given list.

Objective:

Given a list of numbers, our task is to print all the negative numbers from that list.

Example:

For the list numbers = [1, -2, 3, -4, 5, -6], the negative numbers are -2, -4, -6.

Approach:

  1. Iterate over each number in the list.
  2. Check if the number is less than zero.
  3. If it's negative, print the number.

Python Implementation:

def print_negative_numbers(numbers): """Prints all negative numbers from the given list.""" for num in numbers: if num < 0: print(num) # Test numbers = [1, -2, 3, -4, 5, -6] print_negative_numbers(numbers) 

Expected Output:

-2 -4 -6 

Test & Verify:

To further ensure the program's correctness, you can test it with various lists:

test_numbers = [10, -15, 20, -25, 30] print_negative_numbers(test_numbers) # Expected output: -15, -25 test_numbers2 = [7, 9, 11, 13] print_negative_numbers(test_numbers2) # Expected no output as there are no negative numbers. 

Notes:

  • The function directly prints the negative numbers from the list. Depending on your needs, you might want to store the negative numbers in a new list and return it or make other alterations.
  • You can use list comprehension as a more concise way to generate a list of negative numbers if you prefer.

Example using list comprehension:

def get_negative_numbers(numbers): """Returns a list of all negative numbers from the given list.""" return [num for num in numbers if num < 0] # Test numbers = [1, -2, 3, -4, 5, -6] print(get_negative_numbers(numbers)) # Expected Output: [-2, -4, -6] 

This approach builds a new list containing just the negative numbers and returns it.


More Tags

uinavigationitem sum tcpclient configuration-files bottom-sheet msdeploy dataformat jacoco-maven-plugin azure-web-app-service uiapplicationdelegate

More Programming Guides

Other Guides

More Programming Examples