'>' is not supported between instances of 'str' and 'int'

Viewed 34092

I started learning coding quite recently and this is my first question here, so pardon me if the question is too silly.

I started learning Python like yesterday and I am stuck at this problem, when the if statement is being executed, i get an error stating that > is not supported between instances of str and int.

I know a bit of JavaScript, and I think that the variable age is being treated as a string, but shouldn't it be considered an integer if the input is a number.

What should I change here, to make it work in the desired way.

name = input("Enter your name:")
print("Hello, " +name)
age = input("Please enter your age:")
if age > 3:
    print("You are allowed to use the internet.")
elif age <= 3:
    print("You are still a kid what are you doing here.")

I expect the program to print the respective statements according to the age I input, but i get an error at the start of the if statement, stating that the > operator cannot be used to compare a string and an integer.

3 Answers

As the traceback said, age is a string because it has just been "inputted" by the user. Unlike C, there is no method to do something like scanf("%d", &age), so you need to manually cast age to an integer with age = int(age).

name = input("Enter your name:")
print("Hello, " +name)
age = input("Please enter your age:")
# do exception handling to make sure age is in integer format
age = int(age)

the comparison operator is comparing a string with integer. So convert your sting to int before comparison

name = input("Enter your name:")
print("Hello, " +name)
age = input("Please enter your age:")
if int(age) > 3:
    print("You are allowed to use the internet.")
elif int(age) <= 3:
    print("You are still a kid what are you doing here.")

You need to convert age into int by default it is string

name = input("Enter your name:")
print("Hello, " +name)
age = int(input("Please enter your age:"))
if age > 3:
    print("You are allowed to use the internet.")
elif age <= 3:
    print("You are still a kid what are you doing here.")
Related