Not supported between instances of nonetype and int как исправить

This article will give you some solutions to fix the error "TypeError: '<' not supported between instances of 'NoneType' and 'int'". Read on it now.

If you are getting trouble with the error TypeError: ‘<‘ not supported between instances of ‘NoneType’ and ‘int’, do not worry! Today, our article will give a few solutions and detailed explanations to handle the problem. Keep on reading to get your answer.

TypeError is an exception when you apply a function or operation to objects of the wrong type. “TypeError: ‘<‘ not supported between instances of ‘NoneType’ and ‘int’” occurs when you use the ‘<‘ operator to compare an object with the None type and an object with the type int. Look at the simple example below that causes the error.

Code:

noneVar = None
intVar = 22
 
if noneVar < intVar:
  	print("noneVar is less than intVar")
else:
  	print("noneVar is greater than intVar")

Result:

TypeError Traceback (most recent call last)
 in <module>
----> 4 if noneVar < intVar:
TypeError: '<' not supported between instances of 'NoneType' and 'int'

Now you are clear about the cause of the problem. We will look at another example causing the error people often get when working with Object Oriented Programming.

Code:

class Student:
    def __init__(self, name, age):
        self.__name = name
        self.__age = age

    def showName(self):
      	print(self.__name)

    def showAge(self):
        print(self.__age)
    
student1 = Student("Helen Kang", 15)
 
if student1.showAge() < 18:
  	print("The student is still a teenager")
else:
  	print("The student is an adult")

Result:

TypeError Traceback (most recent call last)
in <module>
---> 15 if student1.showAge() < 18:
TypeError: '<' not supported between instances of 'NoneType' and 'int'

Solutions to “TypeError: ‘<‘ not supported between instances of ‘NoneType’ and ‘int’” error

Add a new function

As you can see, three functions are used to show the data. They are called non-return functions. When called, they print the result but return nothing and belong to the class NoneType. Let’s check the type of the function showName().

Code:

print(type(student1.showName()))

Result:

Helen Kang
<class 'NoneType'>

To fix this error, we must change their purpose. In the example, we want to compare the age with 18, so the function must return the age. We will create a function named ‘getAge’ to take the age.

Code:

class Student:
    def __init__(self, name, age):
        self.__name = name
        self.__age = age

    def showName(self):
      	print(self.__name)

    def showAge(self):
      	print(self.__age)

    def getAge(self):
      	return self.__age
  
student1 = Student("Helen Kang", 15)
 
if student1.getAge() < 18:
  	print("The student is still a teenager")
else:
  	print("The student is an adult")

Result:

The student is still a teenager

Use Exception Handling

Exception is a technique used to ignore errors. When using an exception, your process can not be interrupted by errors, and it will generate an error message and continue to execute the process. 

Code:

class Student:
    def __init__(self, name, age):
        self.__name = name
        self.__age = age

    def showName(self):
      	print(self.__name)

    def showAge(self):
      	print(self.__age)
  
student1 = Student("Helen Kang", 15)
 
try:
    if student1.showAge() < 18:
      	print("The student is still a teenager")
    else:
      	print("The student is an adult")
except:
  	print("There is an error here, please check again!")

Result:

15
There is an error here, please check again!

Note: Exception just ignores the error. It can not fix errors. You still come back to fix your errors.

Summary

Our article has explained the error “TypeError: ‘<‘ not supported between instances of ‘NoneType’ and ‘int’” and showed you the root of the problem. It is necessary to understand the purpose of each code line to avoid errors. Thanks for reading!

Maybe you are interested:

  • TypeError: ‘AxesSubplot’ object is not subscriptable
  • TypeError: ‘dict’ object is not callable in Python
  • TypeError: ‘list’ object cannot be interpreted as an integer
  • TypeError: ‘<‘ not supported between instances of list and int
  • TypeError: ‘<‘ not supported between instances of ‘str’ and ‘int’

My name is Robert Collier. I graduated in IT at HUST university. My interest is learning programming languages; my strengths are Python, C, C++, and Machine Learning/Deep Learning/NLP. I will share all the knowledge I have through my articles. Hope you like them.

Name of the university: HUST
Major: IT
Programming Languages: Python, C, C++, Machine Learning/Deep Learning/NLP

Человек разум

0 / 0 / 0

Регистрация: 29.03.2019

Сообщений: 14

1

12.06.2021, 20:49. Показов 5764. Ответов 2

Метки python (Все метки)


Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def f(N):
    n = bin(N)[2:]
    if N%2==0:
        n+=n[-2:]
    else:
        n= '1'+n+'1'
        return int(n,2)
 
 
