The sum of ten numbers inserted from the user

Ian Clark ianhclark510 at gmail.com
Thu Feb 7 13:27:28 EST 2019


This is my whack at it, I can't wait to hear about it being the wrong big o
notation!

numbers=[]

while len(numbers) < 10:
    try:
        chip = int(input('please enter an integer: '))
    except ValueError:
        print('that is not a number, try again')
    else:
        numbers.append(chip)

print(sum(numbers))


On Thu, Feb 7, 2019 at 10:23 AM Schachner, Joseph <
Joseph.Schachner at teledyne.com> wrote:

> Well of course that doesn't work.  For starters, x is an int or a float
> value.  After the loop It holds the 10th value.  It might hold 432.7 ...
>  It is not a list.
> The default start for range is 0.  The stop value, as you already know, is
> not part of the range.  So I will use range(10).
>
> In the second loop, I think you thought x would be a list and you I'm sure
> you wanted to do
>         for y in x:
> but instead you did
>         for y in range(x)
>  and remember x might be a very large number.    So the second loop would
> loop that many times, and each pass it would assign y (which has first
> value of 0 and last value of whatever x-1 is) to sum.  Even though its name
> is "sum" it is not a sum.  After the loop it would hold x-1.  You wanted to
> do  sum += y.    Or sum = sum + y.   I prefer the former, but that could
> reflect my history as a C and C++ programmer.
>
> And then you printed y, but you really want to print sum  (assuming that
> sum was actually the sum).
>
> Putting all of the above together, you want to do this:
>
> vallist =[]     # an empty list, so we can append to it
> for n in range(10):
>     x = input("Insert a number: ")    # get 1 number into x
>     vallist.append(x)                          # append it to our list
>
> # Now vallist holds 10 values
>
> sum = 0   # No need to start sum as a float, in Python if we add a float
> to an integer the result will be float. It doesn't matter in the program if
> sum is int or float.
> for y in vallist:
>      sum += y
>
> print( "The sum is: ", sum)
>
>
>
> -----Original Message-----
> From: ^Bart <gabriele1NOSPAM at hotmail.com>
> Sent: Thursday, February 7, 2019 6:30 AM
> To: python-list at python.org
> Subject: The sum of ten numbers inserted from the user
>
> I thought something like it but doesn't work...
>
> for n in range(1, 11):
>      x = input("Insert a number: ")
>
> for y in range(x):
>      sum = y
>
>      print ("The sum is: ",y)
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>


More information about the Python-list mailing list