为初学者添加if / else语句以形成算法

时间:2013-11-08 02:23:06

标签: python if-statement shapes

我正在尝试将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'

1 个答案:

答案 0 :(得分:1)

print('Please specify a shape to draw. Type S for square')
shape = raw_input('Please specify a shape to draw:')
size = input('Please enter a size:')
chr = raw_input('Please enter a drawing character:')
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"
print''