pythonnameerror

I defined a <variable> in an if-else, but why is there an error "the name <variable> is not defined"?


Why is there an error

the name 'output' is not defined?

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

Solution

  • If converter is not 'l' or 'k', then no output = ... is never executed.

    You can precede the conditionals by

    output = <some default value>

    or raise an exception if no condition was met.