How do I convert a string of letters to an integer?
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.
source to share
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
source to share
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)))
source to share