且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

卡在python中的循环中-仅返回第一个值

更新时间:2023-02-03 11:50:16

一旦到达 return ,函数就会结束.您需要在末尾而不是在循环内返回一次:

Functions end as soon as a return is reached. You'll need to return once at the end instead of inside the loop:

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