且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

python核心编程loopmake.py错误

更新时间:2022-10-11 12:32:51

loopmake.py


#!/usr/bin/env python


dashes = '\n' + '-' * 50 # dashed line

exec_dict = {

'f': """ # for loop

for %s in %s:

   print %s

""",


's': """ # sequence while loop

%s = 0

%s = %s

while %s < len(%s):

   print %s[%s]

   %s = %s + 1

""",


'n': """ # counting while loop

%s = %d

while %s < %d:

   print %s

   %s = %s + %d

"""

}


def main():


   ltype = raw_input('Loop type? (For/While) ')

   dtype = raw_input('Data type? (Number/Seq) ')



   if dtype == 'n':

       start = input('Starting value? ')

       stop = input('Ending value (non-inclusive)? ')

       step = input('Stepping value? ')

       seq = str(range(start, stop, step))

var = raw_input('Iterative variable name? ')

   else:

       seq = raw_input('Enter sequence: ')

       var = raw_input('Iterative variable name? ')



   if ltype == 'f':

       exec_str = exec_dict['f'] % (var, seq, var)


   elif ltype == 'w':

       if dtype == 's':

           svar = raw_input('Enter sequence name? ')

           exec_str = exec_dict['s'] % (var, svar, seq, var, svar, svar, var, var, var)

       elif dtype == 'n':

           exec_str = exec_dict['n'] % (var, start, var, stop, var, var, var, step)


   print dashes

   print 'Your custom-generated code:' + dashes

   print exec_str + dashes

   print 'Test execution of the code:' + dashes

   exec exec_str

   print dashes


if __name__ == '__main__':

   main()


按照书上的测试,代码中少了红色的一行。




本文转自 freeterman 51CTO博客,原文链接:http://blog.51cto.com/myunix/1290999,如需转载请自行联系原作者