Search code examples
pythonstringlistfor-loopwhile-loop

Create a List From Input Separated by Commas And Find the Sum of the List with For/While Loops


I'm new to Python and am currently working on the following problem. It seems simple but I keep getting lost in value errors.

Here's the requirements:

Write a program that allows the user to input as many integers as they would like, separated by commas and then add these integers together using both a while loop and a for loop. You will need to perform the following steps:

  • Ask the user to enter integers separated by commas.
  • Convert the input to a list of integers.
  • Calculate the sum of the integers in the list in two ways:
  • First, use a while loop to calculate the sum and then display the sum.
  • Then, use a for loop to calculate the sum and display the sum.

My code so far:

# First thing I do is enter an input
input_string = input(('Enter elements of a list separated by commas: '))
# Followed by splitting the string into a list:
user_list = (input_string.split())

After this I'm supposed to do some calculations on user_list with a for/while loop, but I can't because it's a string and every time I try to convert it into an integer I get some sort of error. If anyone could help I'd appreciate it.


Solution

  • the forced use of while loop is kind not really necessary when a for loop is more appropriate. so in this example we use the while loop to convert our list of str to int as we total it up. the we use the list we modified in the for loop.

    input_string = input('Enter elements of a list separated by commas: ')
    
    user_list = input_string.split(',')
    user_list_len = len(user_list)
    count = 0
    total = 0
    
    while count < user_list_len:
        user_list[count] = int(user_list[count].strip())
        total += user_list[count]
        count += 1
    print(total)
    
    total = 0
    for item in user_list:
        total += item
    print(total)