我在if-else中定义了<variable>,但是为什么会出现“名称<variable>未定义”错误?

问题描述 投票:0回答:5

为什么会出现错误

名称“输出”未定义?

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)}')
python nameerror
5个回答
3
投票

如果

converter
不是
'l'
'k'
,则永远不会执行
output = ...

您可以在条件语句之前添加

output = <some default value>

或者如果不满足条件则提出异常。


1
投票

如果

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)}')

1
投票

converter
既不是
l
也不是
k
时,这两个条件都是假的,因此永远不会创建
output
,这就是您收到此错误的原因。要解决此问题,您必须在条件语句之前创建一个名为输出的变量(
if
elif

output = ""
# rest of your code here

0
投票

我必须稍微调整输出才能使其工作:

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}')

0
投票
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)}')
© www.soinside.com 2019 - 2024. All rights reserved.