Stuck with loops in python - only returning first value

后端 未结 5 1205
情话喂你
情话喂你 2020-12-02 01:16

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.

相关标签:
5条回答
  • 2020-12-02 01:32

    You can also use a generator, although it is a bit more advanced.

    def fun1(x):
        for (a,b) in enumerate (x):
            if a%2 == 0:
                yield b.upper()
            else:
                yield b.lower()
    
    def func1(x):
        return [i for i in fun1(x)]
    
    
    func1('Testing Testing')
    
    0 讨论(0)
  • 2020-12-02 01:35

    You are returning in the first iteration of the loop.

    Append the alphabets in a list and return concatinated. Also add 1 to a while checking condition if you want even index to capitalize as the index starts from 0. Use below example:

        def func1(x):
            result = []
            for (a,b) in enumerate (x):
                if (a+1)%2 == 0:
                    result.append(b.upper())
                else:
                    result.append(b.lower())
            return "".join(result)
    
    
        print func1('Testing Testing')
    

    Output:

        tEsTiNg tEsTiNg
    
    0 讨论(0)
  • 2020-12-02 01:42

    You are returning from the function early. you need to collect the data you want to return in a variable.

    def func1(x):
    returnMe = {}
        for (a,b) in enumerate (x):
             if a%2 == 0:
                  returnMe += b.upper()
             else:
                  returnMe += b.lower()
    return returnMe
    
    
    func1('Testing Testing')
    
    >>>'T'
    
    0 讨论(0)
  • 2020-12-02 01:46

    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
    
    0 讨论(0)
  • 2020-12-02 01:53

    You are returning after first iteration.

    Try the following:

    def func1(x):
        result = ''
        for (a,b) in enumerate (x):
             if a%2 == 0:
                  result += b.upper()
             else:
                  result += b.lower()
        return result
    
    0 讨论(0)
提交回复
热议问题