【问题标题】:Python - Convert prefixes (kilo etc) to base numberPython - 将前缀(千等)转换为基数
【发布时间】:2020-04-13 11:31:50
【问题描述】:

我有以 k 结尾的数字,意思是 e^3。我写了一个函数来尝试解决这个问题:

def prefixFinder(in1, out1):

if in1.endswith('k'):
    in1 = in1[:-1]              # Remove k from the end
    out1 = float(in1) * 1000    # Multiply by 100

    print(out1)

    return out1                 # Return out1

当我用x调用函数时(想用10000.0替换x的当前值,'10k'

x = '10k'

prefixFinder(x, x)

print(x)

我得到的输出是'10k'。但是函数中的print(out1)10000.0 是正确的。

我不确定我做错了什么,非常感谢任何帮助

【问题讨论】:

  • 如果分配x = prefixFinder(x, x)会怎样?

标签: python python-3.x function loops


【解决方案1】:

Python 中不存在 C 或 C# 中的输出参数,您必须返回它:

def prefixFinder(i):

    if in1.endswith('k'):
        i = i[:-1]               # Remove k from the end
        return float(i) * 1000   # Multiply by 100 

然后像这样使用它:

x = '10k'
x = prefixFinder(x)
print(x)

【讨论】:

    【解决方案2】:

    您只需要输入(x='10k') 即可生成函数并返回结果。

    def prefixFinder(x):
    
        if x.endswith('k'):
            x = x[:-1]               
            return float(x) * 1000        
    
    y = '10k'
    y = prefixFinder(y)
    print(y)
    

    在这种情况下,结果将是:

    10000.0

    您还可以将返回值分配给变量:

    def prefixFinder(x):
    
        if x.endswith('k'):
            x = x[:-1]
            out = float(x) * 1000               
            return  out     
    
    y = '10k'
    y = prefixFinder(y)
    print(y)
    

    【讨论】:

      【解决方案3】:

      您不需要将out1 参数传递给您的函数。做吧:

      def prefixFinder(in1):
          if in1.endswith('k'):
              in1 = in1[:-1]              # Remove k from the end
              out = float(in1) * 1000    # Multiply by 100
              print(out)
              return out 
      x = "10k"
      x = prefixFinder(x)
      print(x)   
      

      【讨论】:

        猜你喜欢
        • 2021-10-30
        • 2012-07-05
        • 2020-04-04
        • 1970-01-01
        • 1970-01-01
        • 2013-11-08
        • 2013-04-02
        • 2016-05-27
        • 2016-01-13
        相关资源
        最近更新 更多