Reputation: 15
I've defined a function. I want that function to return a value. Then, later on in the script, I want to print that returned value inside of another defined function.
When I try to do this, I get the following error:
NameError: name 'variable_name' is not defined.
Here's the defined function:
def get_number_of_purchased_items():
item_quantity = input("Enter quantity purchased: ")
item_quantity = int(item_quantity)
return item_quantity
And here, later on in the script, is where I want to print "item_quantity":
def main():
print("Number of purchased items: ", item_quantity).
A little more information, in case it helps:
The above is one part of my overall script. I'm defining several functions -- to get input from the user on (a) the type of item they want to purchase, (b) the number of items they purchase, (c) the price per unit, and (d) the tax rate.
Then I've created three functions that take arguments, based on the returned values of the four above functions, to calculate (a) the subtotal, (b) the tax, and (c) the total cost.
Then I'm sticking all of these functions inside another function, main(), which, when printed, acts as a sales receipt -- see below. (I've included the "item_quantity" value I want returned, the one which results in a NameError.)
def main():
get_retail_item_description()
get_number_of_purchased_items()
get_price_per_unit()
get_tax_rate()
print("Sales receipt: ")
print("Number of purchased items: ", item_quantity)
print("Unit price: ", )
print("Tax Rate: ", )
print("Subtotal: ", )
print("Tax: ", )
print("Total: ", )
Thanks for your patience and support on this.
Upvotes: 0
Views: 166
Reputation: 2731
The problem is, you use return
, but do not declare a variable to hold it.
item_quantity
is a variable in the function, therefore main
do not know what it is. You have two ways:
item_quantity = get_number_of_purchased_items()
or:
print("Number of purchased items: ", get_number_of_purchased_items())
But #2 will be awkward, so I suggest to go with #1.
Upvotes: 1