【问题标题】:How make this Currency Converter in Python works?Python 中的货币转换器是如何工作的?
【发布时间】:2021-04-29 02:16:38
【问题描述】:

我是 Python 的初学者,但我的代码卡住了... 我必须写一段代码:

  • 向用户询问被视为价值货币的输入 这将被视为欧元

  • 然后计算日元的价值(1 欧元 = 8.09647 日元)

  • 并显示并返回结果这里同时使用“打印”和“返回”函数

  • 包括测试/错误消息/ ...以便在使用程序时指导用户

这是我已经完成的代码,我不明白为什么我不能得到我想要的

def currency_converter():
conversion = float(input('Enter a value in EUR to be converted to YEN:'))
YEN = 8.09647
EUR = EUR * YEN
error_message = 'Error: your input should be a positive number'

if (conversion.isdigit() == False):
    return(error_message)
elif (conversion.isdecimal() == False):
    return (error_message)
else:
    print("Your input is equal to {output} stones".format(output=conversion)) #this line is from the teacher and should stay the same
    return conversion

欢迎任何帮助:)

【问题讨论】:

  • 除了缩进问题,代码本身也有一些问题。此外,您需要call 获取函数executed。它只是一个没有执行的函数定义。

标签: python function if-statement input converters


【解决方案1】:

在您的代码中,EUR 指的是什么?可以看出,输入采用conversion 变量。所以conversion = conversion * YEN需要做。

代码中的另一个问题是缩进,在 Python 中应该严格遵守。

另外,isdecimal()isdigit() 适用于字符串数据类型。

您的代码应如下所示

def currency_converter():
    conversion = input('Enter a value in EUR to be converted to YEN:')
    YEN = 8.09647
    error_message = 'Error: your input should be a positive number'

    if (conversion.isdigit() == False):
        return(error_message)
    elif (conversion.isdecimal() == False):
        return (error_message)
    else:
        conversion = float(conversion) * YEN
        print("Your input is equal to {output} stones".format(output=conversion))
        return conversion

请注意,我以字符串格式输入,首先检查错误消息,然后如果一切正常,则继续计算 YEN 值。在您的代码中,如果输入不是数字,则会在 EUR = EUR * YEN 行引发错误,因为乘法只能在数字上。

【讨论】:

  • 这正是我想要做的!非常感谢,我不知道 float 功能,但现在我明白了它是如何工作的。感谢您的宝贵时间!
【解决方案2】:

将用户输入放入“转换”后,您需要将其乘以 YEN 值,例如:

EUR = conversion * YEN
print("Your input is equal to {output} stones".format(output=EUR))

