Sighs....module 3 question 2 is really giving me problem ...pls who can help out vbeen stuck on it for weeks | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Sighs....module 3 question 2 is really giving me problem ...pls who can help out vbeen stuck on it for weeks

19th Sep 2016, 4:58 AM
Stephen Antai
Stephen Antai - avatar
4 Answers
+ 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!
20th Sep 2016, 1:43 PM
Luke Armstrong
0
can you put the question here? kinda hard to find which question you mean exactly...
19th Sep 2016, 6:00 AM
Luke Armstrong
0
Functions and modules the quiz question(question 2)
20th Sep 2016, 1:01 PM
Stephen Antai
Stephen Antai - avatar
0
thanks...really appreciate it
20th Sep 2016, 9:14 PM
Stephen Antai
Stephen Antai - avatar