0

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.

2
  • 8
    You are not setting foo. If you print foo you will see that it is ['a', 'b']. You maybe want to make foo = random.choice(foo) Commented Feb 5, 2019 at 19:32
  • When you say foo = ['a', 'b'], you're saying that foo is a list of two items. So when you get to if foo == 'a', that's the same as checking if the list ['a', 'b'] is the same thing as the string 'a'. Obviously this will never be the case; one is a list and the other is a string. The command print("foo is: " + random.choice(foo)) randomly picks an item from your list and prints it, but it doesn't make any changes to the list itself. random.choice(foo) just picks a random item from that list to print it. Commented Feb 5, 2019 at 19:50

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

You solution worked. I had to fix the spelling. radomly to randomly on line 4.
Sorry for the typo! Corrected it.
Did it in the morning. Thanks again for helping.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.