Error 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

@kartik4949 @mingxingtan

I change positives_momentum to -1, but still have error.

[1,0]:Traceback (most recent call last):
[1,0]: File «/root/efficientdet/pyenv/lib/python3.6/multiprocessing/process.py», line 258, in _bootstrap
[1,0]: self.run()
[1,0]: File «/root/efficientdet/pyenv/lib/python3.6/multiprocessing/process.py», line 93, in run
[1,0]: self._target(*self._args, **self._kwargs)
[1,0]: File «main.py», line 361, in run_train_and_eval
[1,0]: _train(e * FLAGS.num_examples_per_epoch // FLAGS.train_batch_size)
[1,0]: File «main.py», line 277, in _train
[1,0]: max_steps=steps)
[1,0]: File «/root/efficientdet/pyenv/lib/python3.6/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py», line 3089, in train
[1,0]: rendezvous.raise_errors()
[1,0]: File «/root/efficientdet/pyenv/lib/python3.6/site-packages/tensorflow_estimator/python/estimator/tpu/error_handling.py», line 150, in raise_errors
[1,0]: six.reraise(typ, value, traceback)
[1,0]: File «/root/efficientdet/pyenv/lib/python3.6/site-packages/six.py», line 703, in reraise
[1,0]: raise value
[1,0]: File «/root/efficientdet/pyenv/lib/python3.6/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py», line 3084, in train
[1,0]: saving_listeners=saving_listeners)
[1,0]: File «/root/efficientdet/pyenv/lib/python3.6/site-packages/tensorflow_estimator/python/estimator/estimator.py», line 349, in train
[1,0]: loss = self._train_model(input_fn, hooks, saving_listeners)
[1,0]: File «/root/efficientdet/pyenv/lib/python3.6/site-packages/tensorflow_estimator/python/estimator/estimator.py», line 1175, in _train_model
[1,0]: return self._train_model_default(input_fn, hooks, saving_listeners)
[1,0]: File «/root/efficientdet/pyenv/lib/python3.6/site-packages/tensorflow_estimator/python/estimator/estimator.py», line 1204, in _train_model_default
[1,0]: self.config)
[1,0]: File «/root/efficientdet/pyenv/lib/python3.6/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py», line 2921, in _call_model_fn
[1,0]: config)
[1,0]: File «/root/efficientdet/pyenv/lib/python3.6/site-packages/tensorflow_estimator/python/estimator/estimator.py», line 1163, in _call_model_fn
[1,0]: model_fn_results = self._model_fn(features=features, **kwargs)
[1,0]: File «/root/efficientdet/pyenv/lib/python3.6/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py», line 3179, in _model_fn
[1,0]: features, labels, is_export_mode=is_export_mode)
[1,0]: File «/root/efficientdet/pyenv/lib/python3.6/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py», line 1700, in call_without_tpu
[1,0]: return self._call_model_fn(features, labels, is_export_mode=is_export_mode)
[1,0]: File «/root/efficientdet/pyenv/lib/python3.6/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py», line 2031, in _call_model_fn
[1,0]: estimator_spec = self._model_fn(features=features, **kwargs)
[1,0]: File «/root/efficientdet/automl/efficientdet/det_model_fn.py», line 638, in efficientdet_model_fn
[1,0]: variable_filter_fn=variable_filter_fn)
[1,0]: File «/root/efficientdet/automl/efficientdet/det_model_fn.py», line 385, in _model_fn
[1,0]: cls_outputs, box_outputs, labels, params)
[1,0]: File «/root/efficientdet/automl/efficientdet/det_model_fn.py», line 230, in detection_loss
[1,0]: num_positives_sum = utils.cross_replica_mean(num_positives_sum)
[1,0]: File «/root/efficientdet/automl/efficientdet/utils.py», line 62, in cross_replica_mean
[1,0]: return tf.tpu.cross_replica_sum(t) / tf.cast(num_shards, t.dtype)
[1,0]: File «/root/efficientdet/pyenv/lib/python3.6/site-packages/tensorflow/python/util/dispatch.py», line 201, in wrapper
[1,0]: return target(*args, **kwargs)
[1,0]: File «/root/efficientdet/pyenv/lib/python3.6/site-[1,0]:packages/tensorflow/python/ops/math_ops.py», line 921, in cast
[1,0]: x = ops.convert_to_tensor(x, name=»x»)
[1,0]: File «/root/efficientdet/pyenv/lib/python3.6/site-packages/tensorflow/python/framework/ops.py», line 1499, in convert_to_tensor
[1,0]: ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
[1,0]: File «/root/efficientdet/pyenv/lib/python3.6/site-packages/tensorflow/python/framework/constant_op.py», line 338, in _constant_tensor_conversion_function
[1,0]: return constant(v, dtype=dtype, name=name)
[1,0]: File «/root/efficientdet/pyenv/lib/python3.6/site-packages/tensorflow/python/framework/constant_op.py», line 264, in constant
[1,0]: allow_broadcast=True)
[1,0]: File «/root/efficientdet/pyenv/lib/python3.6/site-packages/tensorflow/python/framework/constant_op.py», line 282, in _constant_impl
[1,0]: allow_broadcast=allow_broadcast))
[1,0]: File «/root/efficientdet/pyenv/lib/python3.6/site-packages/tensorflow/python/framework/tensor_util.py», line 444, in make_tensor_proto
[1,0]: raise ValueError(«None values not supported.»)
[1,0]:ValueError: None values not supported.

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

