简体   繁体   中英

TypeError: unsupported operand type(s) for %: 'NoneType' and 'int' | Python 3

Currently I am working on a decimal to octal number converter. However, I sometimes get this error caused by line 28:

TypeError: unsupported operand type(s) for %: 'NoneType' and 'int'

It seems to happen randomly, sometimes it does it with a number which in a next run of the code just gets converted.

The code is listed below:

decimaal = 0


# Laat de gebruiker een waarde in typen
def user_input():
    getal = int(input('Geef het getal: '))
    if getal < 10000:
        return getal
    else:
        print('Het getal moet kleiner zijn dan 10.000!')
        user_input()


# functie om getal in het decimaal- naar octaal-stelsel om te zetten
def decimaal_octaal_converter(decimaal):
    resultaat = []
    quotient = decimaal
    rest = 0

    # Maakt een lijst met het octale resultaat
    while quotient != 0:
        """
        Soms geeft lijn 28 de volgende error:
        TypeError: unsupported operand type(s) for %: 'NoneType' and 'int'
        Maar waarom?
        """
        rest = quotient % 8
        quotient //= 8
        resultaat.append(rest)

    # Lijst moet omgedraaid worden
    resultaat.reverse()
    octaal = ''

    # De lijst naar een string omzetten zodat de gebruiker het kan lezen
    for i in range(len(resultaat)):
        octaal += str(resultaat[i])

    return print('Het getal %s in octaal is %s' % (decimaal, octaal))


# De hoofd functie voor het omzetten van decimaal naar octaal
def converter():
    decimaal_octaal_converter(user_input())

converter()

This is for a project, hence the <10.000 part and dutch comment's

This problem occurs when i first try to convert '10000' and then '9999'

user_input() returns None if you at first enter a number equal to or greater than 10000, because the recursive call result is ignored. And when user_input() returns None then quotient ends up being set to None and you get your error.

Add a return :

def user_input():
    getal = int(input('Geef het getal: '))
    if getal < 10000:
        return getal
    else:
        print('Het getal moet kleiner zijn dan 10.000!')
        return user_input()

Better still, don't use recursion . All you need is an infinite loop:

def user_input():
    while True:
        getal = int(input('Geef het getal: '))
        if getal < 10000:
            return getal
        else:
            print('Het getal moet kleiner zijn dan 10.000!')

See Asking the user for input until they give a valid response for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM