简体   繁体   English

python 中的错误:未定义名称(if 语句中的变量)

[英]error in python: name not defined (variable in if statement)

May I know why there is an error that 'the name 'output' is not defined'?我可以知道为什么会出现“未定义名称“输出”的错误吗? Thank you谢谢

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

If converter is not 'l' or 'k' , then no output =... is never executed.如果converter不是'l''k' ,则不会执行任何output =...

You can precede the conditionals by您可以在条件句之前通过

output = <some default value>

or raise an exception if no condition was met.如果不满足任何条件,则引发异常。

What would happen if the value of converter is not 'l' neither 'k' ?如果converter的值既不是'l'也不是'k'会发生什么? The code inside your conditionals would never get executed and hence output would never be assigned.条件中的代码永远不会被执行,因此永远不会分配output

You should declare output before your conditionals to have a default value at-least in case none of your conditions are satisfied like this:你应该在你的条件之前声明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)}')

When the converter is neither l nor k then both conditions are false and hence output is never created that's why you are getting this error.converter既不是l也不是k时,两个条件都是错误的,因此output永远不会创建,这就是您收到此错误的原因。 To resolve this issue you have to create a variable named output before the conditional statements( if and elif )要解决此问题,您必须在条件语句( ifelif )之前创建一个名为 output 的变量

output = ""
# rest of your code here

I had to tweak the output a bit to make it work:我不得不稍微调整 output 以使其工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM