mushishi
mushishi

Reputation: 151

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

Upvotes: 3

Views: 1547

Answers (3)

dauren slambekov
dauren slambekov

Reputation: 390

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

Upvotes: 0

Ken Kinder
Ken Kinder

Reputation: 13120

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

Upvotes: 1

Mark Ransom
Mark Ransom

Reputation: 308111

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)

Upvotes: 6

Related Questions