用于打印值的脚本

时间:2013-12-15 20:27:54

标签: python python-2.7 dictionary

我正在尝试创建一个脚本,该脚本将获取用户输入和打印值,具体而言,将函数作为raw_input,并在输入时在字典中打印该键。我试图让它在某些方面发挥作用,但我似乎无法把它搞定。最近几天我在论坛上问了几个问题,并且重申我现在已经在蟒蛇年里待了4天。有人可以给我一个指针吗?

#dictionary of categories and their items
functions = {
'Absolute Value':{
'abs': 'syntax: abs(number), use:The abs function is used to determine the absolute  value 
}
'Round':{
'ro':'syntax: round(number), use: The round function is used to round a number down.'
}

#ask user for input as to which function they want
fnct=raw_input('Choose a function: abs, ro:')

#if a user chooses a function, map it to this key
if fnct=='abs':key='abs'
if fnct=='ro' :key='ro'

#if a user chooses a function, use the mapped key to print the key value
if fnct=='abs':print 'abs'
if fnct=='ro':print 'ro'

提前致谢

1 个答案:

答案 0 :(得分:0)

更新了您的代码,这应该完全符合您的要求(假设您要根据用户输入打印字典元素的内容):

functions = {
    "abs":"syntax: abs(number), use:The abs function is used to determine the absolute value",
    "ro":"syntax: round(number), use: The round function is used to round a number down"
}

fnct = None

while fnct not in functions:
    fnct = raw_input("Choose a function: abs, ro :")

print(functions[fnct])

因此第一行定义functions字典,fnct = None定义该变量,因此我们不会在while循环的第一次迭代中遇到错误(因为input isn “还没调用”,循环检查输入的值是否实际存在于字典中(并且如果不存在则循环询问另一个值,以便在尝试显示时不会遇到KeyError字典中不存在的东西),最后它显示与fnct值对应的内容。