生成一个循环程序。使用python 3改写,并将输入lower处理,避免输入大小写对判断的影响。
这里面有个知识点是将写好的命令用exec执行
#!/usr/bin/env python dashes = '\n' + '-' * 50 # dashed line #dashes用于做格式化输出 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 = input('Loop type? (For/While) ').lower() dtype = input('Data type? (Number/Seq) ').lower() #输入f或者w if dtype == 'n': start = int(input('Starting value? ') ) stop = int(input('Ending value (non-inclusive)? ') ) step = int(input('Stepping value? ') ) seq = str(range(start, stop, step)) else: seq = input('Enter sequence: ') var = input('Iterative variable name? ') if ltype == 'f': exec_str = exec_dict['f'] % (var, seq, var) elif ltype == 'w': if dtype == 's': svar = 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()