如何从raw_input处理整数和字符串?


问题内容

仍在尝试了解python。它与php截然不同。

我将选择设置为整数,问题出在我的菜单上,我也需要使用字母。

如何将整数和字符串一起使用?
为什么不能将字符串设置为整数?

def main(): # Display the main menu
    while True:
        print
        print "  Draw a Shape"
        print "  ============"
        print
        print "  1 - Draw a triangle"
        print "  2 - Draw a square"
        print "  3 - Draw a rectangle"
        print "  4 - Draw a pentagon"
        print "  5 - Draw a hexagon"
        print "  6 - Draw an octagon"
        print "  7 - Draw a circle"
        print
        print "  D - Display what was drawn"
        print "  X - Exit"
        print

        choice = raw_input('  Enter your choice: ')

        if (choice == 'x') or (choice == 'X'):
            break

        elif (choice == 'd') or (choice == 'D'):
            log.show_log()

        try:
            choice = int(choice)
            if (1 <= choice <= 7):

                my_shape_num = h_m.how_many()
                if ( my_shape_num is None): 
                    continue

                # draw in the middle of screen if there is 1 shape to draw
                if (my_shape_num == 1):
                    d_s.start_point(0, 0)
                else:
                    d_s.start_point()
                #
                if choice == 1: 
                    d_s.draw_triangle(my_shape_num) 
                elif choice == 2: 
                    d_s.draw_square(my_shape_num) 
                elif choice == 3:             
                    d_s.draw_rectangle(my_shape_num) 
                elif choice == 4:             
                    d_s.draw_pentagon(my_shape_num) 
                elif choice == 5:             
                    d_s.draw_hexagon(my_shape_num) 
                elif choice == 6:             
                    d_s.draw_octagon(my_shape_num) 
                elif choice == 7: 
                    d_s.draw_circle(my_shape_num)

                d_s.t.end_fill() # shape fill color --draw_shape.py-- def start_point

            else:
                print
                print '  Number must be from 1 to 7!'
                print

        except ValueError:
            print
            print '  Try again'
            print

问题答案:

让我用另一个问题回答您的问题:
是否真的需要混合字母和数字?
难道他们不都是字符串吗?

好吧,让我们走很长一段路,看看程序在做什么:

  1. 显示主菜单
  2. 询问/接收用户输入
    • 如果有效:确定
    • 如果不是,请打印错误消息并重复
  3. 现在我们有一个有效的输入
    • 如果是字母:请执行特殊任务
    • 如果是数字:调用正确的绘图功能

要点1. 让我们为此做一个功能:

def display_menu():
    menu_text = """\
  Draw a Shape
  ============

  1 - Draw a triangle
  2 - Draw a square
  D - Display what was drawn
  X - Exit"""
    print menu_text

display_menu 非常简单,因此无需解释其作用,但是稍后我们将看到将这段代码放入单独的函数中的优势。

第2点。 这将通过循环完成:

options = ['1', '2', 'D', 'X']

while 1:
    choice = raw_input('  Enter your choice: ')
    if choice in options:
        break
    else:
        print 'Try Again!'

第3点。 好了,想一想也许特殊任务不是那么特殊,所以我们也将它们放入函数中:

def exit():
    """Exit"""  # this is a docstring we'll use it later
    return 0

def display_drawn():
    """Display what was drawn"""
    print 'display what was drawn'

def draw_triangle():
    """Draw a triangle"""
    print 'triangle'

def draw_square():
    """Draw a square"""
    print 'square'

现在,我们将它们放在一起:

def main():
    options = {'1': draw_triangle,
               '2': draw_square,
               'D': display_drawn,
               'X': exit}

    display_menu()
    while 1:
        choice = raw_input('  Enter your choice: ').upper()
        if choice in options:
            break
        else:
            print 'Try Again!'

    action = options[choice]   # here we get the right function
    action()     # here we call that function

切换键的关键在于options现在不再是lista dict,而是a ,因此,如果您像if choice in options迭代在
key :上那样简单地对其进行迭代['1', '2', 'D', 'X'],但是如果您这样做,options['X']则会得到exit函数(不是那么好!)。

现在,让我们再次进行改进,因为维护主菜单消息和options字典并不是太好,一年以后,我可能会忘记更改其中一个,而我将无法获得想要的东西,而且我很懒惰,但我没有想要做两次相同的事情,等等。。。
为什么不将options字典传递给display_manu,而是display_menu使用doc字符串__doc__生成菜单来完成所有工作:

def display_menu(opt):
    header = """\
  Draw a Shape
  ============

"""
    menu = '\n'.join('{} - {}'.format(k,func.__doc__) for k,func in opt.items())
    print header + menu

我们需要OrderedDict代替dictfor
options,因为OrderedDict顾名思义,请保持其项的顺序(请看官方文档)。因此,我们有:

def main():
    options = OrderedDict((('1', draw_triangle),
                           ('2', draw_square),
                           ('D', display_drawn),
                           ('X', exit)))

    display_menu(options)
    while 1:
        choice = raw_input('  Enter your choice: ').upper()
        if choice in options:
            break
        else:
            print 'Try Again!'

    action = options[choice]
    action()

请注意,您必须设计动作,使它们都具有相同的签名(无论如何,它们都应该是这样,它们都是动作!)。您可能希望将可调用对象用作操作:具有已__call__实现的类的实例。创建基Action类并从中继承将是完美的选择。