Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function default argument random value

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) .

like image 439
mushishi Avatar asked Feb 01 '26 05:02

mushishi


1 Answers

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)
like image 168
Mark Ransom Avatar answered Feb 02 '26 21:02

Mark Ransom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!