关于python:’>’

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

本问题已经有最佳答案,请猛点这里访问。

我最近才开始学习编码,这是我在这里的第一个问题,如果这个问题太愚蠢,请原谅我。

我像昨天一样开始学习python,在执行if语句时,我遇到一个错误,说明strint的实例之间不支持>

我知道一些javascript,我认为变量age被视为一个字符串,但如果输入是一个数字,它不应该被视为整数。

我应该在这里做些什么改变,让它以理想的方式工作。

1
2
3
4
5
6
7
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.")

我希望程序根据输入的时间打印各自的语句,但在if语句的开头出现错误,说明不能使用>运算符比较字符串和整数。


比较运算符正在将字符串与整数进行比较。所以在比较之前把你的刺转换成int

1
2
3
4
5
6
7
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.")

正如回溯所说,age是一个字符串,因为它刚刚被用户"输入"。与C不同的是,没有方法可以执行类似于scanf("%d", &age)的操作,因此需要使用age = int(age)手动将age转换为整数。

1
2
3
4
5
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)


您需要将年龄转换为int,默认为string

1
2
3
4
5
6
7
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.")