如何将此代码从3.3版反向移植到2.7版

时间:2014-03-28 13:29:23

标签: python python-2.7 python-3.x

我必须在python中做一个任务。我做到了。但由于我的类中使用的软件是2.7版本,所以我需要将我的代码从python 3.3运行到2.7。这些代码在3.3版本中运行良好,但在2.7版本中运行不佳因此,你们可以帮助我吗? 这是我的代码。

# selectRobot.py #  # 2014-03-26 #

 '''
  The output will be like below:

  what type of robot application you like choose?
  a) assembly
  b) spot welding

  Then let say the customer choose a or b, it will go to next question:

  2.How much the load you expect for the robot to carry?
  a) 0-2 kg
  b) 0-5 kg

   And so on ...

  This is just a start ... need to continue ...
  until finished choosing all attributes of the desired robot.

  '''
  from __future__ import print_function
  menu1 = \
  '''Please choose the type of robot application ?
  a) assembly
  b) spot welding
  Please enter a or b    :  '''

  menu2 = \
  '''What is the max load for this robot?
  a) 0-5   kg
  b) 6-10  kg
  c) 11-15 kg
  Please enter a, b or c :  '''

  menu3 = \
 '''What is the reach for this robot?
  a) 0-1 m
  b) 1-2 m
  Please enter a or b    :  '''

  menu4 = \
  '''What is the mounting for this robot?
  a) floor
  b) wall
  Please enter a or b    :  '''

  def showMenuGetChoice( menu, low, high ):
  while True:
       reply = input( menu ).lower()
        if low <= reply and reply <= high:
            return reply
        else:
            print( "'", reply, "' was NOT in valid " \
                   'input range ', low, '..', high, sep = '' )

 modelsStr = [] # get empty list to hold models
 solns = [] # get empty list to hold all possible solution lists
 count = 0

 for i, a in enumerate(['a', 'b']):
    for j, b in enumerate(['a', 'b', 'c']):
        for k, c in enumerate(['a', 'b']):
            for m, d in enumerate(['a', 'b']):
                count += 1
                modelsStr.append( 'model_' + str(count) )
                solns.append( [a,b,c,d])

     # print( modelsStr )


 def mainLoop():
    robot_specs = [] # get an empty list

    robot_specs.append( showMenuGetChoice( menu1, 'a', 'b' ))

    robot_specs.append( showMenuGetChoice( menu2, 'a', 'c' ))

    #print( 'So far, robot_specs =', robot_specs )

    robot_specs.append( showMenuGetChoice( menu3, 'a', 'b' ))

    robot_specs.append( showMenuGetChoice( menu4, 'a', 'b' ))

    #print( 'So far, robot_specs =', robot_specs )

    for i, lst in enumerate( solns ):
        if lst == robot_specs:
            print( robot_specs, '==>', modelsStr[i] )
            return
    print( 'There was an unexpected error ...' ) 


more = True
while( more ):
    mainLoop()
    reply = input( '\nMore (y/n) ? ' ).lower()
    if reply == 'n':
        more = False
        input( "Press 'Enter' to continue/exit ... " )

1 个答案:

答案 0 :(得分:0)

您发布的代码(除了过于难以手动修复的缩进问题)几乎完全是Python 2准备好了。您已使用from __future__ import print_function来处理print()函数。

唯一剩下的就是input()功能;在Python 2中,input()raw_input()eval()的组合;用input()替换所有raw_input()次调用,你的代码应该在Python 2上运行就好了。