I am trying to use this code, to calculate an area cost. I am using the functions option but it says that cost is not defined, I did define it.
def space():
""" This function will calculate the area of floor, that needs
flooring. """
# asking for variables
length =int(input('Please enter the length of the room in meters: '))
width =int(input('Please enter the width of the room in meters: '))
area=length*width
return area
def flooring():
"""This function will take the flooring chosen by the user and will
return the cost of the square meter."""
while True:
# asking for variables
opt=int(input('Please select type of flooring: '))
if (opt>=1 and opt<=5):
break
if (opt==1):
price=18.75
...
return price
def cost():
"""This will calculate the cost of the flooring, and other costs, and
will display them, aligned."""
print(price)
matCost=area*price
print("$",matCost)
###
### MAIN PROGRAM
###
while True:
...
space()
print()
print('Types of Flooring')
print()
print(' Cost per sq.m.')
print('1. Low Pile Carpet $18.75')
...
flooring()
print()
cost()
The error says but I thought I already defined it. With the if statement for the opt, I had thought that I already defined.
Traceback (most recent call last):
File"main.py", line 80 in <module>
cost()
File"main.py", line 52 in <module>
print(price)
NameError: name 'price' is not defined
CodePudding user response:
I think you just forgot to add price on the def cost():
def cost(price):
"""This will calculate the cost of the flooring, and other costs, and
will display them, aligned."""
print(price)
matCost=area*price
print("$",matCost)
price_result = flooring()
cost(price_result)
CodePudding user response:
Because the price variable is defined inside of a function, It is not global. Instead of attempting to call the price variable directly, you must call to the flooring method which returns said price variable.
def cost():
"""This will calculate the cost of the flooring, and other costs, and
will display them, aligned."""
price = flooring()
# The area variable is also not defined outside of the space method so it would be a good idea to add this as well.
area = space()
print(price)
matCost=area*price
print("$",matCost)
