Python 3 - function returns None type, yet print give correct output

浪子不回头ぞ 提交于 2019-12-24 07:50:24

问题


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'

来源:https://stackoverflow.com/questions/47785124/python-3-function-returns-none-type-yet-print-give-correct-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!