0

Folks I'm a newbie to python and I can't figure this out. I have a string that I want to equate to a number but I am at a loss. Here is code that I have so far but its not working. If there is an answer to my question please point me there.

Function takes an argument name and it should produce the corresponding number

    def name_to_number(name):
    name1 = "rock"
    name2 = "paper"
    name3 = "scissors"
    name4 = "lizard"
    name5 = "spock"

    name_rock = int(0, name1)
    name_paper = int(1, name2)
    name_scissors = int(2, name3)
    name_lizard = int(3, name4)
    name_spock = int(4, name5)

    if (name1 == "rock"):
        print name_rock
    elif (name2 == "paper"):
        print name_paper
    elif (name3 == "scissors"):
        print name_scissors
    elif (name4 == "lizard"):
          print name_lizard
    elif (name5 == "spock"):
        print name_spock
    else :
        print "None of the numbers match"

    return name

test = name_to_number("paper")

print test
Alpha Sanneh
  • 1
  • 1
  • 2
  • 4
    `name1`, `name2` is a really common anti-pattern. Use a data structure (`list`, `dict`, etc...) instead. This kind of problem becomes trivial too. – Gareth Latty Apr 27 '13 at 02:44
  • Maybe you need enums: http://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python?rq=1 – Nipun Batra Apr 27 '13 at 02:44

1 Answers1

4

Your real question is "How to map strings to numbers in Python" (or vice-versa). As the current title may be misleading, lets first address it for folks coming over "how to compare strings and numbers": unlike popular script languages Python will not make automatic type castings. For example, in Javascript you can do this:

>>> 5 == '5'
true

But in Python it is False:

>>> 5 == '5'
False

You must cast both values to the same type (for example string or int) explicitly if you expect them to be of different types:

>>> str(5) == str('5')
True

Now lets get back to your real question. As @GarethLatty commented:

name1, name2 is a really common anti-pattern. Use a data structure (list, dict, etc...) instead. This kind of problem becomes trivial too.

Two of the basic container data types in Python are the list and the dict.

Using a list:

>>> name_list = ['rock', 'paper', 'scissors', 'lizard', 'spock']
>>> name_list.index('spock')
4

List indexes are zero-based:

>>> name_list[0]
'rock'

Using a dict you can associate arbitrary numbers to strings:

>>> name_dict = {'rock': 1, 'paper': 2, 'scissors': 3, 'lizard': 4, 'spock': 5}
>>> name_dict['spock']
5

If the value is not present in the list, the index method will raise a ValueError exception. In Python it is common to surround this kind of expression with a try block (like commented by icktoofay):

>>> name = 'kirk'
>>> try:
...     name_list.index(name)
... except ValueError:
...     print('{} is not a valid name.'.format(name)) 
... 
kirk is not a valid name.

This programming style is very popular. Using a dict, the exception you have to watch for is KeyError:

>>> name_dict['kirk']
Traceback (most recent call last):
    File "<interactive input>", line 1, in <module>
KeyError: 'kirk'

If you are starting with Python, the REPL (read-eval-print loop, the Python prompt) is your best friend. Just explore anything using the help and dir built-in functions:

>>> dir(name_dict)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__',
 '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
 '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__',
 '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
 '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__',
 '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key',
 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop',
 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys',
 'viewvalues']
>>> help(name_dict.keys)
Help on built-in function keys:

keys(...)
    D.keys() -> list of D's keys

>>>
Paulo Scardine
  • 73,447
  • 11
  • 124
  • 153
  • For example, `name_to_number = lambda name: name_dict.get(name, -1)`, where if the name is not in name_dict it will return -1. But really, explore your options using the REPL and update your question with the results before asking again. This site is called stackoverflow, not domyhomeworkforme. – Paulo Scardine Apr 27 '13 at 03:17