【问题标题】:Limiting the user input to a fixed length将用户输入限制为固定长度
【发布时间】:2019-03-16 07:14:52
【问题描述】:

我想将用户输入限制为固定长度,然后我必须将其相乘。我想要 C 值作为整数。我如何得到这个?

def F_to_C():
    F=int(input("enter the F value:"))  
    if len(F) >3:
        print("input is too long")
    else:
        C=(F-32)*(5/9)
        print("the corresponding celcius value is: ",C)

我的错误:

if len(F)>3:
TypeError: object of type 'int' has no len()

【问题讨论】:

  • 请编辑您的问题以提供更多上下文/解释。此外,您的代码似乎适用于 python3,如果是这种情况,请删除 python2 标记。
  • 检查之前你投射到int的长度?或检查 int 是否 > 999(但这意味着 -10000 有效)。如果您知道有效边界,也可以与F in range(..., ...) 联系。
  • 为什么想要限制长度?有效温度可以超过 3 位数。
  • 您的完整问题进入巨大的空盒子。较小的“标题”框仅用于的简短描述。
  • 当您检查长度 (if len(F) > 3) 时,您的 F 是一个整数。您应该在转换为 int 之前检查这一点。

标签: python python-3.5


【解决方案1】:

我想你的意思是1000:

def F_to_C():
  F=int(input("enter the F value:"))  
  if F>999:
      print("input is too long")
  else:
      C=(F-32)*(5/9)
      print("the corresponding celcius value is: ",C)

然后:

F_to_C()

示例输出:

enter the F value:234
the corresponding celcius value is:  112.22222222222223

如果想要整数(四舍五入):

def F_to_C():
  F=int(input("enter the F value:"))  
  if F>999:
      print("input is too long")
  else:
      C=round((F-32)*(5/9))
      print("the corresponding celcius value is: ",C)

如果只想四舍五入成为数字部分:

def F_to_C():
  F=int(input("enter the F value:"))  
  if F>999:
      print("input is too long")
  else:
      C=int((F-32)*(5/9))
      print("the corresponding celcius value is: ",C)

【讨论】:

    【解决方案2】:

    所以,我认为错误消息很清楚:变量F 是一个整数,它没有len()。试试这个:

    def F_to_C():
        F = input("enter the F value:")  
        if len(F) > 3:
            print("input is too long")
        else:
            C=(int(F)-32)*(5/9)
            print("the corresponding celcius value is: ",C)
    

    或来自@U9-Forward 的代码

    【讨论】:

    • 哦@U9-Forward,对不起,我很快就会编辑我的答案。
    【解决方案3】:
    F=int(input("enter the F value:"))  
    

    读取字符串并将其转换为 int

    if len(F) >3:
    

    这里你试图读取一个 int 的长度,这是不可能的

    试试这个:

    def F_to_C():
    F=input("enter the F value:")
    if len(F) >3:
        print("input is too long")
    else:
        C=(int(F)-32)*(5/9)
        print("the corresponding celcius value is: ",C)
    

    首先它会检查字符串 F 的长度,然后在计算 C 时将 F 转换为 int。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-04
      • 2021-01-28
      • 2012-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 1970-01-01
      相关资源
      最近更新 更多