0
Sighs....module 3 question 2 is really giving me problem ...pls who can help out vbeen stuck on it for weeks
4 Réponses
+ 1
Ok, so the objective is to make a function that adds up all the numbers up to a certain point. Thankfully we dont have to write the code, just rearrange it.
So our first step is to create a function that takes an argument (the number we wish to stop adding at). So the top line would be
def sum (x):
next we know that our function has to give back the manioulated number, so we will have to return something. However, we have to manipulate before we return it, so return comes at the end. This means the last line is
return res
Now that the easy part is done, we have to manipulate the data. We do it with a for loop. it counts from 0 to x using the range () function. and for each number in that range, we want to add it to a total. The thing is, if we say res = 0 inside the for loop, then every time the loop runs, res will always begin at 0 instead of having numbers added. so we have to declare res outside the loop and then use the loop to just add the numbers to it. So our middle 3 lines read as follows
res = 0
for i in range (x):
res += i
So for the whole function...
def sum (x): #take a max number and start function
res = 0 #declare the variable outside the loop
for i in range (x): #cycle each number from 0-x
res += i #add the number to res
return res #send the total number back to whatever called the function.
Hope that helps! feel free to ask a follow up!
0
can you put the question here? kinda hard to find which question you mean exactly...
0
Functions and modules the quiz question(question 2)
0
thanks...really appreciate it