# Using Loops to track user input

Bengt Richter bokr at oz.net
Sun Jul 6 23:50:40 CEST 2003

```On Sun, 06 Jul 2003 16:32:37 -0400, hokiegal99 <hokiegal99 at hotmail.com> wrote:

>I don't understand how to use a loop to keep track of user input. Could
>someone show me how to do what the program below does with a loop?
>
>Thnaks!
>
>----------------------------
>#Write a program that reads 10 numbers from the user and prints out the
>sum of those numbers.
>
>num0 = input("Enter a number: ")
>num1 = input("Enter a number: ")
>num2 = input("Enter a number: ")
>num3 = input("Enter a number: ")
>num4 = input("Enter a number: ")
>num5 = input("Enter a number: ")
>num6 = input("Enter a number: ")
>num7 = input("Enter a number: ")
>num8 = input("Enter a number: ")
>num9 = input("Enter a number: ")
>
>num = num0+num1+num2+num3+num4+num5+num6+num7+num8+num9
>
>print num
>----------------------------------
>

>>> num = 0
>>> for i in range(10):
...     prompt = 'Enter %s%s number: '%(i,i<4 and 'thstndrd'[2*i:2*i+2] or 'th')
...     while 1:
...         try:
...             num += int(raw_input(prompt))
...             break
...         except Exception,e:
...             print '    Error: %s' % e
...
Enter 0th number: 100
Enter 1st number: 10
Enter 2nd number: x
Error: invalid literal for int(): x
Enter 2nd number: 2
Enter 3rd number: 3
Enter 4th number: 4.5
Error: invalid literal for int(): 4.5
Enter 4th number: 4
Enter 5th number: 5
Enter 6th number: 6
Enter 7th number: 7
Enter 8th number: 8
Enter 9th number: 9
>>> print num
154

Regards,
Bengt Richter

```

More information about the Python-list mailing list