Change a variable given in a function
Question:
I want to make a function that checks if a random number is within a certain value and if it is then reroll the number for that variable.
But I don’t know how to set the input variable without calling its name directly.
code:
def checkVal(value,max,min):
if value<max or value>min:
value=random.randrange((-30/10),(30/10))
checkVal(value,min,max)
else:
pass
Answers:
You can’t charge a variable from within a function without using a global
, however this wouldn’t be good practice here. Rather return
your value.
Also your test would always be True if max>min, you probably meant to swap the conditions (lower > value or value > upper
).
def checkVal(value, upper, lower):
if lower > value or value > upper):
value = random.randrange((-30/10),(30/10))
return checkVal(value, upper, lower)
return value
value = checkVal(value, upper, lower)
From an algorithmic point of view, using a recursive function as a loop is also not so good practice. Rather use a while
loop:
def checkVal(value, upper, lower):
while lower > value or value > upper:
value = random.randrange((-30/10),(30/10))
return value
value = checkVal(value, upper, lower)
Finally, you can probably remove the loop entirely by choosing directly the correct bounds:
def checkVal(value, upper, lower):
if lower > value or value > upper:
value = random.randrange(max(lower, (-30/10)), min(upper, (30/10)))
return value
value = checkVal(value, upper, lower)
I want to make a function that checks if a random number is within a certain value and if it is then reroll the number for that variable.
But I don’t know how to set the input variable without calling its name directly.
code:
def checkVal(value,max,min):
if value<max or value>min:
value=random.randrange((-30/10),(30/10))
checkVal(value,min,max)
else:
pass
You can’t charge a variable from within a function without using a global
, however this wouldn’t be good practice here. Rather return
your value.
Also your test would always be True if max>min, you probably meant to swap the conditions (lower > value or value > upper
).
def checkVal(value, upper, lower):
if lower > value or value > upper):
value = random.randrange((-30/10),(30/10))
return checkVal(value, upper, lower)
return value
value = checkVal(value, upper, lower)
From an algorithmic point of view, using a recursive function as a loop is also not so good practice. Rather use a while
loop:
def checkVal(value, upper, lower):
while lower > value or value > upper:
value = random.randrange((-30/10),(30/10))
return value
value = checkVal(value, upper, lower)
Finally, you can probably remove the loop entirely by choosing directly the correct bounds:
def checkVal(value, upper, lower):
if lower > value or value > upper:
value = random.randrange(max(lower, (-30/10)), min(upper, (30/10)))
return value
value = checkVal(value, upper, lower)