卡在python中的循环中-仅返回第一个值 [英] Stuck with loops in python - only returning first value

查看:74
本文介绍了卡在python中的循环中-仅返回第一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的初学者,他试图创建一个函数,该函数将使用偶数索引将所有值大写,并使用奇数索引将所有值都小写.

I am a beginner in Python trying to make a function that will capitalize all of the values with an even index, and make lowercase all of the values with an odd index.

我一直在为for循环而苦苦挣扎,只给了我第一个值.我也尝试过while循环.但是我很好奇是否有一种方法可以使其与for循环一起使用(我是否需要在某个地方使用"+ = 1"?)

I have been struggling repeatedly with for loops only giving me the first value. I have also tried with while loops. However I am curious if there is a way to make it work with for loops (do I need a '+=1' somewhere?)

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


func1('Testing Testing')

>>>'T'

推荐答案

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

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

这篇关于卡在python中的循环中-仅返回第一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