Skip to content
Advertisement

Python random.choice same output

I’m trying to random some strings in a variable,

myTest = random.choice(["test1","test2","test3"])
print(myTest)
print(myTets)
print(myTest)

And when I’m running my script all of them are the same every time,

test1
test1
test1

I like to random my variable every time I’m calling it, like,

test1
test3
test2

Advertisement

Answer

This is basically the same as

x = 42
print(x)
print(x)
print(x)

A variables value only changes when you assign it:

x = 42
print(x)
x = 45
print(x)

If you want a new random value, you need to call the function again:

l = [1, 2, 3, 4, 5]
x = random.choice(l)
print(x)
x = random.choice(l)
print(x)
Advertisement