0

Can someone explain me why the result is the same, please?

https://code.sololearn.com/cI031FSmL0TD/?ref=app

13th Dec 2019, 3:44 PM
Krasimira
Krasimira - avatar
3 Answers
+ 3
Default values of a function can be tricky. This occurs not just with numbers, but also with strings, lists, and other data types. When the function runs for the first time, it saves the variable as a local one. After that, each time the function runs again (if no value is given ofc), it will read from the last saved state of the variable. So in your case, x takes a random value, and it is saved to the function, and will remain the same. If you want a different value every time you run it, you must give x a default value of None, here is how to do it: https://code.sololearn.com/cfvPu09hlVw4/?ref=app
13th Dec 2019, 3:51 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 3
Krasimira no problem! As I said, this also occurs with other data types, let's say for example you function takes an empty list as a default argument, and appends to it. It might seem that it will create a new list everytime, but in fact it just keeps adding to the old list, here is an example: https://code.sololearn.com/cHb8CAoun9dg/?ref=app
13th Dec 2019, 3:56 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
0
Thank you!
13th Dec 2019, 3:54 PM
Krasimira
Krasimira - avatar