Convert input str to int in python

Asked by At

I get the error code:

TypeError: '>' not supported between instances of 'str' and 'int' in its current state.

The problem is that I don't know how to convert user input expectations to integer from string format.

number = input ("Please guess what number I'm thinking of. HINT: it's between 1 and 30")

I've looked up how to do it but I couldn't find what I was looking for because I'm not sure how to word my question properly.

I've tried putting "int" after number and after input but it doesn't work. Not sure where to put it to get it to work.

1 Answers

2
Yusufsn On Best Solutions

By default, the input type is string. To convert it into integer, just put int before input. E.g.

number = int(input("Please guess what number I'm thinking of. HINT: it's between 1 and 30: "))
print(type(number))

Sample of the output:

Please guess what number I'm thinking of. HINT: it's between 1 and 30: 30
<class 'int'>   # it shows that the input type is integer

ALTERNATIVE

# any input is string
number = input("Please guess what number I'm thinking of. HINT: it's between 1 and 30: ")   
try:                      # if possible, try to convert the input into integer
    number = int(number)
except:                   # if the input couldn't be converted into integer, then do nothing
    pass
print(type(number))       # see the input type after processing

Sample of the output:

Please guess what number I'm thinking of. HINT: it's between 1 and 30: 25    # the input is a number 25
<class 'int'>   # 25 is possible to convert into integer. So, the type is integer

Please guess what number I'm thinking of. HINT: it's between 1 and 30: AAA   # the input is a number AAA
<class 'str'>   # AAA is impossible to convert into integer. So, the type remains string