+ 1

Def Quiz

Would like to know if the order sequence is right, and would like to know how to get the function to print This solution most probably will result in no output def sum(x): #def with the ":" res = 0 #remember the indintation, TAB you can't use for in the second line. for i in range(x): #again TAB then the for loop res += i #then TAB and the i part return res #again TAB then return #You can see that there is no print line, so no output https://code.sololearn.com/cBv7QQbw0a2J/?ref=app

7th May 2018, 1:16 AM
Medo Hamdani
Medo Hamdani - avatar
6 Antworten
+ 10
I'll gladly help! Python isn't my strong suit, but I'm sure I know enough to answer this. And feel free to tag me when you have questions! :) Answering on your code would have been fine, by the way. So you're asking how to print out what you're returning from sum(), right? First off, sum() is written correctly, and is all in the right order. Second, you can so one of three things to print: 1. Print the result inside sum() by replacing "return res" with "print(res)". 2. Make a variable that takes the returned value, then prints it. Ex: result = sum(8) print(result) 3. Print the function call directly. Ex: print(sum(12)) The reason the variable res is there is because it holds the running total. The for adds every number from 0 to x into res. If you used x = 0, you would overwrite the value that was sent in, and sum() would always return 0.
7th May 2018, 3:10 AM
Tamra
Tamra - avatar
+ 12
You don't mean for the counter, do you? The for and range() take care of that.
7th May 2018, 5:38 AM
Tamra
Tamra - avatar
+ 1
... to print an output. What is the point of res = 0 here, can we just use x = 0
7th May 2018, 1:18 AM
Medo Hamdani
Medo Hamdani - avatar
+ 1
Tamra here please. ignore the first tag. if you want me to stop tagging you in future questions if any, please do let me know.
7th May 2018, 2:58 AM
Medo Hamdani
Medo Hamdani - avatar
+ 1
is always when we use for loop to use var += i or similar to it.
7th May 2018, 5:33 AM
Medo Hamdani
Medo Hamdani - avatar
0
noted with many thanks
7th May 2018, 5:42 AM
Medo Hamdani
Medo Hamdani - avatar