0

For learning (and testing) I made this simple dictionary with a small query in Python. but I allways get a NameError and I just can't figure out what's wrong

the Code:

#!/usr/bin/env python3

def getColor(color):
    Colors = {"red":"FF0000","green":"00FF00","blue":"0000FF"}
    return Colors[color]

inputColor = str(input("Please input a color: "))
getColor(inputColor)

The Traceback:

Please input a color: blue
Traceback (most recent call last):
  File "DictionaryTest", line 7, in <module>
    inputColor = str(input("Please input a color: "))
  File "<string>", line 1, in <module>
NameError: name 'blue' is not defined

the Solution

apperently there was a solution for this problem here is my working code:

#!/usr/bin/env python3

def getColor(color):
    Colors = {"red":"FF0000","green":"00FF00","blue":"0000FF"}
    print Colors[str(color)]

inputColor = str(raw_input("Please input a color: "))
getColor(inputColor)
globus243
  • 710
  • 1
  • 15
  • 31
  • You created a dictionary in the variable called `Farben`, but where is `Colors` defined? – Will Vousden May 06 '15 at 07:14
  • crap this isn't an error, I translated my code to english for better understanding and forgot to translate this one. sorry, changed it. – globus243 May 06 '15 at 07:15
  • 1
    Detailed explanation can be found in [this answer](http://stackoverflow.com/a/21122817/1903116) – thefourtheye May 06 '15 at 07:15
  • I didn't notice at first, but it says `python3` in the first line with the environment. – TigerhawkT3 May 06 '15 at 07:17
  • If the OP is using Python 3, is this really a duplicate? – TigerhawkT3 May 06 '15 at 07:22
  • seems so, changed `input` to `raw_input` and it worked. (see my solution in the question) – globus243 May 06 '15 at 07:23
  • @globus243 then i should tell you - you python3 is a fake! :D how do you run the script: like ./script_file.py or python script_file.py ? – Reishin May 06 '15 at 07:25
  • @Reishin care to elaborate? always keen to learn! – globus243 May 06 '15 at 07:26
  • @globus243 sorry, what? Your code sample use hash-bang with python3 binary to execute, but you able to fix the issue using solution for python2. It's make question unclear – Reishin May 06 '15 at 07:27
  • oh, didn't see the second part of your answer. this code will run inside Yowsup ( https://github.com/tgalal/yowsup ) which is a Python CommandLine WhatsApp Client, but I'm testing it like `python3 ./script.py` – globus243 May 06 '15 at 07:30

1 Answers1

0

It sounds like you're using Python 2 and therefore need to use raw_input() instead of input() (no need to cast to str()).

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97