1

I am trying to write a program that asks the user to enter two colors and then display the resulting color. This is what I have so far:

#Define function that prompts user to enter data
def ask():
    color1=input('Enter name of first primary color:')
    color2=input('Enter name of second primary color:')
    mixColors(color1,color2)
#Write function that displays the different color combinations
def mixColors(color1,color2):
    if color1==red and color2==blue:
        print('Mixing red and blue, you get purple.')
    elif color1==blue and color2==red:
        print('Mixing blue andred, you get purple.')
    elif color1==red and color2==yellow:
        print('Mixing red and yellow, you get orange.')
    elif color1==yellow and color2==red:
        print('Mixing yellow and red, you get orange.')
    elif color1==blue and color2==yellow:
        print('Mixing blue and yellow you get green.')
    elif color1==yellow and color2==blue:
        print('Mixing yellow and blue, you get green.')
    else:
        print("I don't know what you get by mixing", color1,'and',color2,'.')
ask()

When I run the program, this error message appears:

Traceback (most recent call last):
  File "/Users/Lin/Documents/Spring Semester 2013/Computer Programming/yuan_linCh0405", line 23, in <module>
    ask()
  File "/Users/Lin/Documents/Spring Semester 2013/Computer Programming/yuan_linCh0405", line 6, in ask
    mixColors(color1,color2)
  File "/Users/Lin/Documents/Spring Semester 2013/Computer Programming/yuan_linCh0405", line 9, in mixColors
    if color1==red and color2==blue:
NameError: global name 'red' is not defined
2
  • You should use a dictionary with keys ('red','blue'), ('blue','red'),('red','yellow'), etc Commented Feb 16, 2014 at 18:12
  • If you use frozensets as the keys you can reduce the number of items in your dictionary Commented Feb 16, 2014 at 20:52

1 Answer 1

6

In Python, strings have to be enclosed with single or double quotes (' or "). Otherwise they will be treated as variables.

In this case, red is neither a variable nor a string. Since red is not a string, Python searches for red in the current namespace, parent namespace and the global namespace. But the variable red is NOT found in any of them. So, it gives up and throws that error message.

So, all the if conditions should have been

if color1=="red" and color2=="blue":
...
elif color1=="blue" and color2=="red":
...
elif color1=="red" and color2=="yellow":
...
elif color1=="yellow" and color2=="red":
...
elif color1=="blue" and color2=="yellow":
...
elif color1=="yellow" and color2=="blue":
...
Sign up to request clarification or add additional context in comments.

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.