Search code examples
pythondictionaryhard-coding

Dictionary Writing and Hard-Coded Entries


TypeError: Can't convert 'NoneType' object to str implicitly. That is the error I get when I try to hard-code an entry into a dictionary by using a function. Having user input works, and puts it into the dictionary, but this won't work. I've searched for other errors such as this(meaning the TypeError.), but I have come up with nothing. The other two(This and this) entries that had this error were irrelevant to me.

So. I tried to make AweInspiring and BeingAwesome a print function thinking it would print properly into the Achievements dictionary because simply putting AweInspiring and BeingAwesome there would lead to it saying it needs to be defined. Then it turned up this error. I think it should work, but it doesn't and I don't know why. Can anybody help me?

    achievements = {}
    AweInspiring = print()
    BeingAwesome = print()

    def dovar():
        global achievements
        print('Type in either \'achievement get\' or \'view achievements.\'')
        achieve = input()
        if achieve == 'view achievements':
            print('Achievements')
            for x in achievements.keys():
                print('Achievement Name: ' + x + '\tFor: ' + achievements[x])
        elif achieve == 'achievement get':
            achieveget()
        elif achieve == 'achieve':
            hardachieve()

    def achieveget():
        print('Add Achievement')
        achievename = input('Name of achievement earned: ')
        achievedesc = input('How was the achievement earned: ')
        achievements[achievename] = achievedesc
        dovarloop()

    def hardachieve():
        achievename = AweInspiring
        achievedesc = BeingAwesome
        achievements[achievename] = achievedesc
        dovar()

    def dovarloop():
        dovar()

    dovar()

Solution

  • print() does not return anything (by default, it returns None). So then when you do achievements[achievename] = achievedesc, python is actually making this:

    {None:None}
    

    Then you're doing:

    print('Achievement Name: ' + x + '\tFor: ' + achievements[x])
    

    Where x is the key None and achievements[x] is the value (which is also None)

    But you can't concatenate a string and a NoneType (hence the error).


    So pretty much, your code in simplest form (as an example), you're trying to do this:

    print('Hello' + None)
    

    To solve this, you can make AweInspiring and BeingAwesome empty strings:

    AweInspiring = ''
    BeingAwesome = ''