Python Forum
TypeError: '<' not supported between instances of 'str' and 'int' - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: TypeError: '<' not supported between instances of 'str' and 'int' (/thread-23854.html)



TypeError: '<' not supported between instances of 'str' and 'int' - Svensation - Jan-20-2020

Dear all

I just tried my first steps with Python and found a - on the first sight - simple example in the internet. I tried to do it exactly the same way mentioned on the page. The programme looks as follows:

secret = 10
guess =0
i = 0

while guess != secret:
    guess = input("Raten Sie: ")
    if guess < secret:
        print ("Zu klein")
    if guess > secret:
        print ("Zu gross")
    i = i + 1
print ("Super, Sie haben es in "), i, ("Versuchen geschafft!")
Unfortunately it shows me the message: TypeError: '<' not supported between instances of 'str' and 'int'

What does that mean? What is wrong?

Thx for any help!


RE: TypeError: '<' not supported between instances of 'str' and 'int' - buran - Jan-20-2020

input() will return str. you need to convert it to int in order t do the comparison


RE: TypeError: '<' not supported between instances of 'str' and 'int' - Svensation - Jan-20-2020

Hi Buran

Thx for the information, will do better next time.

As I said I am an real beginner. What do you mean with int? where do I have to place that?


RE: TypeError: '<' not supported between instances of 'str' and 'int' - buran - Jan-20-2020

the built-in function int()

guess = int(input("Raten Sie: "))
note that incorrect input, that cannot be converted to int will raise an exception
Error:
ValueError: invalid literal for int() with base 10



RE: TypeError: '<' not supported between instances of 'str' and 'int' - Svensation - Jan-20-2020

thx a lot, it works!

Except the last line, as it doesn't count the number of trials. It only showes me the first piece of the print command.


RE: TypeError: '<' not supported between instances of 'str' and 'int' - buran - Jan-20-2020

it should be
print("Super, Sie haben es in ", i, "Versuchen geschafft!")
however it's waaaaaaay better to use string formatting, e.g.

using f-strings (python3.6+):
print(f"Super, Sie haben es in {i} Versuchen geschafft!")
or str.format() method:
print("Super, Sie haben es in {} Versuchen geschafft!".format(i))
see
https://docs.python.org/3/library/string.html#format-string-syntax
https://pyformat.info/