Python - TypeError - TypeError: '<' not

2020-07-02 08:17发布

TypeError: '<' not supported between instances of 'NoneType' and 'int'

I have looked for an answer in Stack Overflow and found that I should be taking an int(input(prompt)), but that's what I am doing

def main():      
while True:
        vPopSize = validinput("Population Size: ")
        if vPopSize < 4:
            print("Value too small, should be > 3")
            continue
        else:
            break

def validinput(prompt):
while True:
    try:
        vPopSize = int(input(prompt))
    except ValueError:
        print("Invalid Entry - try again")
        continue
    else:
        break

标签: python
3条回答
叛逆
2楼-- · 2020-07-02 08:42

This problem also comes up when migrating to Python 3.

In Python 2 comparing an integer to None will "work," such that None is considered less than any integer, even negative ones:

>>> None > 1
False
>>> None < 1
True

In Python 3 such comparisons raise a TypeError:

>>> None > 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'NoneType' and 'int'

>>> None < 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'NoneType' and 'int'
查看更多
混吃等死
3楼-- · 2020-07-02 08:44

you need to add a return in your function to get the number you input, otherwise it return an implicit None

def validinput(prompt):
    while True:
        try:
            return int(input(prompt)) 
            # there is no need to use another variable here, just return the conversion, 
            # if it fail it will try again because it is inside this infinite loop
        except ValueError:
            print("Invalid Entry - try again")


def main():      
    while True:
        vPopSize = validinput("Population Size: ")
        if vPopSize < 4:
            print("Value too small, should be > 3")
            continue
        else:
            break

or as noted in the comments, make validinput also check if it is an appropriate value

def validinput(prompt):
    while True:
        try:
            value = int(input(prompt)) 
            if value > 3:
                return value
            else:
                print("Value too small, should be > 3")
        except ValueError:
            print("Invalid Entry - try again")


def main():      
    vPopSize = validinput("Population Size: ")
    # do stuff with vPopSize
查看更多
走好不送
4楼-- · 2020-07-02 08:58
Try: 
    def validinput(prompt):
    print(prompt) # this one is new!!
    while True:
        try:
            vPopSize = int(input(prompt))
        except ValueError:
            print("Invalid Entry - try again")
            continue
        else:
            break

And you will notice when the function is called.

The problem is that validinput() does not return anything. You'd have to return vPopSize

查看更多
登录 后发表回答