我不知道为什么会出现这个错误:
代码如下`"""形状程序,约旦汉普森"""
def main():
"""main boss function"""
shape = ""
while shape != "q":
shape = ""
shape = input("Enter shape to draw (q to quit): ").lower()
if shape == "q":
print("Goodbye")
elif get_valid_shape(shape):
call_shape(shape)
else:
print("Unknown shape. Please try again")
def call_shape(shape):
"""CALLS THE shape"""
if shape == "rectangle":
height = int(input("Enter height: "))
while get_valid_size_rectangle_height(height):
height = int(input("Enter height: "))
width = int(input("Enter width: "))
while get_valid_size_rectangle_width(width):
width = int(input("Enter width: "))
print_rectangle(height, width)
else:
size = int(input("Enter size: "))
while get_valid_size(size):
size = int(input("Enter size: "))
if shape == "square":
return print_square(size)
elif shape == "triangle":
return print_triangle(size)
def get_valid_size_rectangle_width(height):
"""checks to see if the rectangle size is valid"""
if height < 1:
print("Value must be at least 1")
return True
else:
return False
def get_valid_size_rectangle_height(width):
"""checks to see if the rectangle size is valid"""
if width < 1:
print("Value must be at least 1")
return True
else:
return False
def get_valid_size(size):
"""checks to see if the size is valid"""
if shape == "triangle" or "square" and size <= 0:
print("Value must be at least 1")
return True
else:
return False
def get_valid_shape(shape):
"""gets a valid shape"""
shape_1 = shape
shapes = ["square", "triangle", "q", "rectangle"]
if shape_1 not in shapes:
return False
else:
return True
def print_square(size):
"""prints a square from the input"""
for _ in range(0, size):
print(size * "*")
def print_triangle(size):
"""prints a triangle in *'s"""
for _ in range(1, size +1):
print((size -(size -_)) * "*")
def print_rectangle(height, width):
"""prints a rectangle using height and width"""
rec = (width * "*" for a in range(height))
print('\n'.join(rec))
main()
错误消息是
追踪(最近一次通话): 文件&#34; C:\ Program Files(x86)\ Wing IDE 101 5.1 \ src \ debug \ tserver_sandbox.py&#34;,109行in 文件&#34; C:\ Program Files(x86)\ Wing IDE 101 5.1 \ src \ debug \ tserver_sandbox.py&#34;,第19行,主要 文件&#34; C:\ Program Files(x86)\ Wing IDE 101 5.1 \ src \ debug \ tserver_sandbox.py&#34;,第44行,在call_shape中 builtins.UnboundLocalError:局部变量&#39; size&#39;在分配前引用
答案 0 :(得分:1)
在这里查看简化代码:
if shape == "rectangle":
# size not declared here...
else:
size = int(input("Enter size: "))
while get_valid_size(size):
如果shape
确实是"rectangle"
,则未声明size
,并且您无法在while
循环中使用它。解决此问题的一种方法是使用无效值预先声明它:
size = -1
if shape == "rectangle":
# size not declared here...
else:
size = int(input("Enter size: "))
while get_valid_size(size):
答案 1 :(得分:0)
这似乎是缩进错误。从while get_valid_size(size):
到该函数末尾的所有内容都应该向右移动一个缩进,以便它包含在else
块中。