Arthur V
Arthur V

Reputation: 91

Unable to set a new variable after using the random command in Python

I'm very new to Python and I'm having an issue setting a new variable after using the random command.

Here is my sample code:

import random

foo = ['a', 'b']
print("foo is: " + random.choice(foo))

if foo == 'a':
    randomLetter = 'a'
else:
    randomLetter = 'b'

print(randomLetter)

No matter what foo equals, randomLetter always equals b.

I'm not sure what I am doing wrong. Any help with be appreciated.

Upvotes: 0

Views: 55

Answers (2)

taurus05
taurus05

Reputation: 2546

import random

foo = ['a', 'b']
randomly_selected = random.choice(foo)
print("foo is: " + randomly_selected)

if randomly_selected == 'a':
    randomLetter = 'a'
else:
    randomLetter = 'b'

print(randomLetter)

foo is a list containing two alphabets. Using random, if you wish to select a random element, you can do so using random.choice(foo). But, if you want to use the output of this elsewhere in your code, you will have to store the result in a different variable and then check condition in the code, accordingly.

Upvotes: 2

Paul
Paul

Reputation: 89

random.choice needs to be assigned to a variable...

letters=["a","b"]
randomLetter = random.choice(letters)
print(randomLetter)

What happened in your code is, that foo was never equal to "a" so it jumped in the else condition

randomLetter = 'b'

Where you assigned randomLetter its value, wich is then printed

Upvotes: 2

Related Questions