Reputation: 115
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)}')
Upvotes: 0
Views: 846
Reputation: 174
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)}')
Upvotes: 0
Reputation:
I had to tweak the output a bit to make it work:
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}')
Upvotes: 0
Reputation: 903
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. To resolve this issue you have to create a variable named output before the conditional statements(if
and elif
)
output = ""
# rest of your code here
Upvotes: 0
Reputation: 76396
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.
Upvotes: 2
Reputation: 8564
What would happen if the value of converter
is not 'l'
neither 'k'
? The code inside your conditionals would never get executed and hence output
would never be assigned.
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 = ""
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)}')
Upvotes: 1