Using Loops to track user input

Behrang Dadsetan ben at dadsetan.com
Mon Jul 7 00:06:24 CEST 2003


hokiegal99 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
> ----------------------------------
> 

# If you are want to loop a fixed amount of time, as I understand a way
# would be:
sum = 0
for i in xrange(10):
    sum += input("Enter a number: ")
average = sum/10
print average

# I guess however it would be more pythonic, because you do not really
# need that counter, to do something like:
entries=0
sum=0
while entries < 10:
    try:
       sum += input("%d) Enter a number: " % (entries + 1) )
       entries += 1
    except:
       print "You need to enter 10 values."
print "The average is %d" % (sum)

# And when you need you would want to make a "general" tool out of your
# case...
entries=0
sum=0
try:
    while 1:
       sum += input("%d) Enter a number: " % (entries + 1) )
       entries += 1
except:
    if entries == 0:
       print "You did not enter any number. Can not make average of 
nothing."
    else:
       print "The average of all %d numbers entered is %d" % (entries, 
sum/entries)





More information about the Python-list mailing list