+ 1

Can someone explain me a few things about python?

So if there is a code like this: for c in char: char += 1 Or something. I don't usually see the "c" defined anywhere. And neither do I see the "char" being defined. Why? Same thing with functions: def random_func(func, arg) xxxx xxx yyyyyy The "func" and "arg" are never defined. So what are they and how do they magically work? Am I missing something here? If I even try to use undefined variables, oh boy does the system remind me. But in Sololearn's examples, this never happens.

29th Dec 2019, 3:52 PM
Ville Nordström
Ville Nordström - avatar
3 Respostas
+ 1
for c in char: char += 1 You ask you program to put every value of "char" variable into "c". 1 by 1 with each loop run. "c" exists only when the loop is running. "char" should be defined before this loop. def random_func(func, arg): pass "func, arg" aren't variables. Treat them as a placeholder for everything you put in a function. For example: def add(first, second): return first + second print(add(15, 20)) Output: 35. "first" is 15 and "second" is 20 in this example.
29th Dec 2019, 7:43 PM
Daniil Kovalenko
Daniil Kovalenko - avatar
+ 1
For simplification, you can see loop variables and function parameters as just another style of assigning. See 'for c in chars' as 'Please do c = letter for every letter in chars'. (You can test it: After the loop is over, the variable still has the last value.) See a function definition like 'def f(x)' as meaning: 'Whenever I call the function f, please do x = the argument I pass'.
29th Dec 2019, 4:53 PM
HonFu
HonFu - avatar