猿问

大写备用字母

我想为任何给定的单词写一个备用的大写字母。所以我创建下面的函数。但是问题在于它不返回任何值。相反,我觉得它陷入了无限循环。


def farrange(word):

finaloutput = ''

i = 0

for i in word:

    if i%2 == 0:

        finaloutput = finaloutput + word[i].upper()        

    else:            

        finaloutput = finaloutput + word[i].lower()    

    i = i + 1   

return finaloutput

我知道还有其他方法可以解决问题。我使用了另一种元组拆包的方式。但是我想知道为什么会这样吗?


呼唤远方
浏览 183回答 3
3回答

繁花不似锦

您i既用作循环变量(递增整数),又用作容纳字符串的变量。这就是为什么它不起作用。尝试使用此功能的固定代码:finaloutput = ''i = 0for e in word:    if i%2 == 0:        finaloutput = finaloutput + e.upper()            else:                    finaloutput = finaloutput + e.lower()        i = i + 1   return finaloutput您还可以进行列表理解:''.join([e.lower() if c%2 else e.upper() for c,e in enumerate(a)])

德玛西亚99

问题是您要遍历单词并将其字母用作索引,这样可以解决此问题:def farrange(word):    finaloutput = ''    for i, l in enumerate(word):        if i%2 == 0:            finaloutput += l.upper()                else:                        finaloutput += l.lower()    return finaloutput例如,一种更pythonic的方式:def arrange(word):    op = (        str.upper,        str.lower    )    return "".join(op[x%2](l) for x, l in enumerate(word))

吃鸡游戏

谢谢大家的解释和快捷方式!如果我使用while循环怎么办?def farrange(word):finaloutput = ''i = 0while i < len(word):&nbsp; &nbsp; if i%2 == 0:&nbsp; &nbsp; &nbsp; &nbsp; finaloutput = finaloutput + word[i].upper()&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; finaloutput = finaloutput + word[i].lower()&nbsp; &nbsp; i = i + 1&nbsp;return finaloutputprint(farrange("abc")在这种情况下,我将i用作循环变量,并且它的相同值将作为单词的索引。因此,我认为这应该可行,但是这次,我只得到第一封信。没有其他的。为了检查计数器是否没有卡在while循环中,我将while条件更改为,while i < 3.但是没有用。再次返回输出为a。
随时随地看视频慕课网APP

相关分类

Python
我要回答