Write a program to read a list of n integers (positive as well as negative). Create two new lists, one having all positive numbers and the other having all negative numbers from the given list. Print all three lists.
Question
Write a program to read a list of $\mathrm{n}$ integers (positive as well as negative). Create two new lists, one having all positive numbers and the other having all negative numbers from the given list. Print all three lists.
✨ Free AI Tools for You
Powered by Chatterbot AI
Answer
Here is a Python program that reads a list of n
integers, and creates two new lists: one with all the positive numbers and the other with all the negative numbers. Then, it prints all three lists.
# Function to separate positive and negative numbers
def separate_numbers(input_list):
positive_list = []
negative_list = []
for number in input_list:
if number >= 0:
positive_list.append(number)
else:
negative_list.append(number)
return positive_list, negative_list
# Main program
input_list = []
# Reading the number of integers
n = int(input("Enter the number of integers: "))
# Reading the integers
for i in range(n):
num = int(input(f"Enter integer {i + 1}: "))
input_list.append(num)
# Separate the numbers into positive and negative lists
positive_list, negative_list = separate_numbers(input_list)
# Print the three lists
print("Original list:", input_list)
print("Positive numbers list:", positive_list)
print("Negative numbers list:", negative_list)
Important points:
Reading Input: The program first asks the user for the number of integers and then reads each integer.
Separating Numbers: The function
separate_numbers
takes the original list and separates it into two lists based on whether the numbers are positive or negative.Output: Finally, the program prints the original list, the list of positive numbers, and the list of negative numbers.
India's 1st AI Doubt Solver for CBSE, JEE, and NEET
Ask a Question for Freeand then it's just ₹212 a month