The problem seems very simple but I'm cracking my head over it. It's just an algorithm exercise. This is what I have so far:
positivesum = 0
negativeqt = 0
value = int(input(("Enter the numbers: ")))
for _ in range(20):
value
if value > 0:
positivesum = positivesum value
print("The sum of positives is ", positivesum)`
Also, if someone could translate the same exercise in Javascript, I would appreciate it.
CodePudding user response:
int_list = [int(inp) for inp in input("Enter 20 numbers: ").split()]
pos_sum = sum(num for num in int_list if num > 0)
neg_quantity = len([num for num in int_list if num < 0])
print(f"{pos_sum=} {neg_quantity=}")
How It Works
int_list
is something called a list comprehension. When prompted with the input, a user is able to input the 20 numbers, with spaces in between the different numbers due to the call to split()
. split()
by default will split by a white space character. split()
will return an iterable list, so we iterate over that list with for inp in …
. int(inp)
will convert each of the numbers from type str
to type int
. input()
returns a string, so this is needed to do number operations
pos_sum
calls the sum
built in and passes it a generator expression. It iterates over the list resulting from all of the operations done in int_list
and only looks for the numbers that are greater than 0. It will add these up, giving us our sum.
neg_quantity
calls the len
built in and passes in an iterable list to len
, constructed through a list comprehension. The resulting list from the comprehension will contain all numbers from int_list
less than 0, and len
will return the length of that list, giving us our quantity of negatives
CodePudding user response:
positive = 0
negative = 0
for i in range(-10 , 10):
print(i)
if i >= 0:
positive = i
elif i <= 0:
negative = 1
print(positive)
print(negative)
CodePudding user response:
Your issue is that you put the input
statement in the wrong place:
positivesum = 0
negativeqt = 0
for _ in range(20):
value = int(input(("Enter the numbers: ")))
if value > 0:
positivesum = value
else if value < 0:
negativeqt
If you only ask for one input then the user can only give you one number. Since you want twenty numbers, you need to put the input
inside your for-loop so you get a value every time you need a value.
CodePudding user response:
Something like this?
Python:
sum_positive_number = 0
negative_number_quantities = 0
numbers = 20
for i in range(numbers):
number_input = int(input(f'Enter number #{i 1}: '))
if number_input > 0:
sum_positive_number = number_input
elif number_input < 0:
negative_number_quantities = 1
print('Sum of positive numbers: ', sum_positive_number)
print('Quantities of negative numbers: ', negative_number_quantities)