473,221 Members | 1,832 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,221 software developers and data experts.

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 ...)
Jul 18 '07 #1
10 6234
bvdet
2,851 Expert Mod 2GB
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.
Expand|Select|Wrap|Line Numbers
  1. numsum = 0
  2. while numsum < 100:
  3.     numsum += int(raw_input('Enter a number'))
  4.  
  5. print 'The sum of the numbers you entered is %d.' % numsum
HTH :)
Jul 18 '07 #2
bartonc
6,596 Expert 4TB
Two (of many) ways to do the second one:
Expand|Select|Wrap|Line Numbers
  1. numsum = 0
  2. for i in range(100):
  3.     numsum += int(raw_input('Enter a number'))
  4.  
  5. print 'The sum of the numbers you entered is %d.' % numsum
or
Expand|Select|Wrap|Line Numbers
  1. numsum = 0
  2. i = 0
  3. while i < 100:
  4.     numsum += int(raw_input('Enter a number'))
  5.     i += 1
  6.  
  7. print 'The sum of the numbers you entered is %d.' % numsum
I need to give this thread a new name, so let us know when you have read it. Thanks.
Jul 19 '07 #3
ah ok love y'all i read it & thx
Aug 9 '07 #4
bartonc
6,596 Expert 4TB
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!
Aug 10 '07 #5
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)
Aug 10 '07 #6
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.
Aug 12 '07 #7
bartonc
6,596 Expert 4TB
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:
Expand|Select|Wrap|Line Numbers
  1. def forLoopTest(n):
  2.     for i in range(n):
  3.         pass
  4.  
  5. def whileLoopTest(n):
  6.     i = 0
  7.     while i < n:
  8.         i += 1
  9.  
TimeTestModule.py:
Expand|Select|Wrap|Line Numbers
  1. import timeit
  2.  
  3. test1ExecStr = \
  4. """from test3 import forLoopTest; forLoopTest(10)"""
  5.  
  6. t = timeit.Timer(test1ExecStr)
  7. print t.timeit()
  8.  
  9. # 14.056588477
  10.  
  11. test2ExecStr = \
  12. """from test3 import whileLoopTest; whileLoopTest(10)"""
  13.  
  14. t = timeit.Timer(test2ExecStr)
  15. print t.timeit()
  16.  
  17. # 13.6136176525
Aug 12 '07 #8
ilikepython
844 Expert 512MB
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:
Expand|Select|Wrap|Line Numbers
  1. def forLoopTest(n):
  2.     for i in range(n):
  3.         pass
  4.  
  5. def whileLoopTest(n):
  6.     i = 0
  7.     while i < n:
  8.         i += 1
  9.  
TimeTestModule.py:
Expand|Select|Wrap|Line Numbers
  1. import timeit
  2.  
  3. test1ExecStr = \
  4. """from test3 import forLoopTest; forLoopTest(10)"""
  5.  
  6. t = timeit.Timer(test1ExecStr)
  7. print t.timeit()
  8.  
  9. # 14.056588477
  10.  
  11. test2ExecStr = \
  12. """from test3 import whileLoopTest; whileLoopTest(10)"""
  13.  
  14. t = timeit.Timer(test2ExecStr)
  15. print t.timeit()
  16.  
  17. # 13.6136176525
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).
Aug 12 '07 #9
bartonc
6,596 Expert 4TB
<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.
Aug 12 '07 #10
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.
Aug 13 '07 #11

Sign in to post your reply or Sign up for a free account.

Similar topics

33
by: Arthur | last post by:
>>>a= >>> for p in a: print p 1 2 3 >>> p 3 My naive expectation was that p would be 'not defined' from outside
0
by: John Wilson | last post by:
Hello, I have the following code which populates as table data from a SQL Server 2000 stored proc (RSByDemoID2). Below that is the view and stored procedure which takes @DemoID as input to match...
3
by: zeroDoNotYeSpamtype | last post by:
(I tried to post this earlier, but it seems without success) A similar question to this has been answered many times, to whit the question applying when the index variable of a for loop is...
3
by: Gustavo Randich | last post by:
The following seems to be a bug. The execution returns rows 1,2. It should return 1,1. In fact, if I run the code within a stored procedure alone (not in a trigger), the loop doesn't overwrite the...
22
by: Jan Richter | last post by:
Hi there, the Code below shows DJBs own implementation of strlen (str_len): unsigned int str_len(char *s) { register char *t; t = s; for (;;) { if (!*t) return t - s; ++t;
8
by: Shamrokk | last post by:
My application has a loop that needs to run every 2 seconds or so. To acomplish this I used... "Thread.Sleep(2000);" When I run the program it runs fine. Once I press the button that starts the...
29
by: garyusenet | last post by:
I'm trying to investigate the maximum size of different variable types. I'm using INT as my starting variable for exploration. I know that the maximum number that the int variable can take is:...
3
by: nina297 | last post by:
Good morning, How do I set up a For each loop to loop through my records in the database? My fields are topics, question and answers. I want the one topic displayed that goes with each...
44
by: James Watt | last post by:
can anyone tell me how to do an infinite loop in C/C++, please ? this is not a homework question .
2
by: perkykoala | last post by:
I apologize in advance for being REALLY detailed/verbose. It's the result of staring/tweaking code for too long. Using VB 2005: I need to design a multiple choice test (unfortunately, I can't...
1
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: mar23 | last post by:
Here's the situation. I have a form called frmDiceInventory with subform called subfrmDice. The subform's control source is linked to a query called qryDiceInventory. I've been trying to pick up the...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
by: jimatqsi | last post by:
The boss wants the word "CONFIDENTIAL" overlaying certain reports. He wants it large, slanted across the page, on every page, very light gray, outlined letters, not block letters. I thought Word Art...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.