0 / 0 / 0

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

Сообщений: 14

1

12.06.2021, 20:49. Показов 5719. Ответов 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



2955 / 2121 / 615

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

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

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



#python

Вопрос:

Я пытаюсь понять, как справиться с этой ошибкой типа в моей программе. Я получаю ошибку типа в этой функции

     # Function will get the distances between current location and next package's delivery address.
def find_distance(current_address, package_address):
    if find_address(package_address) > find_address(current_address):
        current_distance = distance_data[find_address(package_address)][
            find_address(current_address)]
    else:
        current_distance = distance_data[find_address(current_address)][
            find_address(package_address)]
    return current_distance
 

Функция вызывает другую функцию find_address()

    def find_address(address):
    i = 0
    while i < len(address_data):
        if address == address_data[i][1]:
            return i
        else:
            i = i   1


Traceback (most recent call last):
  File "C:UsersDeNyus KeysPycharmProjectsC950main.py", line 21, in <module>
    start_trucks(timedelta(hours=-0))
  File "C:UsersDeNyus KeysPycharmProjectsC950trucks.py", line 32, in start_trucks
    run_routes(truck1, time)
  File "C:UsersDeNyus KeysPycharmProjectsC950trucks.py", line 48, in run_routes
    new_distance = find_distance(current_location, package_address)  # Calls find_distance() function
  File "C:UsersDeNyus KeysPycharmProjectsC950trucks.py", line 77, in find_distance
    if find_address(package_address) > find_address(current_address):
TypeError: '>' not supported between instances of 'NoneType' and 'int'
 

Функция find_address() возвращает значение int, которое является идентификатором пакетов, поэтому я не знаю, откуда берется «Нетип». Есть какие-нибудь идеи? Большое вам спасибо, ребята, за любую помощь. Я надеюсь, что написал достаточно кода, чтобы понять проблему.

Комментарии:

1. Он, безусловно, возвращается None , когда не может найти соответствующий адрес в address_data .

2. В сообщении об ошибке говорится, что первый вызов find_address(package_address) не возвращает ни одного. Это произойдет, если while i < len(address_data): завершится без каких-либо результатов, и функция завершится возвращаемым по умолчанию значением None.

3. Итак, что должно произойти, если find_address адрес не найден?

Ответ №1:

Причина сбоя в том, что у address_data вас нет записи для package_address пройденного, так что вы можете сделать, если какой-либо адрес отсутствует в address_data ответ, сказав, что не можете рассчитать расстояние.

 def find_distance(current_address, package_address):
    package_address = find_address(package_address)
    current_address = find_address(current_address)
    if not package_address or not current_address:
        return "Unable to get the distance between the address"

    if find_address(package_address) > find_address(current_address):
        current_distance = distance_data[find_address(package_address)][
            find_address(current_address)]
    else:
        current_distance = distance_data[find_address(current_address)][
            find_address(package_address)]
    return current_distance
 

Ответ №2:

Немного научившись использовать отладчик, я обнаружил, что используемый адрес package_address был "2010 West 500 S" в то время как адрес в загрузчике CSV, на который он ссылался, был "2010 West 500 South" . Как только я переименую его в точное соответствие, программа запустится.

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

Понравилась статья? Поделить с друзьями:
  • Error not null constraint failed
  • Error not launcher gta 5
  • Error none mapped
  • Error not found physx driver ок
  • Error not found dart html