Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 40 Online
OpenStudy (anonymous):

The code: ``` x=4 for j in range (x): for i in range (x): print i x=2 ``` prints as result: 0 1 2 3 0 1 0 1 0 1 Why?

OpenStudy (e.mccormick):

Umm... you have some inteting issues in what you pasted. I do not know what indenting you meant. Try adding some more prints to see what happenes: ``` x=4 for j in range (x): print "j cycled" for i in range (x): print "i cycled" print i x=2 ```

OpenStudy (anonymous):

Hey e.mccormick (just wandering if you are a guy or a gilr...), how have you been? Well, I found this code on Mr. Guttag's textbook Introduction to Computation and Programming Using Python. On pg. 24, Spring 2013 edition, it shows this code and what is prints. Furthermore, it gives a piece of explanation: The code prints that outcome because the "range" function in the outer loop is evaluated only once, but the range function in the inner loop is evaluated each time "for" statement is reached. I tried to evaluate each step of the code by writing the outcomes on a sheet (yes, hand work). I have too say I got a very different result. And I have to admit I did not understand Mr. Guttag's explanation. Any idea? Thanks.

OpenStudy (anonymous):

The code you posted does not execute, there are indentation errors as e.mccormick pointed out. However, assuming correct indendation, here's what happens in pseudo code: 1. Do everything that follows four times (t1, t2, t3, t4). 2. Print I for the range of 0 to x (excluding x) So this is what happens: t1: print 0, 1, 2, 3 t2: x is now 2, so print 0, 1 t3: print 0, 1 t4: print 0, 1

OpenStudy (anonymous):

Hey, dust7, how are you doing? At first I thought there was an error in indentation. So I wrote the code and it worked very well. I now understand what happened. Thanks a lot :)

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Latest Questions
Twaylor: I wrote a song a while back (No AI used), and I just found it:
19 hours ago 18 Replies 4 Medals
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!