【问题标题】:Convert an input result/string to integer in Python在 Python 中将输入结果/字符串转换为整数
【发布时间】:2021-03-07 20:39:12
【问题描述】:

我在运行此代码时遇到问题。当我尝试运行它时,它说它不起作用,因为年龄是一个字符串。如何将字符串转换为整数?我也尝试过 18 - int(age) 也行不通。

    age = input ("How old are you? (): ")
    if int(age) > 18 :
        print("You're old enough to drink") 
    else:
        print("You're not old enough to drink. Wait", + 18 - age, "more years")

【问题讨论】:

  • 您能否与我们分享这段代码产生的输出以及您期望它产生的输出。
  • 你在哪里做if int(age) > 18,用你自己的话来说:a) int(age) 部分是什么意思? b) 您是否希望这会修改age?为什么或为什么不?
  • "我也尝试过 18 - int(age),但也行不通。"你是什​​么意思,“不会工作”?你究竟是如何“尝试”这个的;当你尝试时发生了什么;这与应该发生的情况有何不同?
  • 可能是您正在输入诸如“19.0”之类的字符串 ....如果 str 具有 str 格式的浮点数,则不能直接将 str 转换为 int ....您可以为此使用浮点数。 .. 浮动(年龄)

标签: python string integer


【解决方案1】:
age = input("How old are you? (): "))
try:
    age = int(age)
    if age > 18 :
        print("You're old enough to drink.") 
    else:
        print(f"You're not old enough to drink. Wait {18-age} more years.")
except:
    print("You did not enter a valid age.")

【讨论】:

    【解决方案2】:

    注意input("How old are you? (): ")int(input("How old are you? (): "))

    age = int(input("How old are you? (): "))
    if int(age) > 18 :
        print("You're old enough to drink") 
    else:
        print("You're not old enough to drink. Wait {} more years".format(18-age))
    

    【讨论】:

      【解决方案3】:

      你可以加try.. except..

      像这样:

      age = input("How old are you? (): "))
      try:
          age = int(age)
          if age > 18 :
              print("You're old enough to drink.") 
          else:
              print(f"You're not old enough to drink. Wait {18-age} more years.")
      except ValueError:
          print("Not a valid age. Please enter again")
      

      顺便说一句,您可以使用f' 字符串作为字符串格式。

      或使用.format

      print("You're not old enough to drink. Wait {0} more years.".format(18-age))
      

      【讨论】:

        【解决方案4】:
        while True:
            age = input ("How old are you?  ")
        #Check if the input is a positive integer
            if age.isdigit() >0:
                break
        if int(age) > 18 :
            print("You're old enough to drink.") 
        else:
            print("You're not old enough to drink. Wait",18 - int(age), "more years.")
        #Remove the + in 18 because you already use comma after'Wait'
        

        【讨论】:

        • 我使用while循环重复提示无效输入。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-27
        • 2010-10-31
        • 1970-01-01
        • 1970-01-01
        • 2012-11-04
        相关资源
        最近更新 更多