首页 > 解决方案 > 如何解决以下 Python 代码冻结问题?

问题描述

我有一个 Python 问题,我需要将输入作为函数中的字符串,并需要返回一个字符串,其中每个备用字母都是小写字母和大写字母的序列。例如:传递给函数的字符串:AmsTerdam那么返回的字符串应该是AmStErDaM. 它可以从任何情况开始,即小写或大写。

我仍处于 Python 的学习阶段,并提出了以下建议,但不知何故,当我尝试执行时,代码挂起。谁能帮我解决这个问题?

def myfunc(NAME='AmsTerdam'):
    leng=len(NAME)
    ind=1
    newlist=[]
    while ind <= leng:
        if ind%2==0:
            newlist.append(NAME[ind-1].upper())
        else:
            newlist.append(NAME[ind-1].lower())
    str(mylist)   # Can we typecast a list to a string?
    return newlist

OUT=myfunc('Ankitkumarsharma')
print('Output: {}'.format(OUT))

如果无法进行类型转换,以下是否正确?

def myfunc(NAME='AmsTerdam'):
    leng=len(NAME)
    ind=1
    newstr=''
    while ind <= leng:
        if ind%2==0:
            newstr=newstr+NAME[ind-1].upper()
        else:
            newstr=newstr+NAME[ind-1].lower()
    return newstr

OUT=myfunc('AmsTerdam')
print('Output: {}'.format(OUT))

标签: pythonpython-3.x

解决方案


本质上,您编写了一个 while true 循环,没有中断条件。

按照您之前的逻辑,我们可以重写您的循环并假设ind=1总是如此,我们得到:

def myfunc(NAME='AmsTerdam'):
  leng=len(NAME)
  newstr=''
  while 1 <= leng:
      if ind%2==0:
          newstr=newstr+NAME[ind-1].upper()
      else:
          newstr=newstr+NAME[ind-1].lower()
  return newstr

这意味着如果len(name) > 1,循环将永远运行。解决这个问题,我们得到以下函数,它将终止。

def myfunc(NAME='AmsTerdam'):
  leng=len(NAME)
  newstr=''
  ind=1
  while ind <= leng:
      if ind%2==0:
          newstr=newstr+NAME[ind-1].upper()
      else:
          newstr=newstr+NAME[ind-1].lower()
      ind+=1
  return newstr

推荐阅读