[Python] Need help simplifying - generating random items from a pre-set list

Discussão em 'Python' iniciado por Stack, Setembro 14, 2024.

  1. Stack

    Stack Membro Participativo

    I know there's an easier way to do this. It is supposed to be a "Simon" like game where you generate 5 random colors from the list and the user enters the colors. Each turn it should keep the 1st color the same and add a new random color, which is where my trouble is coming in.

    import random
    # Create a list of colors.
    colors = ['Yellow', 'Green', 'Red', 'Blue']

    # Generate random colors from the list.
    color1 = random.choice(colors)
    color2 = random.choice(colors)
    color3 = random.choice(colors)
    color4 = random.choice(colors)
    color5 = random.choice(colors)


    # Simon displays the 5 color choices, adding 1 each turn.

    print "Simon says: ", color1
    raw_input ("What did Simon say? ")

    print "Simon says: ", color1, color2
    raw_input ("What did Simon say? ")

    print "Simon says: ", color1, color2, color3
    raw_input ("What did Simon say? ")

    print "Simon says: ", color1, color2, color3, color4
    raw_input ("What did Simon say? ")

    print "Simon says: ", color1, color2, color3, color4, color5
    raw_input ("What did Simon say? ")


    My first try looked like this but was not working either:

    # Create a list of colors.
    colors = ['Yellow', 'Green', 'Red', 'Blue']


    # Display the color list, adding one random color each turn. Prompt the
    # user to enter the colors after each is added.
    for i in range (5):
    import random
    color = random.choice(colors)

    print "Simon says: " ,color

    raw_input ("What did Simon say? ")
    colors.append(colors)
    print "Simon says: " , (color)

    Continue reading...

Compartilhe esta Página