m=1000
N = 1
while True:
    R=f(N)
    if R > 130 and R < m:#проблема
        m=f(N) 
        print(m)
    N+=1

Не понимаю почему в указаном месте пишет проблему. Вроде нормальное присваивание переменной.
Traceback (most recent call last):
File «d:EGEpython5.py», line 14, in <module>
if R > 130 and R < m:
TypeError: ‘>’ not supported between instances of ‘NoneType’ and ‘int’

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



2957 / 2123 / 615

Регистрация: 02.08.2011

Сообщений: 5,854

12.06.2021, 20:59

2

Человек разум, в if ветке ничего не возвращается, поэтому неявно возвращается None. Аналогичное поведение функций в JS-е, которые возвращают undefined при отсутствии возвращаемого значения. Видимо у вас просто проблема с отступами.



0



Михалыч

687 / 293 / 54

Регистрация: 28.02.2013

Сообщений: 838

15.06.2021, 09:00

3

Человек разум, а так?

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def f(N):
    n = bin(N)[2:]
    if N%2==0:
        n+=n[-2:]
    else:
        n= '1'+n+'1'
    return int(n,2)
 
 
m=1000
N = 1
while True:
    R=f(N)
    if R > 130 and R < m:#проблема
        m=f(N) 
        print(m)
    N+=1

Добавлено через 1 минуту
__________________
А это ваш код, т.е. когда else то return int(n,2), а если if то что вернуть?

Python
1
2
3
4
5
6
7
def f(N):
    n = bin(N)[2:]
    if N%2==0:
        n+=n[-2:]
    else:
        n= '1'+n+'1'
        return int(n,2)



0



Bug description

Steps to reproduce

  1. Create python file test.py with contents:
from __future__ import annotations

from collections import namedtuple


class SomeClass(namedtuple("SomeClass", [])):
    def method(self) -> SomeClass:
        pass
  1. Run pylint against it:
$ pylint -d C0114,C0115,C0116 test.py

Expected

  • pylint succeeds
  • worked as expected with pylint==2.12.2 and earlier versions of pylint

Actual

Exception on node <Name.SomeClass l.7 at 0x112389a10> in file '/private/tmp/pylintfail/crash_pylint.py'
Traceback (most recent call last):
  File "/private/tmp/pylintfail/.venv/lib/python3.7/site-packages/pylint/utils/ast_walker.py", line 73, in walk
    callback(astroid)
  File "/private/tmp/pylintfail/.venv/lib/python3.7/site-packages/pylint/checkers/variables.py", line 1362, in visit_name
    self._undefined_and_used_before_checker(node, stmt)
  File "/private/tmp/pylintfail/.venv/lib/python3.7/site-packages/pylint/checkers/variables.py", line 1405, in _undefined_and_used_before_checker
    node, stmt, frame, current_consumer, i, base_scope_type
  File "/private/tmp/pylintfail/.venv/lib/python3.7/site-packages/pylint/checkers/variables.py", line 1595, in _check_consumer
    is_recursive_klass,
  File "/private/tmp/pylintfail/.venv/lib/python3.7/site-packages/pylint/checkers/variables.py", line 1866, in _is_variable_violation
    maybe_before_assign = _detect_global_scope(node, frame, defframe)
  File "/private/tmp/pylintfail/.venv/lib/python3.7/site-packages/pylint/checkers/variables.py", line 262, in _detect_global_scope
    return frame.lineno < defframe.lineno
TypeError: '<' not supported between instances of 'int' and 'NoneType'
************* Module crash_pylint
crash_pylint.py:1:0: F0001: Fatal error while checking 'crash_pylint.py'. Please open an issue in our bug tracker so we address this. There is a pre-filled template that you can use in '/Users/name/Library/Caches/pylint/pylint-crash-2022-03-25-14.txt'. (fatal)

------------------------------------------------------------------
Your code has been rated at 0.00/10 (previous run: 0.00/10, +0.00)

Configuration

No response

Command used

pylint -d C0114,C0115,C0116 test.py

Pylint output

Exception on node <Name.SomeClass l.7 at 0x112389a10> in file '/private/tmp/pylintfail/crash_pylint.py'
Traceback (most recent call last):
  File "/private/tmp/pylintfail/.venv/lib/python3.7/site-packages/pylint/utils/ast_walker.py", line 73, in walk
    callback(astroid)
  File "/private/tmp/pylintfail/.venv/lib/python3.7/site-packages/pylint/checkers/variables.py", line 1362, in visit_name
    self._undefined_and_used_before_checker(node, stmt)
  File "/private/tmp/pylintfail/.venv/lib/python3.7/site-packages/pylint/checkers/variables.py", line 1405, in _undefined_and_used_before_checker
    node, stmt, frame, current_consumer, i, base_scope_type
  File "/private/tmp/pylintfail/.venv/lib/python3.7/site-packages/pylint/checkers/variables.py", line 1595, in _check_consumer
    is_recursive_klass,
  File "/private/tmp/pylintfail/.venv/lib/python3.7/site-packages/pylint/checkers/variables.py", line 1866, in _is_variable_violation
    maybe_before_assign = _detect_global_scope(node, frame, defframe)
  File "/private/tmp/pylintfail/.venv/lib/python3.7/site-packages/pylint/checkers/variables.py", line 262, in _detect_global_scope
    return frame.lineno < defframe.lineno
