Can u explain me the code I don't understand it....what is res in this and why error is coming....don't share code... | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 1

Can u explain me the code I don't understand it....what is res in this and why error is coming....don't share code...

First give me the step by step guide so that I can practice 🙂👇 https://code.sololearn.com/caTYXjzYHktj/?ref=app

1st Aug 2020, 8:54 AM
riya charles
riya charles - avatar
4 Antworten
+ 2
Some quick fix: def func(x): res=0 for i in range (x): res+=i return res print(func(4)) In this fixed code, the for loop is written within func, and this the "x" and "res" variable has consistent and only one meaning. 0. Declare a function called func, which takes x as its argument. 1. Called func(4), so within func, local x=4 2. Declare local res=0 within func. 3. For i in range(4), add i to res. So, res=0+1+2+3=6 4. Function func returns res=6 5. print(6)
1st Aug 2020, 9:15 AM
Panko
Panko - avatar
+ 2
riya charles Your indentation is the issue here def func(x): res=0 for i in range (x): res+=i return res print(func(4)) "res" is like a counter here for i in range(4) == 0,1,2,3 res += i means add values of i to res. Therefore, res = 0+0+1+2+3 Output: 6 Also, you can't use the return keyword outside of a function. Happy Coding 😀😀
1st Aug 2020, 9:18 AM
Tomiwa Joseph
Tomiwa Joseph - avatar
+ 1
This code can be viewed as 3 parts. (1) def func(x): res=0 This defined a function called "func", which takes one argument named "x", and then declared a local variable called "res", which is assigned to zero. Note that since there is no return nor print statement, this function shows no output by itself. (2) for i in range (x): res+=i return res This is a for loop that runs "x" times, where x should be an integer and res should be something numeric, and they both should be declared beforehand to avoid NameError. Note that this block has same indentation level as the previous block (i.e. "def" in (1) is aligned with "for" in (2)), which makes the whole block global (not local/not within func), so the x, res written in this block [have different meaning with that in block (1)]. Also, you can't use return outside the function. (3) print(func(4)) You tried to call the func function with x=4, and print out its returned value, since func doesn't returns anything, you will see "None" in output.
1st Aug 2020, 9:08 AM
Panko
Panko - avatar
+ 1
Thank u all for your help I now understand it..I'll practice this code again now And happy coding to all of u ☺😊😃👋👌
1st Aug 2020, 9:35 AM
riya charles
riya charles - avatar