【讨论】:

    【解决方案3】:

    首先,如果您尝试验证输入的数字,您应该在开始使用float之前进行验证:

    def check_float(potential_float):
        try:
            float(potential_float)#Try to convert argument into a float
            return True
        except ValueError:
           return False
    
    conversion = input('Enter a value in EUR to be converted to YEN:')
    
    if check_float() == False:
        print('It is not number')
        return
    else:
        print("Your input is equal to {output} stones".format(output=conversion))
        return conversion
    

    其次,您应该将conversion 分配给EUR,但最好替换为conversion

    YEN = 8.09647
    conversion= conversion* YEN
    

    【讨论】:

      【解决方案4】:

      如果您想添加连续的要求输入直到它成为一个数字,您可以在此更正代码旁边使用while

      所以input 输入一个string 变量,使用try - except 块您将检查输入是否可以转换为float(因为一串数字可以转换为浮点数,但一串字母不能)。如果输入是一个数字,它将计算结果,打破while 循环并执行打印 - 返回。

      如果输入不是数字,它将显示错误消息并要求输入数字,直到它得到它。

      def currency_converter():
          conversion_rate = 8.09647
          error_message = "Error: your input should be a positive number"
           
          isnotnumber = True
          while isnotnumber:
              try:
                  # checks if the input can be converted to float
                  # input imports string variable even if you input a number
                  # so if it can be changed to float it will calculate YEN
                  # if not, so the input is not number and with while
                  # it will continously ask for a number
                  EUR = float(input("Enter a value in EUR to be converted to YEN: "))
                  YEN = EUR * conversion_rate
                  isnotnumber = False
                  print("Your input is equal to {output} stones".format(output=YEN))
                  return(YEN)
              
              except:
                  print(error_message)
                  EUR = input("Enter a value in EUR to be converted to YEN: ")
      
      currency_converter()
      

      【讨论】:

        【解决方案5】:

        你有几个问题。首先,您需要在使用您使用的方法之前检查您的输入是否可转换,只需在字符串上调用它们即可。然而,更 Pythonic 的做事方式是 EAFTP。因此,只需将其包装在 try/catch 中并捕获 float 函数可能引发的 ValueError。

        那么你需要先分配一个值,然后才能使用它。将变量名称视为存储桶。首先,您需要获取存储桶并为其命名,通常还决定填充它(例如0None 或所需的值)。所以在首先定义EURYEN 之前,你不能做EUR = EUR * YEN(想想,使用乘法运算组合两个桶)。否则,计算机要使用什么值?

        然后你只需乘以你的常数并打印+返回。

        Python 3 (PyPy)

        def currency_converter():
            try:
                EUR = float(input('Enter a value in EUR to be converted to YEN:'))
            except ValueError as e:
                print("\nError: your input should be a number. Error message:", e)
                return float("NaN")
            print()
        
            YEN = 8.09647
        
            conversion = EUR * YEN
            print("Your input is equal to {output} stones".format(output=conversion)) #this line is from the teacher and should stay the same
            return conversion
        

        Try it online!

        编辑:添加了如何检查负数。

        Python 3 (PyPy)

        def currency_converter():
            try:
                EUR = float(input('Enter a value in EUR to be converted to YEN:'))
            except ValueError as e:
                print("\nError: your input should be a number. Error message:", e)
                return float("NaN")
            print()
            if EUR < 0:
                print("EUR must be a positive number!")
                return float("NaN")
        
            YEN = 8.09647
        
            conversion = EUR * YEN
            print("Your input is equal to {output} stones".format(output=conversion)) #this line is from the teacher and should stay the same
            return conversion
        

        Try it online!

        【讨论】:

        • 我试过了,效果很好!非常感谢,解释很清楚,我更好地理解了我的错误。如果输入是负数,我现在如何输入错误消息?我可以再做一个“例外”吗?
        • 不,try/catch 只捕获大多数函数在出现问题时抛出的错误和异常。您可以捕获这些错误,也可以不捕获并让程序捕获。虽然您可以使用负数产生错误。例如通过查看 math.sqrt(EUR) 是否抛出错误,更好的方法是在 try/catch 之后的空打印之后添加:if EUR &lt; 0: print("EUR must be a positive number!"); return float("NaN")
        • 添加了对答案的否定检查。根据您的程序使用货币转换器的方式,您要么必须检查返回值的NaN,要么不这样做;你也可以raise ValueError("Only positive numbers allowed!")你自己;)然后只需将curreny_converter的调用者包装在try/catch中并进行相应处理。
        【解决方案6】:

        这里是更正的代码:-

        def currency_converter(UserInput): #Defining Function
            YEN = 8.09647
            error_message = 'Error: your input should be a positive number'
            
            try: # This will check if input is number, if not then except statement is executed
                EUR = float(UserInput)*YEN #replace float with int if you don't want to accept decimal numbers
                print(f"Your input is equal to {EUR} stones")
            except:
                print(error_message) #this will get printed only if try fails
        
        
        conversion = input('Enter a value in EUR to be converted to YEN:') # taking user input
        currency_converter(conversion) #calling function
        

        【讨论】:

          猜你喜欢
          • 2020-09-01
          • 1970-01-01
          • 2021-07-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多