【发布时间】:2020-04-08 15:05:58
【问题描述】:
我正在尝试编写一个简单的函数,当给定字典名称和键的参数时,它将返回正确的值。它基本上只是用作在正确尺寸的电缆上安装正确尺寸的密封套和正确数量的芯数的快速参考。
这就是我所拥有的:
cable120 = { 2 : '40mm', 3 : '40mm', 4 : '50mm' }
cable150 = { 2 : '40mm', 3 : '50s', 4 : '50mm' }
cable185 = { 2 : '50s', 3 : '50mm', 4 : '63s' }
cable240 = { 2 : '50mm', 3 : '63s', 4 : '63mm' }
def glandsize(csa,cores):
try :
print(csa[cores])
except :
print('Command not recognised. Please try Again.')
print (' Use As Follows glandsize(cable??, cores)\n For Example If Cable Is 16mm 3 core,\n glandsize(cable16,3')
#glandsize(cable185,2)
现在我将此文件保存为 GlandSize.py 并将其放在路径环境中,以便我可以从 Shell 导入它以使用它。
当我尝试在 shell 中使用它时会发生以下情况:
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import GlandSize
>>> GlandSize.glandsize(cable185, 3)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
GlandSize.glandsize(cable185, 3)
NameError: name 'cable185' is not defined
>>>
我不明白为什么?我知道如果我在导入 GlandSize.py 时调用了 GlandSize(cable185,2) 函数,它会输出正确的结果。
为什么我不能从 shell 访问模块中正确的字典?
我知道这可能是一个非常基本的错误,但我似乎无法理解它。任何帮助将不胜感激。
【问题讨论】:
标签: python function dictionary