Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stuck with loops in python - only returning first value

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.

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'
like image 837
hhillman231 Avatar asked Feb 27 '26 04:02

hhillman231


1 Answers

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
like image 142
Carcigenicate Avatar answered Mar 01 '26 17:03

Carcigenicate



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!