TypeError: '<' not supported between instances of 'int' and 'str' in Python

Dung Do Tien Oct 02 2021 154

Hello you guys, I am a newbie in Python and I'm also studying more about Python.

I have some lines of code, I want to learn about array, comparison and condition in Python. Function as below:

countries= []
num = 0

while(num >= 0 and num < 10):
    num = input('Enter number countries: ')
    if (0 < num <= 11):
        countries.append(num + 1)
    else:
        print('Invalid num, try again')

print(countries)

But I get an exception TypeError: '<' not supported between instances of 'int' and 'str' when I run code above.

Enter number countries: 5
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    if (0 < num <= 11):
TypeError: '<' not supported between instances of 'int' and 'str'

And I am using python 3.8.2

Anyone can explain it to me? How can I solve it?

Thanks for any suggestions.

Have 3 answer(s) found.
  • W

    Watcharapong Jakkawannorasing Oct 02 2021

    input() method always return string by default. So you can not compare string with number. You need to convert it to integer by using int() method.

    num = int(input('Enter number players: '))

    I hope it solve issue for you.

  • D

    Denis Cano Oct 02 2021

    If you are using Python3.x input() method will return a string, so you must use the method int() to convert the string to an integer.

    num = int(input('Enter number players: '))

    You can use more try-catch block to handle exception if you are enter not a integer.

  • N

    Nguyễn Danh Ngọc Oct 02 2021

    You need to cast num variable to integer datatype.

    num = input('Enter number players: ')

    To

    num = int(input('Enter number players: '))

    And it worked for you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close