3

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..

martineau
  • 119,623
  • 25
  • 170
  • 301
Mariıos
  • 273
  • 2
  • 5

6 Answers6

6

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.
omri_saadon
  • 10,193
  • 7
  • 33
  • 58
  • 2
    how do you type that fast... I would use the more flexible: `animals_map.get(animal, 0)` – Ma0 Jun 07 '17 at 15:26
  • @Ev.Kounis If you're a programmer, learn to type: [gtypist](https://www.gnu.org/software/gtypist/index.html) – Peter Wood Jun 07 '17 at 15:27
  • @Ev.Kounis , I agree with the get function, I've edited the answer with that. Thank you ! – omri_saadon Jun 07 '17 at 15:38
  • @omri_saadon you could also use [`defaultdict(int)`](https://docs.python.org/2/library/collections.html#collections.defaultdict) – Peter Wood Jun 07 '17 at 15:39
2

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())
Vanojx1
  • 5,574
  • 2
  • 23
  • 37
  • instead of `pass` you could have something more useful, like the available options for example and the whole thing inside a `while True` that `break`s when the `try` is successful with an `else` maybe.. [See this](https://repl.it/Iai1/0) – Ma0 Jun 07 '17 at 15:36
  • The user experience can be enanched for sure. – Vanojx1 Jun 07 '17 at 15:42
1
animal = raw_input(>)
animal_dict = {'dog': 30, 'cat': 10, 'frog': 5}
number = animal_dict.get(animal, 0):
print 10+number
Sagar
  • 1,115
  • 2
  • 11
  • 23
1

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

owns
  • 305
  • 2
  • 7
0

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]
Kewl
  • 3,327
  • 5
  • 26
  • 45
-4

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)))
Tbaki
  • 1,013
  • 7
  • 12
  • 1
    Very bad idea to `eval` a string input by the user. That basically allows the user to execute arbitrary code. – khelwood Jun 07 '17 at 15:29
  • This solution work for the assignment, even if it is not best practice, so why the downvote ? – Tbaki Jun 07 '17 at 15:30
  • 1
    Because it is bad advice. – khelwood Jun 07 '17 at 15:31
  • It's not an advice, but a solution, even if i get your point, i don't think the answer it wrong. – Tbaki Jun 07 '17 at 15:32
  • Should add a comment about the dangers. not the best, but still a solution. – owns Jun 07 '17 at 15:38
  • Point taken, i think it's good to know that eval exist, and what it can do, and looking at his application, i didn't think that would have been an issue, although i agree a warning may be helpful. – Tbaki Jun 07 '17 at 15:46
  • If you are suggesting `eval` to a problem that has (multiple!) safe solutions, you're doing a disservice to the asker and any future visitors too. Whatever excuses you might think you have about "knowing about it is helpful" for the asker: these are wrong, and despite well-meaning you are wrong. – Andras Deak -- Слава Україні Jun 22 '17 at 14:19
  • @AndrasDeak sure, will use ast.literal_eval() next time – Tbaki Jun 22 '17 at 14:20
  • 1. you can always [edit] your answer, nothing is set in stone on SO and especially wrong/harmful answers are encouraged not to be left lying around; 2. I think `literal_eval` will only evaluate literals, so it won't work now. That's the exact reason why this application of `eval` is so dangerous: if the teacher types `rm -f /` as input (well, or the proper version preferably with sudo), all hell breaks loose. It's just _not safe and not helpful_. Anyway, I just saw your request for explanations for downvotes, and thought I'd share my own. Good luck. – Andras Deak -- Слава Україні Jun 22 '17 at 14:23
  • 1
    @AndrasDeak, sure thanks, didn't know about the rm -f thing, just learnt about the literal equivalent which is safer on another post. – Tbaki Jun 22 '17 at 14:27
  • Actually, now I realize that I exaggerated, there would probably have to be an `import subprocess; subprocess.call` involved in the input;) But my point (which is the point of everyone who rejects showing eval to newbies when there are safe alternatives) stands:) Thanks for understanding. – Andras Deak -- Слава Україні Jun 22 '17 at 14:29
  • 1
    @AndrasDeak Thanks for taking the time to make people improve. :D – Tbaki Jun 22 '17 at 14:31