【问题标题】:using subroutines in python instead of if statements在 python 中使用子例程而不是 if 语句
【发布时间】:2014-01-15 20:03:56
【问题描述】:

我想知道是否可以在这里使用子例程,如果可以的话,我该怎么做或有另一种方法来缩短这段代码。

    if currency1=='GBP':
        if currency2=='USD':
            number=float(1.64)
        elif currency2=='EUR':
            number=float(1.20552)
        elif currency2=='JPY':
            number=float(171.181)

【问题讨论】:

  • 您还可以通过删除对float 的不必要调用来缩短您的代码。

标签: python if-statement subroutine


【解决方案1】:

你当然可以做一本字典:

currencies = {}
currencies['USD'] = 1.64
currencies['EUR'] = 1.20552
currencies['JPY'] = 171.181
currencies['GBP'] = 1.

number = currencies[currency2]

这样做的好处是你也可以这样做:

other_number = currencies[currency1]
exchange_rate = number / other_number # exchange rate BETWEEN the two currencies

【讨论】:

    【解决方案2】:

    怎么样:

    Brit_converter: {'USD':1.64, 'EUR':1.20552}
    
    if currency1=='GBP':
      multiplier = converter[currency2]
    

    或者,假设这符合我的预期:

    converted_currency = currency1 * converter[currency2]
    

    【讨论】:

      【解决方案3】:

      子例程 - 在 Python 中,接受的术语是 function - 不能替换 if 运算符,原因很简单 - 它们有不同的用途:

      • 函数用于将代码分解为可管理的小单元,并在多个地方整合所需的功能
      • if 运算符更改控制流

      正如上面所指出的,字典是多种固定选择的优秀解决方案之一。

      【讨论】:

      • 子程序不同于函数。函数有自己的作用域,函数中定义的变量不会在调用上下文中定义。
      【解决方案4】:

      我会使用这样的字典*:

      if currency1 == 'GBP':
          number = {'USD':1.64, 'EUR':1.20552, 'JPY':171.181}.get(currency2, 1)
      

      另外,请注意我在这里使用了dict.get。如果在字典中找不到currency2,则number 将被分配给1,并且不会引发KeyError。但是,您可以选择任何您想要的默认值(或完全省略它并使用 None 作为默认值)。

      最后,您应该注意,将浮点字面量放在 float 内置是不必要的。


      *注意:如果您打算在多个地方使用该词典,请不要一直重新创建它。相反,将其保存在如下变量中:

      my_dict = {'USD':1.64, 'EUR':1.20552, 'JPY':171.181}
      if currency1 == 'GBP':
          number = my_dict.get(currency2, 1)
      

      【讨论】:

      • 可能希望默认值为1而不是0,所以当转换乘以时,它只是保持不变。
      猜你喜欢
      • 1970-01-01
      • 2015-10-24
      • 1970-01-01
      • 2010-09-15
      • 2017-09-27
      • 1970-01-01
      • 1970-01-01
      • 2020-09-25
      • 1970-01-01
      相关资源
      最近更新 更多