如何从用户的选择中调用子例程



我的需求

编写一个程序,根据用户的选择绘制五种形状之一:直线(l(、正方形(s(、矩形(r(、三角形(t(或菱形(d(。如果用户输入了有效的选择,程序将提示用户输入形状的大小。

问题

我已经为每个形状编写了子例程,但我很难弄清楚如何使用用户选择的字母来实现子例程。我假设我使用if/else语句,但不确定如何将这些语句与字符串一起使用。这是我迄今为止的代码:

#   Subroutines
def drawLine(length):
length = int(input("Enter size of line: "))
print("*" * (length))
def drawSquare(size):
size = int(input("Enter size of side of square: "))
for i in range(size):
print('*' * size)
def drawRectangle(across_size, down_size):
across_size = int(input("Enter the across side of rectangle: "))
down_size = int(input("Enter the down side of rectangle: "))
for i in range(down_size):
for j in range(across_size):
print('*' if i in [0, down_size-1] or j in [0, across_size-1] else " ", end='')
print()
def drawTriangle(size):
size = int(input("Enter size of triangle: "))
x = 1
while (x <= size):
print("*" * x)
x = x + 1
def drawDiamond(size):
size = int(input("Enter size of diamond: "))
for i in range(n-1):
print((n-i) * ' ' + (2*i+1) * '*')
for i in range(n-1, -1, -1):
print((n-i) * ' ' + (2*i+1) * '*')
# main program
shape = input ("Enter type of shape (l,s,r,t,d): ")
list = ['l', 's', 'r', 't', 'd']
if shape not in list:
print("Entered incorrect type of shape", shape)

我已经用字母创建了一个列表,但无法继续我的代码,所以如果有人选择"l",它会调用子程序drawLine等。

其余部分遵循相同的逻辑。您还需要从用户那里获得一个整数以传递到函数中,因为您正在为函数提供输入。

size = int(input("Please enter a number for the size: "))
if shape == 'l':
drawLine(size)
else if shape == 's':
drawSquare(size)
else if ...:
.
.
else:
print("Entered incorrect type of shape")

顺便说一句,函数定义的工作方式如下:

def drawLine(length):
length = int(input("Enter size of line: "))
print("*" * (length))

就是说,您正在定义一个名为drawLine的函数,该函数接受一个称为length的参数。当您调用此函数(即drawLine(5)(时,您的函数将使用length = 5执行。然后,当您在函数体中使用变量length时,它将等于您调用函数时使用的任何值,因为它是参数,所以您不需要在每个函数中要求用户输入。或者,你可以在函数中获取长度,但不应该用任何输入参数定义函数,比如:

# this definition takes 0 arguments(inputs) and gets length inside
def drawLine(): 
length = int(input("Enter size of line: "))
print("*" * (length))
# this definition expects drawLine to be called with a value, and you can get the length from the user elsewhere
def drawLine(length):
print("*" * (length))

当使用第二个定义调用时,它将执行函数的主体,如下所示(以drawLine(10)为例(:

print("*" * (10))

最新更新