TypeError: can only concatenate str (not "NoneType") to str in Python

Dung Do Tien Sep 19 2021 186

Hello you guys, I am a newbie in Python and I'm also studying more about Python.

I have a small code functions and I want to convert all uppercase characters to lowercase. Function as below:

def convertChar(char):
    if char >= 'A' and char <= 'Z':
        return chr(ord(char) + 32)
def toLowerCase(string):
    for char in string:
        string = string + convertChar(char)
    return string
string = input("Enter string - ")
result = toLowerCase(string)
print(result)

But I get an exception TypeError: can only concatenate str (not "NoneType") to str when I run code above.

Enter string - Python
Traceback (most recent call last):
  File "main.py", line 9, in <module>
    result = toLowerCase(string)
  File "main.py", line 6, in toLowerCase
    string = string + convertChar(char)
TypeError: can only concatenate str (not "NoneType") to str

And I am using python 3.8.2

Anyone can explain it to me? How can I solve it?

Thanks for any response.

Have 1 answer(s) found.
  • K

    Kitajima 2910 Sep 19 2021

    This error throw because your function is not return value. You can see convertChar() function still not return for else case. So you can change code as below:

    def convertChar(char):
        if char >= 'A' and char <= 'Z':
            return chr(ord(char) + 32)
            
        return char
            
    def toLowerCase(string):
        str = ""
        for char in string:
            str = str + convertChar(char)
            
        return str
        
    string = input("Enter string - ")
    result = toLowerCase(string)
    print(result)

    In the toLowerCase() function I also changed a little code, I used to other variable to help store value return for this function help avoid duplicate content, and below is result:

    Enter string - LAZY LOADING, AGGREGATE AND CQRS
    lazy loading, aggregate and cqrs

    I hope it resolve issue for you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close