首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python中的温度单位转换器

Python中的温度单位转换器
EN

Code Review用户
提问于 2020-07-13 16:58:35
回答 1查看 476关注 0票数 8

我开始学习python,这是我的第一个项目,但我并不完全高兴,我认为它可以做得更好。你能帮我一下吗?这些字符串是西班牙语的,但我认为这不会损害理解。

代码语言:javascript
复制
    elegir_magnitud = int(input(
"""1 = Temperatura
2 = Longitud 
3 = Masa
4 = Volumen
5 = Tiempo
6 = Divisa
Entra número deseado: """))
if elegir_magnitud == 1 :
    unidad_temperatura = int(input(
        """         

------------------Elige la unidad de temperatura a ser convertida:---------------
1 = Celsius
2 = Farhengei o como se escriba
3 = Kelvin
Entra número deseado: """))
    cantidad_temperatura = float(input(
        """

Entra la cántidad de esa unidad deseada: """))
#ELEGIR UNIDAD DE TEMPERATURA A CONVERTIR
    unidad_a_convertir = int(input(
        """         

--------------------Elige la unidad de temperatura a convertir:-----------------
1 = Celsius
2 = Farhengei o como se escriba
3 = Kelvin
Entra número deseado: """))
    if unidad_temperatura == unidad_a_convertir:
        print("Por qué quieres convertir a la misma unidad?")
    if unidad_temperatura == 1 and unidad_a_convertir == 3:
        print("""El resultado de la conversion es: \n""",float(cantidad_temperatura - 273),"ºK")
    if unidad_temperatura == 1 and unidad_a_convertir == 2:
        print("""El resultado de la conversion es: \n""",float(cantidad_temperatura * 9%5 +32),"ºF")
    if unidad_temperatura == 3 and unidad_a_convertir == 1:
        print("""El resultado de la conversion es: \n""",float(cantidad_temperatura + 273),"ºC")
    if unidad_temperatura == 3 and unidad_a_convertir == 2:
        print("""El resultado de la conversion es: \n""",float((cantidad_temperatura -273) * 9 % 5 + 32),"ºF")
    if unidad_temperatura == 2 and unidad_a_convertir == 3:
        print("""El resultado de la conversion es: \n""",float((cantidad_temperatura - 32) % 9 * 5 - 273),"ºK")
    if unidad_temperatura == 2 and unidad_a_convertir == 1:
        print("""El resultado de la conversion es: \n""",float(cantidad_temperatura % 9*5 -32),"ºC")
EN

回答 1

Code Review用户

回答已采纳

发布于 2020-07-13 17:54:51

本地化

这些字符串是西班牙语的。

太棒了!然而,这并不是西班牙语中唯一的东西:变量(elegir_magnitudunidad_temperatura等)也一样。

这是不理想的,至少有几个原因:

  • Python作为一种语言,其语法是用英语编写的,它与您的代码相冲突,而代码则是英语和西班牙语的混合体。这是不一致的。
  • 不管是好是坏,软件开发的实际语言是英语.特别是对于国际合作或在线开源开发,使用一种更多人可以访问的语言是很重要的。

将国际化(i18n)应用于您的字符串是一件很棒的事情,但它应该只适用于您的字符串,而不是代码。

分解出公共代码

考虑将代码重构为:

  • 只有一个请求单位的方法,调用两次(一次用于源单元,一次用于目标单元)。
  • 做一个系数偏移对的元组。这些代表从给定的单位到开尔文和后面的线性函数。这将只需要两个单位转换公式,而不是(最坏的情况) 2^n与当前的策略。

Bug?

你确定这样能行吗?

代码语言:javascript
复制
cantidad_temperatura % 9*5 -32

我怀疑模数在这里是正确的。你应该使用组织/

示例代码

备注:

  • 这是一个粗略的i18n,有一些来自谷歌翻译的字符串(所以我为可能糟糕的西班牙语道歉)。
  • 只有英文和西班牙文才能实现,但可以增加任何其他语文。
  • 这假定您的操作系统设置为正确的区域设置。
  • 为此,只考虑没有国家代码的ISO639 639-1语言。
  • Enum用于更严格的类型保证。
  • 类型提示用于更好的静态分析和文档。
  • 我没有费心增加输入验证的复杂性,所以如果输入无效,就会引发异常。
  • 注意locale方法的使用,而不是直接使用intfloat构造和格式化。

strings.py

