具体而言,我正在处理用户输入的一个单词,该单词相当于一个数字(用户不知道该数字)。
我的代码:
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
不确定如何做..
具体而言,我正在处理用户输入的一个单词,该单词相当于一个数字(用户不知道该数字)。
我的代码:
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
我会在这里使用一个字典
首先,用相关的值初始化你的字典。
其次,请求用户输入。
最后,通过用户输入作为键从映射中获取值。
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
编辑:
正如 Ev. Kounis 在评论中提到的,您可以使用 get 函数,以便在用户输入不在字典中时获取默认值。animals_map.get(animal, 0) # default for zero whether the user input is not a key at the dictionary.
请务必处理每一个输入值:
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())
animal = raw_input(>)
animal_dict = {'dog': 30, 'cat': 10, 'frog': 5}
number = animal_dict.get(animal, 0):
print 10+number
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
animal = raw_input( > ) #and a user inputs cat
d = {'dog' : 30, 'cat' : 10, 'frog' : 5}
print 10 + d[animal]
使用eval
print (10 + eval(animal))
对于您的情况,这可能是一个问题,但在创建更复杂的内容时,它可能会出现一些安全问题。参见:在Python中使用eval是不好的实践吗?
虽然在某些情况下生成代码可能很方便,正如评论中所指出的那样,请谨慎使用。
编辑:您可以使用更安全的版本,它只会评估字面表达式:
import ast
print ( 10 + int(ast.literal_eval( animal)))
eval
来执行用户输入的字符串是非常糟糕的想法。这基本上允许用户执行任意代码。 - khelwood
animals_map.get(animal, 0)
。 - Ma0defaultdict(int)
。 - Peter Wood