为什么会出现错误
名称“输出”未定义?
weight = input('> ')
converter = input('lbs or kg: ').lower()
if converter == 'l':
output = weight * 2.205 + 'lbs'
elif converter == 'k':
output = weight / 2.205 + 'kg'
print(f'converted weight = {str(output)}')
如果
converter
不是 'l'
或 'k'
,则永远不会执行 output = ...
。
您可以在条件语句之前添加
output = <some default value>
或者如果不满足条件则提出异常。
如果
converter
的值既不是 'l'
也不是 'k'
会发生什么?条件语句中的代码永远不会被执行,因此 output
永远不会被分配。
您应该在条件之前声明
output
,至少有一个默认值,以防万一您的条件都不满足,如下所示:
output = ""
weight = input('> ')
converter = input('lbs or kg: ').lower()
if converter == 'l':
output = weight * 2.205 + 'lbs'
elif converter == 'k':
output = weight / 2.205 + 'kg'
print(f'converted weight = {str(output)}')
当
converter
既不是 l
也不是 k
时,这两个条件都是假的,因此永远不会创建 output
,这就是您收到此错误的原因。要解决此问题,您必须在条件语句之前创建一个名为输出的变量(if
和elif
)
output = ""
# rest of your code here
我必须稍微调整输出才能使其工作:
weight = input('> ')
converter = input('lbs or kg: ').lower()
if converter == 'l':
output = str(float(weight) * 2.205) + 'lbs'
elif converter == 'k':
output = str(float(weight) / 2.205) + 'kg'
else:
output = 'fail'
print(f'converted weight = {output}')
def main () :
weight = input('> ')
converter = input('lbs or kg: ').lower()
try :
weight = float(weight)
if converter[0] == 'l':
output = str(weight * 2.205) + 'lbs'
elif converter[0] == 'k':
output = str(weight / 2.205) + 'kg'
else:
output = "Invalid option"
except Exception as e:
output = "Invalid Weight"
print(f'converted weight = {str(output)}')