如何处理来自 raw_input 的整数和字符串? [英] How to handle both integer and string from raw_input?

查看:29
本文介绍了如何处理来自 raw_input 的整数和字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仍在尝试理解python.它与 php 非常不同.

Still trying to understand python. It is so different than php.

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

I set the choice to integer, the problem is on my menu I need to use letters as well.

如何同时使用整数和字符串?
为什么我不能设置为字符串而不是整数?

How can I use integer and string together?
Why can I not set to string than integer?

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

推荐答案

让我用另一个问题来回答你的问题:
字母和数字真的有必要混用吗?
它们不能都是字符串吗?

Let me answer your question with another question:
Is it really necessary to mix letters and numbers?
Can't they just be all strings?

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

Well, let's take the long way and see what the program is doing:

  1. 显示主菜单
  2. 询问/接收用户输入
    • 如果有效:ok
    • 如果不是:打印错误消息并重复
  • 如果是一封信:做一个特殊的任务
  • 如果是数字:调用正确的绘制函数

第 1 点.让我们为此创建一个函数:

Point 1. Let's make a function for this:

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 非常简单,因此无需解释它的作用,但稍后我们将看到将这段代码放入单独函数的好处.

display_menu is very simple so there's no need to explain what it does, but we'll see later the advantage of putting this code into a separate function.

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

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

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

第 3 点.好吧,仔细想想,也许特殊任务并没有那么特殊,所以让我们将它们也放入一个函数中:

Point 3. Well, after a second thought maybe the special tasks are not so special, so let's put them too into a function:

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'

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

Now let's put it all together:

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 现在不再是 list 而是 dict,所以如果你简单地迭代它就像 if choice in options 你的迭代在 keys 上:['1', '2', 'D', 'X'],但是如果你执行 options['X'] 你会得到退出函数(不是那么美妙!).

The key to your switch lies in options that now is no more a list but a dict, so if you simply iterate on it like if choice in options your iteration is on the keys:['1', '2', 'D', 'X'], but if you do options['X'] you get the exit function (isn't that wonderful!).

现在我们再改进一下,因为维护主菜单消息和options字典不太好,一年后我可能会忘记改变一个或另一个,我不会得到我想要的想要,我很懒,我不想做两次同样的事情,等等......
那么为什么不将 options 字典传递给 display_manu 并让 display_menu 使用 __doc__<中的文档字符串完成所有工作/code> 生成菜单:

Now let's improve again, because maintaining the main menu message and the options dictionary it's not too good, a year from now I may forget to change one or the other, I will not get what I want and I'm lazy and I don't want to do twice the same thing, etc...
So why don't pass the options dictionary to display_manu and let display_menu do all the work using the doc-strings in __doc__ to generate the menu:

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

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

对于options,我们需要OrderedDict 而不是dict,因为OrderedDict 顾名思义,保留其项目的顺序(查看官方文档).所以我们有:

We'll need OrderedDict instead of dict for options, because OrderedDict as the name suggests keep the order of its items (take a look at the official doc). So we have:

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 类并继承它在这里将是完美的.

Beware that you have to design your actions so that they all have the same signature (they should be like that anyway, they are all actions!). You may want to use callables as actions: instances of class with __call__ implemented. Creating a base Action class and inherit from it will be perfect here.

这篇关于如何处理来自 raw_input 的整数和字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