Python 中的货币转换器如何工作?

How make this Currency Converter in Python works?

我是 Python 的初学者,我被困在我的代码中... 我必须写一个代码:

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

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

欢迎任何帮助:)

这是更正后的代码:-

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

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

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

在您的代码中,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:

之前
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

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

那你需要赋值才可以使用。将变量名视为桶。首先你需要抓住桶并给它起个名字,通常还要决定填充它(例如 0None 或所需的值)。所以在先定义 EURYEN 之前,你不能做 EUR = EUR * YEN(想一想,使用乘法运算组合两个桶)。否则,计算机使用什么值?

然后你只需要乘以你的常量然后打印+return.

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!

如果你想添加连续的输入请求,直到它是一个数字,你可以使用 while 和这个更正的代码。

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

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

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()