我编写了一个python代码,使用颜色代码查找阻力
# resistance of the resistor with
# the given color codes
# Function to find the resistance
# using color codes
def findResistance(a, b, c, d):
# Hash-map to store the values
# of the color-digits
color_digit = {'black': '0',
'brown': '1',
'red': '2',
'orange': '3',
'yellow': '4',
'green' : '5',
'blue' : '6',
'violet' : '7',
'grey' : '8',
'white': '9'}
multiplier = {'black': '1',
'brown': '10',
'red': '100',
'orange': '1k',
'yellow': '10k',
'green' : '100k',
'blue' : '1M',
'violet' : '10M',
'grey' : '100M',
'white': '1G'}
tolerance = {'brown': '+/- 1 %',
'red' : '+/- 2 %',
'green': "+/- 0.5 %",
'blue': '+/- 0.25 %',
'violet' : '+/- 0.1 %',
'gold': '+/- 5 %',
'silver' : '+/- 10 %',
'none': '+/-20 %'}
xx = color_digit.get(a)
yy = color_digit.get(b)
zz = multiplier.get(c)
aa = tolerance.get(d)
print("Resistance = "+xx + yy+
" x "+zz+" ohms "+aa)
# Driver Code
if __name__ == "__main__":
a = input("enter 1st color: ")
b = input("enter 2nd color: ")
c = input("enter 3rd color: ")
d = input("enter 4th color: ")
# Function Call
findResistance(a, b, c, d)
但当我运行它时,它会给我以下错误
Traceback (most recent call last):
File "1.py", line 59, in <module>
findResistance(a, b, c, d)
File "1.py", line 45, in findResistance
print("Resistance = "+xx + yy+
TypeError: can only concatenate str (not "NoneType") to str
我的代码有问题吗
您不希望使用
get
,因为如果在字典中找不到键,这将使用默认值(在本例中为None
)。但是在这里的用例中,键必须存在,例如pink
不能给出有效的输出。一种选择是在findResistance
函数中进行普通的字典查找,即因此,如果给出了无效的输入,那么将引发
KeyError
。然后,您可以在调用者中对此进行测试(异常的字符串表示形式将是尝试的键):或者,如果您希望您的函数在这种情况下引发某种不同类型的异常(例如
ValueError
或某种自定义异常),您可以在函数本身中执行try
块,例如:但是允许
get
提供默认的None
,然后在代码的后面得到一个模糊的TypeError
是没有用的行为我修改了关于颜色的电阻计算方法,因为我们需要将颜色系数乘以
k
值。修改后的代码如下所示:相关问题 更多 >
编程相关推荐