3

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.

Ha. Huynh
  • 1,772
  • 11
  • 27
Sumedh
  • 89
  • 1
  • 2
  • 8
  • Python, although dynamically typed like JS, is stricter about what it allows in terms of comparing different types. `age` here will indeed be a string, and unlike JS the `>` operator won't automatically convert strings to number or numbers to strings for you. – Robin Zigmond Dec 26 '18 at 11:53
  • 1
    @Robinzigmond note that in Python 2, this comparison would be valid, but basically nonsense. It will be compared lexicographically based on the type name. Thankfully that "feature" was removed. – roganjosh Dec 26 '18 at 11:55

3 Answers3

2

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)
DarthCadeus
  • 372
  • 3
  • 13
1

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.")
Surjya Narayana Padhi
  • 7,741
  • 25
  • 81
  • 130
0

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.")
Sociopath
  • 13,068
  • 19
  • 47
  • 75