Ask your own question, for FREE!
MIT 6.189 A Gentle Introduction to Programming Using Python (OCW) 17 Online
OpenStudy (anonymous):

So I'm trying to write a for loop to compute the first 20 integers for 4k + 1 in python. I've done a little programming in matlab before, but I'm a complete noob at python. How do I write the loop?

OpenStudy (anonymous):

k = 1; #This is our k value; it will be increased by 1 every time we loop k_max = 20; #This is the number we will want to stop at total = 0; #This variable will keep track of our total while k <= k_max: #While our value of k is less than or equal to the maximum k value #Notice how the following is tabbed in? #Anything tabbed under the "while" loop will repeat until k > k_max total = total + (4*k + 1) #Set "total" equal to the previous value of total, plus (4k+1) k = k + 1 #Add one to k print total; #After the loop is done, print the value of "total" to the screen

OpenStudy (anonymous):

Without comments: k = 1; k_max = 20; total = 0; while k <= k_max: total = total + (4*k + 1) k = k + 1 print total;

OpenStudy (anonymous):

Let me know if you need any further explanation! I got 860.

OpenStudy (anonymous):

Thanks! I actually need all of the results from each iteration printed or stored in a vector.

OpenStudy (rsmith6559):

As a for loop: for k in xrange( 1, 21, 1 ): range() and xrange() can be called three ways: 1. With one argument: k would be the first value AFTER the loop, zero is assumed to start and it's incremented by one. 2. first number is the start value, second the first AFTER the loop, incremented by one 3. First two numbers are the same as 2, the third number is the increment.

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