Function's arguments | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

Function's arguments

hey guys, i have got a little problem with this part of a code: it has to change the default value of an argument of a function https://code.sololearn.com/cNNkMA0asY22/?ref=app the commented part doesn't work, instead the code below run correctly is it an 'elegant' solution? is there a better way to make this code run correctly?

18th Jul 2017, 9:26 AM
Daniele
Daniele - avatar
2 Answers
0
Hello ! The principle of a default parameter is that it won't change and is used when no parameter is provided on function call. So in your example, set the default parameter to a value in the function definition: def f(val=2) then when you call f() -> val equals 2. If you need to set val to another value, call the function with a parameter : f(val=5) Another comment, global variable are often not recommended. Your f() function should instead return a value. Like this : def f(val=2): print(val) return val yourval = f() # This will print 2 and set yourval to 2 yourval = f(5) # This will print 5 and set yourval to 5
18th Jul 2017, 10:27 AM
Burrich
0
thank you @Burrich , i used this method because i have to call different functions imported from an external file all these functions refer to an object which change during the program to avoid re-writing the reference of the object in each functions i tried to use this ploy the other solution to avoid using global variable could be to creating a class..
18th Jul 2017, 11:19 AM
Daniele
Daniele - avatar