for loop vs while loop question.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Milo Daemon
    New Member
    • Jul 2007
    • 4

    #1

    for loop vs while loop question.

    Hi, i am extremely new to python and i've been following a tutorial about learning to programm with python. After reading through the tutorial and answering the questions given by it i findally came to a question which i can't figure out!
    ***Warning: Extremely noobish, i know this***
    the question is:
    Write a program that continually reads in numbers from the user and adds them together until the sum reaches 100. Write another program that reads 100 numbers from the user and prints out the sum.

    ... i really got stuck here ... i would be happy if i just got the answer to this one so i could see it and start to understand and apply the solution myself.

    If you do chose to respond and help me out : Thanks a lot!

    (P.S i'm going on a holiday tomorrow (19.7.2007) so i will not respond for a long time ... still i'm sort of hoping i can get a reply really fast ...)
    Last edited by Milo Daemon; Jul 18 '07, 09:17 PM. Reason: Forgot to say something rather important.
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Originally posted by Milo Daemon
    Hi, i am extremely new to python and i've been following a tutorial about learning to programm with python. After reading through the tutorial and answering the questions given by it i findally came to a question which i can't figure out!
    ***Warning: Extremely noobish, i know this***
    the question is:
    Write a program that continually reads in numbers from the user and adds them together until the sum reaches 100. Write another program that reads 100 numbers from the user and prints out the sum.

    ... i really got stuck here ... i would be happy if i just got the answer to this one so i could see it and start to understand and apply the solution myself.

    If you do chose to respond and help me out : Thanks a lot!

    (P.S i'm going on a holiday tomorrow (19.7.2007) so i will not respond for a long time ... still i'm sort of hoping i can get a reply really fast ...)
    Here's the first one. The second one will be similar. [code=Python]numsum = 0
    while numsum < 100:
    numsum += int(raw_input(' Enter a number'))

    print 'The sum of the numbers you entered is %d.' % numsum[/code]HTH :)

    Comment

    • bartonc
      Recognized Expert Expert
      • Sep 2006
      • 6478

      #3
      Two (of many) ways to do the second one:[code=Python]numsum = 0
      for i in range(100):
      numsum += int(raw_input(' Enter a number'))

      print 'The sum of the numbers you entered is %d.' % numsum[/code]
      or[code=Python]numsum = 0
      i = 0
      while i < 100:
      numsum += int(raw_input(' Enter a number'))
      i += 1

      print 'The sum of the numbers you entered is %d.' % numsum[/code]

      I need to give this thread a new name, so let us know when you have read it. Thanks.

      Comment

      • Milo Daemon
        New Member
        • Jul 2007
        • 4

        #4
        ah ok love y'all i read it & thx

        Comment

        • bartonc
          Recognized Expert Expert
          • Sep 2006
          • 6478

          #5
          Originally posted by Milo Daemon
          ah ok love y'all i read it & thx
          I'm glad that you were able to dig up your thread (I was worried that you'd be unable).

          Now I can rename it.


          Welcome back!

          Comment

          • Milo Daemon
            New Member
            • Jul 2007
            • 4

            #6
            Originally posted by bartonc
            I'm glad that you were able to dig up your thread (I was worried that you'd be unable).

            Now I can rename it.


            Welcome back!
            I know sorry, long holiday -_- (added it 2 favourites so dont think it would have been that much of a problem tho)

            Comment

            • William Manley
              New Member
              • Mar 2007
              • 56

              #7
              I have a question thats not exactly related to the original topic, but is sorta related to the new name of the topic :P

              are there any differences in speed when executing a for loop or a while loop? It seems to me that for loops complete faster but I have no real way of testing it, I don't think. Was wondering if others experianced the same thing.

              Comment

              • bartonc
                Recognized Expert Expert
                • Sep 2006
                • 6478

                #8
                Originally posted by William Manley
                I have a question thats not exactly related to the original topic, but is sorta related to the new name of the topic :P

                are there any differences in speed when executing a for loop or a while loop? It seems to me that for loops complete faster but I have no real way of testing it, I don't think. Was wondering if others experianced the same thing.
                The results are a bit surprising: (Bare in mind that the import actually takes up over half of the times posted) I would have expected the call to range() to be the bottleneck.
                test3.py:[CODE=python]def forLoopTest(n):
                for i in range(n):
                pass

                def whileLoopTest(n ):
                i = 0
                while i < n:
                i += 1
                [/CODE]

                TimeTestModule. py:[CODE=python]import timeit

                test1ExecStr = \
                """from test3 import forLoopTest; forLoopTest(10) """

                t = timeit.Timer(te st1ExecStr)
                print t.timeit()

                # 14.056588477

                test2ExecStr = \
                """from test3 import whileLoopTest; whileLoopTest(1 0)"""

                t = timeit.Timer(te st2ExecStr)
                print t.timeit()

                # 13.6136176525[/CODE]

                Comment

                • ilikepython
                  Recognized Expert Contributor
                  • Feb 2007
                  • 844

                  #9
                  Originally posted by bartonc
                  The results are a bit surprising: (Bare in mind that the import actually takes up over half of the times posted) I would have expected the call to range() to be the bottleneck.
                  test3.py:[CODE=python]def forLoopTest(n):
                  for i in range(n):
                  pass

                  def whileLoopTest(n ):
                  i = 0
                  while i < n:
                  i += 1
                  [/CODE]

                  TimeTestModule. py:[CODE=python]import timeit

                  test1ExecStr = \
                  """from test3 import forLoopTest; forLoopTest(10) """

                  t = timeit.Timer(te st1ExecStr)
                  print t.timeit()

                  # 14.056588477

                  test2ExecStr = \
                  """from test3 import whileLoopTest; whileLoopTest(1 0)"""

                  t = timeit.Timer(te st2ExecStr)
                  print t.timeit()

                  # 13.6136176525[/CODE]
                  When I run the same code with 50 iterations. The for loop is definately faster than the while loop. (6.9 - 7.1 vs. 10.2 - 10.5). Changing the range() call to xrange() makes the for loop even faster (6.0 - 6.2).

                  Comment

                  • bartonc
                    Recognized Expert Expert
                    • Sep 2006
                    • 6478

                    #10
                    Originally posted by ilikepython
                    <snip> Changing the range() call to xrange() makes the for loop even faster (6.0 - 6.2).
                    Great catch, my friend. I forgot about that one. Thanks.

                    Comment

                    • William Manley
                      New Member
                      • Mar 2007
                      • 56

                      #11
                      Thanks for those, I *must* remember the timeit module.

                      At the time I thought it was just lag (I was using the for loops vs while loops in my irc bots, with 3 channels spamming it on purpose) but now it know for sure.

                      Thanks again,
                      Will.

                      Comment

                      Working...