Infinite loops and string comparision in a lists

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ambo2011
    New Member
    • Nov 2011
    • 6

    Infinite loops and string comparision in a lists

    I am a new programmer, learning python. I have written this code but I need help
    1. Make an infinite loop so that the user can enter many numbers into the list.
    2. Make a provision for a infinite loop to end, like typing the word "Done".
    Here is the code:
    Code:
    print "Welcome to average script "
    
    def main():
        #declaration of an empty list avg
        avg = []
        loop = 1
        while loop ==1:
            try:
                
                avg.append( int(raw_input("Enter the first number you want average: \n")))   
                avg.append( int(raw_input("Enter the second number you want average: \n")))
                avg.append( int(raw_input("Enter the third number you want average: \n")))
    
                print "The list is: ", avg
                ambo = len(avg)
                print "The number of members in the list is: ", ambo
                s = sum(avg)
                print "The sum of the enterd numbers is: ",s
                a = float (s/ambo)
                print "The average of the enterd members of the list are: ", a
                break
            except ValueError:
                print "\n Please Enter a number (Integer)"
            
            try:
                loop = input("Press 1 to try again: ")
                avg = []
            except NameError:
                loop = 1
           
            continue           
    main()
    Last edited by Meetee; Nov 24 '11, 08:11 AM. Reason: code tags added
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    Hi

    Thanks for posting. Here's some methods that might help
    Code:
    mylist=[]
    while 1:
        a=raw_input("enter number: ")
        if a=="done": break
        try:
            mylist.append(float(a))
        except:
            print "invalid input."
    print mylist, sum(mylist)/max([len(mylist),1])
    I haven't tested it but hopefully it makes sense.

    Comment

    • ambo2011
      New Member
      • Nov 2011
      • 6

      #3
      Hi Glenton,
      Thanks so much, it works perfectly as i expected.

      Comment

      Working...