2017-08-12 216 views
0

我对python非常陌生,我在代码中调用一个函数,它有一个while循环,代码如下。问题是在循环的最后一个被更新的变量'n'没有正确地改变它的值,而是得到值'0'。我已经通过pdb调试器进行了检查。我无法理解它为什么会发生。我是PYTHON的新手。我错了,它与C/C++? 这PROGRAMM产生随机密钥,我们必须坡口,这些随机密钥有时会 代码之后重复:Python脚本执行错误

def answer(n, b): 


    cyclenum = 0 #his counts no. of times loop executes 

    desired_len = len(str(n)) 
    listofnums = [] 

    while True: 
     newnum = str(n) 
     if newnum in listofnums: 
      print(cyclenum) 
      break 

    bla=newnum.split() #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 
    x5=int(bla[0]) 
    x4=[] 
    while(x5>0): 
     t=x5%10 
     x4.append(t) # in this para , the sole aim is to rearrange the 
     x5 = x5/10  # digits of the no. in descending order 
     x3 = sorted(x4, key=int, reverse=True) 
    x2=map(str,x3) 
    x1=''.join(x2)   
    bla=x1.split() 
    x=int(bla[0]) #!!!!!!!!!!!!!!!!!!!!!!!!!! 


    bla=newnum.split() 
    y5=int(bla[0]) 
    y4=[] 
    while(y5>0): 
     t=y5%10 
     y4.append(t) #if 0 comes in start due to ascending order 
     y5 = y5/10  # they are ignored 
     y3 = sorted(y4, key=int) 
    y2=map(str,y3) 
    y1=''.join(y2)   
    bla=y1.split() 
    y=int(bla[0]) 


    z = x - y 

    newz=0 
    if len(str(z)) != desired_len: 
    newz = map(int, str(z)) 
    lendiff = desired_len - len(str(z)) 
    newz = list(newz) 
    for i in range(0, lendiff): 
     newz.insert(0, 0)     #here ignored 0 are added 
    cyclenum += 1       #to keep the length constant 
    listofnums.append(newnum)     
    n = newz 


answer(n="210022",b=3) 

******************** **编辑1 对不起,缩进错误是一个错误

+2

您的代码的缩进错误。为了我们能够帮助您,您需要以正确的格式提供代码。另一方面,问题可能出现在'newz = 0'这一行,因为你将'newz'分配给'n'。 – EsotericVoid

+0

如果我们知道该代码应该做什么,那将会更容易帮助您。请给我们一个总体概述,并在代码中添加注释,以解释每个部分试图实现的内容。我怀疑'bla = x1.split()'和'bla = y1.split()'没有做你期望的。顺便说一句,你可能应该使用'/ /'而不是'/';在Python 2中并不重要,但它在Python 3中有很大的不同。 –

+0

@Bit我认为你得到我的问题,我对使用全局关键字 –

回答

0

您是否检查过,当您执行它时,以下if语句的计算结果为true?

if len(str(z)) != desired_len: 

这可以解释为什么它停留在0

+0

中添加注释为你可以看到第一次迭代,表达式将评估为假,即使'n'为'0' –