Jack Ingof
Jack Ingof

Reputation: 9

For loop not saving variable outside the loop

Im not sure why but my code does not display the contents of the variable for each colour selected when I ask it to print it after the loop has concluded. When the program runs, all it outputs is a blank line which no text outputted.

If anyone could give a pointer that'd be vert helpful, thanks.

def inputs(): firstColour = "" #Variables for each of the three colours determined by entered letters in for loop secondColour = "" thirdColour = "" patchSize = "" #States the number of patches in the grid

for i in range(3):

    patchColour = input ("Please choose a colour: r, g, b, m, c, o: ").lower()

    if patchColour == "r":
        colour = "red"
        print (colour)
    elif patchColour == "g":
        colour = "green"
        print (colour)
    elif patchColour == "b":
        colour = "blue"
        print (colour)
    elif patchColour == "m":
        colour = "magneta"
        print (colour)
    elif patchColour == "c":
        colour = "cyan"
        print (colour)
    elif patchColour == "o":
        colour = "orange"
    else:
        print("No valid input has been entered")
        break

    if i == 0:
        colour == firstColour
    elif i == 1:
        colour == secondColour
    elif i == 2:
        colour == thirdColour

    print(firstColour, secondColour, thirdColour)

Upvotes: 1

Views: 992

Answers (1)

KJTHoward
KJTHoward

Reputation: 876

This section:

if i == 0:
    colour == firstColour
elif i == 1:
    colour == secondColour
elif i == 2:
    colour == thirdColour

Should be:

if i == 0:
    firstColour = colour
elif i == 1:
    secondColour = colour
elif i == 2:
    thirdColour = colour

"==" is used for comparing if items are the same, "=" is used to assign a value to a variable. Additionally colour and firstColour etc... were the wrong way round. As You later print out firstColour you need to asign a value to it first

Upvotes: 1

Related Questions