Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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)

Solution 2:

You'll want to have the default value be a specific value. To make it be dynamic like that, you'll want to default it to something else, check for that, and then change the value.

For example:

import random

def f(val=None):
    if val is None:
        val = random.randint(0,10)
    print(val)

for i in range(10):
    f()

Solution 3:

The default param can't be changed on calling. I can't understand why it needed. you can do simply like this.

import random
def f():
  print(random.randint(0,10))
for i in range(10):
  f()

Post a Comment for "Python Function Default Argument Random Value"