Python 3 - function returns None type, yet print g

2019-08-13 22:32发布

问题:

I wrote a function that takes a string and using a for loop reads each letter in the string. Based on what the two adjacent letters are, it writes a new letter to a new string. Once the for loop finishes, if the length of the new string is greater than 1, it calls the function again with the new string. Everything seems to work fine, except it is returning a None type. It will print the correct output from inside the function, and the type is correct (string), but when I do print(triangle(row)) I get a None type back. I have run the debugger in Spyder and followed each step with the variable explorer. I am sure I am missing something simple, but I don't know what it is.

def triangle(row):

    newRow = ''
    i = 0 # index of the string

    if len(row) <= 1: # if it is only one letter, just return that
        return row


        for y in range(len(row)-1):
            if row[i] == row[i + 1]:
                newRow += row[i] 
            elif row[i] == 'B' and row[i + 1] == 'G':
                newRow += 'R'
            elif row[i] == 'G' and row[i + 1] == 'B':
                newRow += 'R'
            elif row[i] == 'R' and row[i + 1] == 'G':
                newRow += 'B'
            elif row[i] == 'G' and row[i + 1] == 'R':
                newRow += 'B'
            elif row[i] == 'B' and row[i + 1] == 'R':
                newRow += 'G'
            elif row[i] == 'R' and row[i + 1] == 'B':
                newRow += 'G'
            i += 1
        if len(newRow) > 1:
            triangle(newRow)

        else:
            print(newRow) # prints 'B'
            print(type(newRow)) # prints <class 'str'>
            return newRow

row = 'RGBG'
triangle(row) # should output 'B'
标签: python-3.6