Reputation: 69
I am learning to code in Python. I am creating a program that will perform unit conversions, however I have been stuck on this error for a good while:
NameError: name 'ini' is not defined
Here is the code:
a = ("Distance")
b = ("Time")
c = ("Volume")
d = ("Temp")
e = ("Weight")
def conversion_type(first):
if first == ("Distance"):
ini = input("How great a distance am I converting?\n")
elif first == ("Time"):
ini = input("How much time am I converting?\n")
elif first == ("Volume"):
ini = input("How great a volume am I converting?\n")
elif first == ("Temp"):
ini = input("How many degrees am I converting?\n")
elif first == ("Weight"):
ini = input("How much weight am I converting?\n")
else:
print("That not was an afformentioned dimension you dolt.")
def variable_type_converter(ini):
ini = float(ini)
print ("\n Welcome to the Convert-O-Matic\n==============================\n")
print ("I support the following dimensions:\n")
print ("%s, %s, %s, %s, and %s," % (a,b,c,d,e))
first = input("What kind of conversion would you like to do?\n")
conversion_type(first)
variable_type_converter(ini)
print("==========================================")
Upvotes: 0
Views: 64
Reputation: 56588
ini
is not declared in the global scope, only inside of functions (it is used in conversion_type()
and therefore implicitly declared there, and it is an argument to variable_type_converter()
). But since it was not declared in the global scope, it does not exist there. If you want to set the value of ini
in conversion_type()
and have the value be usable elsewhere, declare a value for ini
somewhere before you call conversion_type()
.
This answer has a good summary of Python's scoping rules.
Update: As MadWombat points out in comments, your variable_type_converter()
function doesn't do anything. It takes one argument, called ini
, it casts it as float and reassigns back to ini
, but then it doesn't return a value. So when the variable_type_converter()
function exits, the value is discarded and and the float cast is never used.
Upvotes: 2
Reputation: 15288
When defining your variables you should use a = "Distance"
. You should also check the conversion type using first == "Distance"
ini
is not defined, is occurring because the function conversion_type(first)
is returning a value that is not stored. Try:
# get conversion type
conversion_type_chosen = conversion_type(first)
# calculate value
converted_value = variable_type_convertor(conversion_type_chosen)
# print result
print "result: {}".format(converted_value)
Upvotes: 1