What is the output of this code? def func(x): res = 0 for i in range(x): res += i return res print(func(4)) how we got the output as 6?
4/17/2020 10:08:12 AM
PRIYANKA K3 Answers
New AnswerThe for loop will run from 0 to 3 as the range is till 4. Initialally, the i is 0. Then i will become 1. 1 is added to result Then i will become 2. 2 is added to result. Similarly i will become 3. Now 3 is added to the result. So result will be 0+1+2+3 i.e. 6
The output is 4. It is 4 because the for loop is executed 4 times. Each time adding 1 to the variable "res" which starts at 0. If you want 6 as the output, either make rs == 2 or x ==6
Sololearn Inc.
535 Mission Street, Suite 1591Send us a message