TypeError: '<' not supported between instances of 'int' and 'NoneType'
************* Module crash_pylint
crash_pylint.py:1:0: F0001: Fatal error while checking 'crash_pylint.py'. Please open an issue in our bug tracker so we address this. There is a pre-filled template that you can use in '/Users/name/Library/Caches/pylint/pylint-crash-2022-03-25-14.txt'. (fatal)

------------------------------------------------------------------
Your code has been rated at 0.00/10 (previous run: 0.00/10, +0.00)

Expected behavior

pylint succeeds

Pylint version

pylint 2.13.0
astroid 2.11.1
Python 3.7.10 (default, Apr  2 2021, 10:55:19) 
[Clang 12.0.0 (clang-1200.0.32.29)]

OS / Environment

No response

Additional dependencies

No response

https://narito.ninja/blog/detail/13/
I would like to make a semi-monthly calendar referring to the website.
We haven’t changed the basic part, only the part that returns the date.

In this state, the following error will appear.
unsupported operand type (s) for +: ‘NoneType’ and ‘int’

If i erase month = month + 1, the following error will occur.
‘<=’ not supported between instances of ‘int’ and ‘NoneType’

I know the integer isn’t coming back, but I don’t know how to solve it.
urls.py views.py is used as it is on the above site. I only tampered with the get_week_days part of mixins.py.
I am a pretty beginner, thank you.

class WeekCalendarMixin (BaseCalendarMixin):
    "" "Mixin that provides weekly calendar function" ""
    def get_week_days (self):
        "" "Return all days of the week" ""
        month = self.kwargs.get ('month')
        year = self.kwargs.get ('year')
        day = self.kwargs.get ('day')
        if month and year and day:
            date = datetime.date (year = int (year), month = int (month), day = int (day))
            if date.day<21 and day>4:
                date = datetime.date (year = int (year), month = int (month + 1), day = int (1))
                dtlist = [date + datetime.timedelta (days = day) for day in range (0,15)]
                return dtlist
            if date.day<6:
                dtm = calendar.monthrange (year, month) [1]
                date = datetime.date (year = int (year), month = int (month), day = int (15))
                dtlist = [date + datetime.timedelta (days = day) for day in range (1, dtm-14)]
                return dtlist
            if date.day>20:
                month = month-1
                dtm = calendar.monthrange (year, month) [1]
                date = datetime.date (year = int (year), month = int (month), day = int (15))
                dtlist = [date + datetime.timedelta (days = day) for day in range (1, dtm-14)]
                return dtlist
        else:
            date = datetime.date.today ()
            if date.day<21 and day>4:
                date = datetime.date (year = int (year), month = int (month + 1), day = int (1))
                dtlist = [date + datetime.timedelta (days = day) for day in range (0,15)]
                return dtlist
            if date.day<6:
                dtm = calendar.monthrange (year, month) [1]
                date = datetime.date (year = int (year), month = int (month), day = int (15))
                dtlist = [date + datetime.timedelta (days = day) for day in range (1, dtm-14)]
                return dtlist
            if date.day>20:
                # month = month + 1
                dtm = calendar.monthrange (year, month) [1]
                date = datetime.date (year = int (year), month = int (month), day = int (15))
                dtlist = [date + datetime.timedelta (days = day) for day in range (1, dtm-14)]
                return dtlist
    def get_week_calendar (self):
        "" "Returns a dictionary with weekly calendar information" ""
        self.setup_calendar ()
        days = self.get_week_days ()
        first = days [0]
        last = days [-1]
        calendar_data = {
            'now': datetime.date.today (),
            'week_days': days,
            'week_previous': first-datetime.timedelta (days = 7),
            'week_next': first + datetime.timedelta (days = 7),
            'week_names': self.get_week_names (),
            'week_first': first,
            'week_last': last,
        }
        return calendar_data

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Not rooted как исправить
  • Not produced due to error s
  • Not printed error encountered during print
  • Not phoenix dell insyde efi bios как исправить
  • Not mpisp mode 1b ssd ошибка

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии