user2795843
user2795843

Reputation: 33

Random choice works but only sometimes

import random

mylist = ["a", "b", "c"]
mynums = ["1","2","3"]
myint = ["6","7","8"]
random.choice (mylist)

if random.choice(mylist) == "a":
    print ("a")
    random.choice (mynums)
    print (random.choice (mynums))

if random.choice(mylist) == "b":
    print ("b")
    random.choice (myint)
    print (random.choice (myint))

if random.choice(mylist) == "c":
    print ("c")

Now this code works for the most part, however sometimes after running; it will either execute without displaying anything, or it will pick two letters during the same run.

(I'm also new to python and I am open to any suggestion to make my above code "neater/faster". But please explain the change, I'd like to understand it before I change it.)

edit Thank you all very much! you are all extremely helpful, and fast I might add.

Upvotes: 2

Views: 321

Answers (3)

Graeme Stuart
Graeme Stuart

Reputation: 6063

This could be simplified to the following.

import random

mylist = ["a", "b", "c"]
mynums = ["1","2","3"]
myint = ["6","7","8"]
letterChoice = random.choice (mylist)
numberChoice = random.choice (mynums)
intchoice = random.choice (myint)

print (letterchoice)
if letterChoice == "a":
    print (numberChoice)
elif letterChoice == "b":
    print (intChoice)

Upvotes: 0

Jon Clements
Jon Clements

Reputation: 142256

@jonhopkins has explained why what's happening is happening, but you could make it a bit cleaner by putting the letter and list it refers to as pairs, and then structure the code as the following:

import random

mynums = ["1","2","3"]
myint = ["6","7","8"]
mylist = (('a', mynums), ('b', myint), ('c', None))

letter, opts = random.choice(mylist)
print letter
if opts:
    print random.choice(opts)

Upvotes: 2

jonhopkins
jonhopkins

Reputation: 3842

You are getting a new random letter in each if statement. There is a possibility that the new choice won't be the letter that you're comparing, or it could even be the letter you're comparing every time. There's no way to know. If you just want to get a single random letter from the list and do something based on which one it was, store it in a variable and use the variable in your if statements instead.

import random

mylist = ["a", "b", "c"]
mynums = ["1","2","3"]
myint = ["6","7","8"]
letterChoice = random.choice(mylist)

if letterChoice == "a":
    print ("a")
    numberChoice = random.choice(mynums)
    print (numberChoice)

if letterChoice == "b":
    print ("b")
    intChoice = random.choice(myint)
    print (intChoice)

if letterChoice == "c":
    print ("c")

Upvotes: 11

Related Questions