【问题标题】:How to accept the input of both int and float types?如何接受 int 和 float 类型的输入?
【发布时间】:2017-04-22 20:13:10
【问题描述】:

我正在做一个货币转换器。如何让 python 同时接受整数和浮点数?

我就是这样做的:

def aud_brl(amount,From,to):
    ER = 0.42108
    if amount == int:
        if From.strip() == 'aud' and to.strip() == 'brl':
            ab = int(amount)/ER
         print(ab)
        elif From.strip() == 'brl' and to.strip() == 'aud':
            ba = int(amount)*ER
         print(ba)
    if amount == float:
        if From.strip() == 'aud' and to.strip() == 'brl':
            ab = float(amount)/ER
         print(ab)
        elif From.strip() == 'brl' and to.strip() == 'aud':
            ba = float(amount)*ER
         print(ba)

def question():
    amount = input("Amount: ")
    From = input("From: ")
    to = input("To: ")

    if From == 'aud' or 'brl' and to == 'aud' or 'brl':
        aud_brl(amount,From,to)

question()

我如何做到的简单示例:

number = input("Enter a number: ")

if number == int:
    print("integer")
if number == float:
    print("float")

这两个不起作用。

【问题讨论】:

  • 我把你的标题和标题改成了小写。请不要对我们大喊大叫:)
  • if type(number) is int 但这永远是错误的,因为number 永远是一个字符串。
  • @juanpa.arrivillaga 不,不是。他使用input 读取用户,type(numer)str
  • 您知道,if From == 'aud' or 'brl' and to == 'aud' or 'brl' 行将始终计算为True,因为'brl' 在这两种情况下都是真实的。如果您想查看From'aud' 还是'brl',您需要这样的东西:if From == 'aud' or From == 'brl' ...

标签: python python-3.x integer


【解决方案1】:

我真的希望我没有完全误解这个问题,但我开始了。

看起来你只是想确保传入的值可以像浮点数一样被操作,不管输入是3还是4.79,对吗?如果是这种情况,那么只需将输入转换为浮点数,然后再对其进行操作。这是您修改后的代码:

def aud_brl(amount, From, to):
    ER = 0.42108 
    if From.strip() == 'aud' and to.strip() == 'brl': 
        result = amount/ER 
    elif From.strip() == 'brl' and to.strip() == 'aud': 
        result = amount*ER 

    print(result)

def question(): 
    amount = float(input("Amount: "))
    From = input("From: ") 
    to = input("To: ")

    if (From == 'aud' or From == 'brl') and (to == 'aud' or to == 'brl'): 
        aud_brl(amount, From, to)

question()

(为了整洁,我也做了一些改动,希望你不要介意

【讨论】:

    【解决方案2】:

    这是您检查给定字符串并接受intfloat 的方法(也可以转换为它;nb 将是intfloat):

    number = input("Enter a number: ")
    
    nb = None
    for cast in (int, float):
        try:
            nb = cast(number)
            print(cast)
            break
        except ValueError:
            pass
    

    但在您的情况下,仅使用浮点数可能会解决问题(整数的字符串表示形式也可以转换为浮点数:float('3') -> 3.0):

    number = input("Enter a number: ")
    
    nb = None
    try:
        nb = float(number)
    except ValueError:
        pass
    

    如果nbNone,则您得到的内容无法转换为float

    【讨论】:

    • 为什么其他人会说,“当然,这里真正的 Pythonic 解决方案是鸭子输入并在传递非 int/float 时捕获错误!”?你能解释一下吗?我是编程新手。
    • 这与鸭式打字无关。我只是尝试以永远不会崩溃的方式将字符串转换为浮点数。 python 哲学之一是EAFP,而不是LBYL。所以 python 编码人员通常会try 一些东西,而不是先检查一些东西。 (例如,如果您想将 str 转换为 int 您可以先检查字符串是否仅包含数字;这不是 Python 的事情)。
    【解决方案3】:

    使用内置的isinstance函数

    if isinstance(num, (int, float)):
        #do stuff
    

    此外,您应该避免使用保留关键字作为变量名。关键字from是Python中的保留关键字

    最后,我注意到另一个错误:

    if From == 'aud' or 'brl'
    

    应该是

    if From == 'aud' or From == 'brl'
    

    最后,为了清理 if 语句,理论上您可以使用列表(如果您将来有更多货币,这可能会更好。

    currencies = ['aud', 'brl']     #other currencies possible
    if From in currencies and to in currencies:
        #do conversion
    

    【讨论】:

    • isinstance(num, (int, float)) 可以直接完成...而且看起来 OPs 输入以字符串开头。
    • @hiroprotagonist 当然,这里真正的 Pythonic 解决方案是鸭式输入并在传递非 int/float 时捕获错误!
    • 如果 if 语句中没有指定货币,我该如何转换?
    • @KGarcia 您将不得不为此大幅重组您的代码,这超出了本评论的范围,但如果您计划转换多种货币,那么您的功能布局方式效率很低
    【解决方案4】:

    amount==int 没有意义。 input 给了我们一个字符串。 int(和float)是一个函数。字符串永远不等于函数。

    In [42]: x=input('test')
    test12.23
    In [43]: x
    Out[43]: '12.23'
    In [44]: int(x)
    ....
    ValueError: invalid literal for int() with base 10: '12.23'
    In [45]: float(x)
    Out[45]: 12.23
    

    float('12.23') 返回一个float 对象。 int('12.23') 产生错误,因为它不是有效的整数字符串格式。

    如果用户可能给出“12”或“12.23”,使用float(x) 将其转换为数字会更安全。结果将是一个浮点数。对于许多计算,您无需担心它是浮点数还是整数。数学是一样的。

    如果需要,您可以在 int 和 float 之间进行转换:

    In [45]: float(x)
    Out[45]: 12.23
    In [46]: float(12)
    Out[46]: 12.0
    In [47]: int(12.23)
    Out[47]: 12
    In [48]: round(12.23)
    Out[48]: 12
    

    你也可以做instance测试

    In [51]: isinstance(12,float)
    Out[51]: False
    In [52]: isinstance(12.23,float)
    Out[52]: True
    In [53]: isinstance(12.23,int)
    Out[53]: False
    In [54]: isinstance(12,int)
    Out[54]: True
    

    但你可能不需要做任何这些。

    【讨论】:

      【解决方案5】:

      这些似乎运作良好。

      定义 getInt(): """ 输入返回一个str, 强制返回所需类型 """ x = str() 而类型(x)!= int: 尝试: return int(input('输入一个整数:')) 除了 ValueError:继续

      def getFloat(): """ 输入返回一个str, 强制返回所需类型 """ x = str() 而类型(x)!=浮动: 尝试: return float(input('输入一个浮点数:')) 除了 ValueError:继续

      【讨论】:

      • 写/分享代码时请使用代码块。
      • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 2016-08-27
      • 2020-07-28
      • 1970-01-01
      • 2019-03-21
      • 2014-05-25
      • 2019-02-24
      • 2017-02-25
      • 2018-11-28
      • 1970-01-01
      相关资源
      最近更新 更多