For loop question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

For loop question

Can anyone help me out in describing below for loop that how it works step by step, please? a = 2 b = 3 for i in range (b): a = a + a * i print (a) Output: 12

23rd May 2018, 8:44 AM
Dolan
Dolan - avatar
8 Answers
+ 4
Hi Dolan , Let me try to explain- First the variables a and b are initialized by 2 and 3, Then the loop, here variable i is by default initialized with 0 and the loop will run like- for(i=0;i<3;i++) Each step increase value of a, according to the given equation. Initially, a = 2 + 2 * 0 =2 then, a = 2 + 2 * 1 = 4 then the last iteration, a = 4 + 4 * 2 = 12 Thus, we get 12 as the output.
23rd May 2018, 9:21 AM
Sachin Artani
Sachin Artani - avatar
+ 12
sorry !!😫🙇
23rd May 2018, 9:36 AM
Prabhat
Prabhat - avatar
+ 11
The for loop that is used to iterate over elements of a sequence, it is often used when you have a piece of code which you want to repeat "n" number of time. It works like this: " for all elements in a list, do this"
23rd May 2018, 8:54 AM
Prabhat
Prabhat - avatar
+ 8
a and b are the variables and there is + operator, so the loop will run 3 times , after third condition the loop will not work because the condition is false. step 1 - a= 2 + 2 * 0 = 2 step 2 - a= 2 + 2 * 1 = 4 step 3 - a= 4 + 4 * 2 = 12 thus, we get 12 as our answer
23rd May 2018, 9:33 AM
Prabhat
Prabhat - avatar
+ 3
iteration 1: i = 0; a = 2 + 2 * 0 = 2 iteration 2: i = 1; a = 2 + 2 * 1 = 4 iteration 3: i = 2; a = 4 + 4 * 2 = 12
23rd May 2018, 9:20 AM
Ulisses Cruz
Ulisses Cruz - avatar
+ 3
Thank you all 🙏
23rd May 2018, 9:57 AM
Dolan
Dolan - avatar
+ 2
Prabhat Singh , Is step 3 correct?
23rd May 2018, 9:34 AM
Sachin Artani
Sachin Artani - avatar
0
I know the basics of for loop, but I need more detailed about this example.
23rd May 2018, 8:55 AM
Dolan
Dolan - avatar