In the following code, a random value is generated as expected:
import random
for i in range(10):
print(random.randint(0,10))
However, this does not work if I use a function:
import random
def f(val: int = random.randint(0,10)):
print(val)
for i in range(10):
f()
Why is the result of the second code snippet always the same number? The most similar question I could find is this one, but it refers to a different language (I don't master) .
The default argument expression isn't evaluated when you call the function, it's evaluated when you create the function. So you'll always get the same value no matter what you do.
The typical way around this is to use a flag value and replace it inside the body of the function:
def f(val=None):
if val is None:
val = random.randint(0,10)
print(val)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With