我正在尝试将 if/else 语句添加到一组代码中,当用户使用输入字符串指定形状并且遇到困难时输出形状。如何在我的形状代码中添加一个简单的 If/else 语句,以便它只输出具有正确输入字符串的形状,并且当使用不正确的输入字符串时,它会输出一条错误消息,指出“形状未定义”。
我的形状代码之一是一个简单的平方算法:
def square(size, chr):
row = 1
while row <= size:
col = 1
while col <= size:
print chr,
col = col + 1
print ''
row = row + 1
print ''
更新代码:
print('Please specify a shape to draw. Type S for square, T for triangle, R for reverse triangle, D for diagonal, and A for angle')
shape = raw_input('Please specify a shape to draw:')
size = input('Please enter a size:')
chr = raw_input('Please enter a drawing character:')
print''
valid_shape_codes =('"S":square, "T":triangle, "R":reversetriangle, "D":diagonal, "A":angle')
if shape in valid_shape_codes:
valid_shape_codes[shape](size, chr)
else:
print 'Shape is not defined'