如何解决如何使用python向用户询问Main Function上的函数输入?
我需要在使用主函数时询问用户输入高度和宽度以查找周长和面积,我收到一个简单的错误,即 (Area= (Width * Height) NameError: name 'Width' is not defined)但我已经尝试了我所知道的一切来修复它
print("Find the Area and Perimeter of a retangle.")
def main():
Width = input("Enter the Width:")
Height = input("Enter the Height:")
Area()
Perimeter()
def Area():
Area= (Width * Height)
print("The area is",Area)
def Perimeter():
Perimeter = (Width * 2 + Height * 2)
main()
解决方法
重写代码:
print("Find the Area and Perimeter of a retangle.")
def main():
Width = input("Enter the Width:")
Height = input("Enter the Height:")
Area(Width,Height)
Perimeter(Width,Height)
def Area(Width,Height):
Area= (Width * Height)
print("The area is",Area)
def Perimeter(Width,Height):
Perimeter = (Width * 2 + Height * 2)
main()
,
正如其他答案已经指出的那样,函数 test_react
和 Area
不知道 Perimeter
内部发生了什么。这是了解课程的绝佳机会。我会将其重组为一个类,如下所示:
main
,
您的函数应尽可能接受参数并返回值。
def main():
print("Find the Area and Perimeter of a retangle.")
width = input("Enter the Width:")
height = input("Enter the Height:")
print("The area is",area(width,height))
print("The perimeter is",perimeter(width,height))
def area(w,h):
return w * h
def perimeter(w,h):
return w*2 + h*2
main()
area
和 perimeter
不应该负责执行任何输出:它们将必要的输入作为参数并返回值。
您的 main
函数负责所有 I/O:它提示用户输入宽度和高度,并使用 area
和 perimeter
获取要输出的值。
如果您想进一步分解 main
的作用,您可以定义额外的输入和输出例程:
def get_input():
width = input("Enter the width: ")
height = input("Enter the height: ")
return width,height
def give_output(a,p):
print("The area is",a)
print("The perimeter is",p)
def main():
width,height = get_input()
give_output(area(width,height),height))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。