【问题标题】:'>' is not supported between instances of 'str' and 'int' [duplicate]在“str”和“int”的实例之间不支持“>”[重复]
【发布时间】:2018-12-26 11:49:41
【问题描述】:

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

我像昨天一样开始学习 Python,但遇到了这个问题,当正在执行 if 语句时,我收到一条错误消息,指出 strint 的实例之间不支持 >

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

我应该在此处更改什么,以使其以所需的方式工作。

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 语句的开头收到错误,指出&gt; 运算符不能用于比较字符串和整数。

【问题讨论】:

  • Python 虽然像 JS 一样是动态类型的,但在比较不同类型方面它允许的内容更加严格。 age 这里确实是一个字符串,与 JS 不同,&gt; 运算符不会自动为您将字符串转换为数字或数字为字符串。
  • @Robinzigmond 请注意,在 Python 2 中,这种比较是有效的,但基本上是无稽之谈。它将根据类型名称按字典顺序进行比较。谢天谢地,“功能”已被删除。

标签: python


【解决方案1】:

正如回溯所说,age 是一个字符串,因为它刚刚被用户“输入”。与 C 不同,没有类似 scanf("%d", &amp;age) 的方法,因此您需要使用 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)

【讨论】:

    【解决方案2】:

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

    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.")
    

    【讨论】:

      【解决方案3】:

      需要将年龄转换为int,默认为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.")
      

      【讨论】:

        猜你喜欢
        • 2023-04-08
        • 2020-05-19
        • 2021-08-10
        • 2019-11-18
        • 1970-01-01
        • 2019-09-10
        • 2018-02-23
        • 2020-03-12
        • 1970-01-01
        相关资源
        最近更新 更多