Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)
edited by

When I try to put this python code within the input 12, I get the answer is 0, 6, 18. I don't know how to calculate that and I keep visualizing it as code snippet 2, with the answers 0,0,1,3,6,6,8,12.

How does this loop work?

stop=int(input())

result=0

for a in range(5): 

  for b in range(4): 

    result += a * b

  print(result)

  if result > stop: 

    break 

What I calculate

stop=int(input())

result=0

for a in range(5): 

  for b in range(4): 

    result += a * b

    print(result)

  if result > stop: 

    break 

1 Answer

0 votes
by (36.8k points)

I will walk you through the for in range(5) loop.

First, a = 0, result = 0.

This loops 4 times and result remains at 0 because 0 * b = 0

0 is printed

Next, a = 1, result = 0.

The Result += 1x0 + 1x1 + 1x2 + 1x3

So result = 0 + 6

6 is printed

Finally, a = 2, result = 6.

Result += 2x0 + 2x1 + 2x2 + 2x3

So result = 6 + 12 = 18

18 is printed

if result > stop evaluates to true so your loop is broken.

If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Oct 10, 2019 in Python by Sammy (47.6k points)

Browse Categories

...