def getInt():
while True:
width = int(input("Enter width (1 - 60):"))
if width > 1 and width < 60:
break
else:
print("Please enter a valid input")
while True:
height = int(input("Enter width (1 - 20):"))
if height > 1 and height < 20:
break
else:
print("Please enter a valid input")
return width, height
def calcPerimeter(width, height):
perimeter = (2 * (width + height))
return perimeter
def calcArea(width, height):
area = width * height
return area
def main():
print('Results: {}'.format(getInt()))
print('The perimeter is {}' .format(calcPerimeter(width, height)))
print('The area is {}' .format(calcArea(width, height)))
main()
当我跑步时,它说:
追踪(最近一次呼叫最后一次):
main()
打印(&#39;周长为{}&#39; .format(calcPerimeter(width,height)))
NameError:name&#39; width&#39;未定义
答案 0 :(得分:2)
也许您可以尝试将main()更改为此
def main():
width, height = getInt()
print('Results: {}, {}'.format(width, height))
print('The perimeter is {}' .format(calcPerimeter(width, height)))
print('The area is {}' .format(calcArea(width, height)))
在传入另一个函数
之前,需要将getInt()返回给特定变量其他方法是在getInt()函数中调用calculatePerimeter和calculateArea,这里是示例
def getInt():
while True:
width = int(input("Enter width (1 - 60):"))
if width > 1 and width < 60:
break
else:
print("Please enter a valid input")
while True:
height = int(input("Enter width (1 - 20):"))
if height > 1 and height < 20:
break
else:
print("Please enter a valid input")
return calcPerimeter(width, height), calcArea(width, height)
def calcPerimeter(width, height):
perimeter = (2 * (width + height))
return perimeter
def calcArea(width, height):
area = width * height
return area
def main():
perimeter, area = getInt()
print('Perimeter is {}, area is {}'.format(perimeter, area))
main()
答案 1 :(得分:0)
一种方法是使用全局关键字。另一种方法是从函数返回所需的变量并将它们保存在全局范围内。
答案 2 :(得分:0)
您应该阅读这篇文章并一般性地研究变量范围的规则。作为程序员,这是必不可少的知识。
答案 3 :(得分:0)
请参阅此(链接)[http://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html],了解为何将main
功能更改为Po的答案可以使代码正常运行。
函数calcPerimeter
和calcArea
中定义的变量对于main
函数不可见/可访问,因为它们位于不同的范围内。
答案 4 :(得分:0)
#I think i have resolved your problem.In your case it was returning list/tuple .you have to convert it into simple variable
def getInt():
while True:
width = int(input("Enter width (1 - 60):"))
if width > 1 and width < 60:
break
else:
print("Please enter a valid input")
while True:
height = int(input("Enter height (1 - 20):"))
if height > 1 and height < 20:
break
else:
print("Please enter a valid input")
return width,height
def calcPerimeter(width, height):
hw=width+height
perimeter = 2*hw
return perimeter
def main():
width,height= getInt()
p=calcPerimeter(width, height)
print('The perimeter is %s'%p)
a=calcArea(width, height)
print('The area is %s'%a)
main()