Skip to content Skip to sidebar Skip to footer

Is It Possible To Have A User Enter Integers And Add Them Using A While Loop In Python?

This is for one of my assignments. Here is the question just for clarity on what I am trying to do. Please do not give me the answer, just if you could help me understand what I ne

Solution 1:

You want to read numbers one at a time, until the sum exceeds 45.

total = 0
num_list = []
while total < 45:
    num = int(input(...))
    num_list.append(num)
    total += num

# Now compute the average and report the sum and averages

To make sure the last number is not added to the list if that would put the total over 45,

total = 0
num_list = []
whileTrue:
    num = int(input(...))
    new_total = total + num
    if new_total > 45:
        break
    num_list.append(num)
    total = new_total

Solution 2:

The while loop should be used to get values from the user : While the total of the given values is lower than 45, ask the user for another value

numList = []
total = 0whileTrue:
    num = int(input('Enter an integer: '))
    if (total + num) > 45:
        break
    numList.append(num)
    total = total + num

avg = total / len(numList)
print('Sum of all numbers ', total)
print('Average of all numbers ', avg)

Post a Comment for "Is It Possible To Have A User Enter Integers And Add Them Using A While Loop In Python?"