How do I convert a string of letters to an integer?

Specifically, I take a word that the user enters, which is equivalent to a number (which the user didn't know).

my code:

animal = raw_input( > )  #and a user inputs cat
dog = 30 
cat = 10
frog = 5
print 10 + int(animal) #with the hope that will output 20

      

Not sure how to do this.

+3


source to share


6 answers


I would use a dictionary here

First, initialize the dictionary with the appropriate values.

Second, ask to enter user data.

Finally, get the value from the map using user input as the key.



animals_map = {"dog" : 30, "cat" : 10, "frog" : 5}

animal = raw_input('>') #and a user inputs cat
animal_number = animals_map[animal]

print 10 + int(animal_number) #with the hope that will output 20

      

EDIT:

As Ev. Kounis mentioned in a comment that you can use the get function so that you can get the default when the user input is not in the dictionary.

animals_map.get(animal, 0) # default for zero whether the user input is not a key at the dictionary.

      

+6


source


Make sure to process each input value:



types = {'dog': 30, 'cat': 10, 'frog': 5}

def getInput():
  try:
    return 10 + types[raw_input("Give me an animal: ")]
  except:
    print("BAD! Available animals are: {}".format(", ".join(types.keys())))
    return getInput()

print(getInput())

      

+2


source


animal = raw_input(>)
animal_dict = {'dog': 30, 'cat': 10, 'frog': 5}
number = animal_dict.get(animal, 0):
print 10+number

      

+1


source


Dictionary is the best idea, others have published. Just remember to handle bad input

animals = dict(dog=30,cat=10,frog=5)
animal = raw_input(">") # and a user inputs cat
if animal in animals:
    print "animal %s id: %d" % (animal,animals[animal])
else:
    print "animal '%s' not found" % (animal,)

      

https://docs.python.org/2/tutorial/datastructures.html#dictionaries

+1


source


You can use dictionaries for this:

animal = raw_input( > ) #and a user inputs cat

d = {'dog' : 30, 'cat' : 10, 'frog' : 5}

print 10 + d[animal]

      

0


source


use eval

print (10 + eval(animal))

      

In your case, this will probably be a problem, but there may be a security issue when asking more complex questions. Refer to: Is eval in Python a bad practice?

Although in some cases, if it might be convenient to generate code as pointed out in the comment, use with caution.

EDIT: you can use a safer version that will evaluate the litteral :

import ast
print ( 10 + int(ast.literal_eval(  animal)))

      

-4


source







All Articles