代码语言:javascript
复制
from locale import getlocale, getdefaultlocale


# For testing only
# from locale import setlocale, LC_ALL
# setlocale(LC_ALL, 'es_ES.UTF8')


def get_lang() -> str:
    lang, _ = getlocale()
    def_lang, _ = getdefaultlocale()
    return (lang or def_lang)[:2]


LANG = get_lang()

if LANG == 'en':
    DIMENSIONS = (
      'Temperature',
      'Length',
      'Mass',
      'Volume',
      'Time',
      'Currency',
    )
    TEMP_UNITS = (
      'Kelvin',
      'Celsius',
      'Fahrenheit',
    )
    ENTER_NUMBER = 'Enter the desired number: '
    CHOOSE_TEMP_SOURCE = 'Choose the source temperature unit to convert: '
    CHOOSE_TEMP_DEST = 'Choose the destination temperature unit to convert: '
    PROVIDE_TEMP = 'Provide the source temperature: '
    RESULT = 'The result of the conversion is:'

elif LANG == 'es':
    DIMENSIONS = (
      'Temperatura',
      'Longitud',
      'Masa',
      'Volumen',
      'Tiempo',
      'Divisa'
    )
    TEMP_UNITS = (
      'Kelvin',
      'Centígrada',
      'Fahrenheit'
    )
    ENTER_NUMBER = 'Entra número deseado: '
    CHOOSE_TEMP_SOURCE = 'Elija la unidad de temperatura fuente para convertir: '
    CHOOSE_TEMP_DEST = 'Elija la unidad de temperatura de destino para convertir: '
    PROVIDE_TEMP = 'Proporcionar la temperatura de la fuente: '
    RESULT = 'El resultado de la conversión es:'

convert.py

代码语言:javascript
复制
from enum import Enum
from locale import format_string, atof, atoi
from typing import TypeVar, Type, Iterable

from strings import *


class Dimension(Enum):
    TEMPERATURE = 1
    LONGITUDE = 2
    MASS = 3
    VOLUME = 4
    TIME = 5
    CURRENCY = 6


class TempUnit(Enum):
    KELVIN = 1
    CELSIUS = 2
    FAHRENHEIT = 3


# To get from this unit to Kelvin:
# kelvin = m * this_unit + b
TEMP_PARAMETERS = {
    # This unit       m  b
    TempUnit.KELVIN: (1, 0),
    TempUnit.CELSIUS: (1, 273.16),
    TempUnit.FAHRENHEIT: (5/9, 273.16 - 5/9*32),
}


InputEnum = TypeVar('InputEnum', bound=Enum)


def enum_from_input(t_enum: Type[InputEnum], labels: Iterable[str]) -> InputEnum:
    print(
        '\n'.join(
            format_string('%d = %s', (enum.value, label))
            for enum, label in zip(t_enum, labels)
        )
    )
    result = t_enum(atoi(input(ENTER_NUMBER)))
    print()
    return result


def main():
    dimension = enum_from_input(Dimension, DIMENSIONS)
    if dimension != Dimension.TEMPERATURE:
        raise NotImplementedError()

    print(CHOOSE_TEMP_SOURCE)
    source = enum_from_input(TempUnit, TEMP_UNITS)
    print(CHOOSE_TEMP_DEST)
    dest = enum_from_input(TempUnit, TEMP_UNITS)

    temp1 = atof(input(PROVIDE_TEMP))

    # Use a simple linear transformation where y = mx + b; first convert to
    # the base unit (Kelvin)
    m, b = TEMP_PARAMETERS[source]
    kelvin = m*temp1 + b

    # Now calculate inverse to the destination unit
    m, b = TEMP_PARAMETERS[dest]
    temp2 = (kelvin - b)/m

    print(format_string('%s %.1f', (RESULT, temp2)))


if __name__ == '__main__':
    main()

示例输出

代码语言:javascript
复制
1 = Temperatura
2 = Longitud
3 = Masa
4 = Volumen
5 = Tiempo
6 = Divisa
Entra número deseado: 1

Elija la unidad de temperatura fuente para convertir: 
1 = Kelvin
2 = Centígrada
3 = Fahrenheit
Entra número deseado: 3

Elija la unidad de temperatura de destino para convertir: 
1 = Kelvin
2 = Centígrada
3 = Fahrenheit
Entra número deseado: 2

Proporcionar la temperatura de la fuente: 81
El resultado de la conversión es: 27,2
票数 12
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/245418

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档