Mariıos
Mariıos

Reputation: 283

How to turn a string of letters into integer?

Specifically, I'm taking a word that a user inputs, which is equivalent to a number (that the user wouldn'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 it..

Upvotes: 3

Views: 165

Answers (6)

omri_saadon
omri_saadon

Reputation: 10621

I would use a dictionary here

First, initialize your dictionary with the relevant values.

Second, ask for the user input.

Last, get the value from the map with the 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 at the comment you can use the get function so that you can get a default value 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.

Upvotes: 6

Tbaki
Tbaki

Reputation: 1003

use eval

print (10 + eval(animal))

In your case this would probably be a problem, but when creating more complexe it may present some security issue. Refer to : Is using eval in Python a bad practice?

Althought in some case if may be convenient to generate code, as pointed out in the comment, use with caution.

EDIT : You can use a safer version which will only evaluated litteral expression :

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

Upvotes: -4

Vanojx1
Vanojx1

Reputation: 5574

Be sure to handle every 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())

Upvotes: 2

owns
owns

Reputation: 325

A dictionary is the best idea, has other's have posted. Just don't forget 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

Upvotes: 1

Sagar
Sagar

Reputation: 1155

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

Upvotes: 1

Kewl
Kewl

Reputation: 3417

You can use dictionaries to do this:

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

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

print 10 + d[animal]

Upvotes: 0

Related Questions