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

eMR*_*MRe 3 python user-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
Run Code Online (Sandbox Code Playgroud)

Rik*_*ggi 6

让我用另一个问题回答你的问题:
是否真的有必要混合字母和数字?
他们不能只是串?

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

  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
Run Code Online (Sandbox Code Playgroud)

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!'
Run Code Online (Sandbox Code Playgroud)

第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'
Run Code Online (Sandbox Code Playgroud)

现在让我们把它们放在一起:

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
Run Code Online (Sandbox Code Playgroud)

你的转换的关键在于options现在不再list只是一个dict,所以如果你只是迭代它就像if choice in options你的迭代在键上:['1', '2', 'D', 'X'],但如果你这样做,options['X']你得到退出函数(不是那么好!).

现在让我们再次改进,因为保持主菜单消息和options字典不太好,一年后我可能忘记改变其中一种,我不会得到我想要的东西而且我很懒,我不会想要做两次相同的事情,等等......
那么为什么不把options字典传递给所有工作display_manu,让display_menu使用doc-strings __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
Run Code Online (Sandbox Code Playgroud)

我们需要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()
Run Code Online (Sandbox Code Playgroud)

请注意,你必须设计你的行动,使他们都有相同的签名(他们应该是这样的,无论如何,他们都是行动!).您可能希望将callables用作操作:已__call__实现的类的实例.创建一个基Action类并从中继承将是完美的.