陷入python中的循环 - 只返回第一个值

hhi*_*231 3 loops enumerate python-3.x

我是 Python 的初学者,试图制作一个函数,该函数将使用偶数索引大写所有值,并使用奇数索引小写所有值。

我一直在为只给我第一个值的循环而苦苦挣扎。我也尝试过 while 循环。但是我很好奇是否有办法让它与 for 循环一起工作(我需要在某处使用 '+=1' 吗?)

def func1(x):
    for (a,b) in enumerate (x):
         if a%2 == 0:
              return b.upper()
         else:
              return b.lower()


func1('Testing Testing')

>>>'T'
Run Code Online (Sandbox Code Playgroud)

Car*_*ate 6

一旦达到 a 函数就结束return。您需要在最后而不是在循环内返回一次:

def func1(x):
  # The string to work on
  new_str = ""

  for (a,b) in enumerate (x):
    # Add to the new string instead of returning immediately
    if a%2 == 0:
      new_str += b.upper()
    else:
      new_str += b.lower()

  # Then return the complete string
  return new_str
Run Code Online (Sandbox Code Playgroud)