0

Module 3 Quiz - Functions and Modules: Last Question.

I struggled with this question and found the answer, so I thought I'd share. def func(x): # defines the function name and input parameter res=0 # created a variable that is right now set to 0 for i in range(x): # this has two parts, for-loop, and a range function both explained below res += i # this adds 1 to the variable 'res' each time the for-loop loops return res # end of the function, passes the variables value back to the caller print(func(5)) # call the function while passing 5 as an argument # for i in range(5) = i in range of [0, 1, 2, 3, 4] # so res += i # is res += [0,1,2,3,4] # since res = 0 # 0 += 1 + 2 + 3 + 4 = 10 def func(x): # defines the function name and input parameter res=0 # created a variable that is right now set to 0 for i in range(x): # this has two parts, for-loop, and a range function both explained below res += i # this adds 1 to the variable 'res' each time the for-loop loops return res # end of the function, passes the variables value back to the caller print(func(10)) # call the function while passing 10 as an argument # it will print 0+1+2+3+4+5+6+7+8+9=45

3rd Apr 2018, 12:42 PM
Rafael Tousignant
1 Antwort
+ 1
See a community comment section on this question. Someone may post a method to fix it. Rafael Tousignant
3rd Apr 2018, 1:55 PM
Warith Vatanaplachaigoon
Warith Vatanaplachaigoon - avatar