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:
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.
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)