简体   繁体   中英

How make this Currency Converter in Python works?

I'm a beginner in Python and I'm stuck on my code... I must write a code which:

  • Asks from the user an input considered as value money This one will be considered to be in EUR

  • Then calculates the value in YEN (1 EUR = 8.09647 YEN)

  • And displays and returns the result Here use both "print" and "return" functions

  • include tests / error messages /... in order to guide the user when using the program

Here is the code I've already done and I don't understand why I can't get what i want

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

Any help will be welcome:)

After you put the user input into "conversion" you need to multiply it by the YEN value for example:

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

In your code, what is referred to by EUR ? As can be seen, the input is taken in a conversion variable. So conversion = conversion * YEN needs to be done.

Another problem in your code is of indentation, which should be strictly followed in Python.

Also, isdecimal() and isdigit() works on string data type.

Your code should look like this

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

Note that I took the input in string format, checked for error messages first, and then if everything was fine, went forward to calculate the YEN value. In your code, if the input is not digit, then an error will be raised at line EUR = EUR * YEN because multiplication can be on digits only.

Firstly, if you try to validate entered number you should do it at the beginning, before using 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

Secondary, you should assign conversion to EUR , but better replace with conversion :

YEN = 8.09647
conversion= conversion* YEN

You had a couple of issues. First, you need to check if your input is convertible before you do, using the methods you used, just call them on a string. However, the more pythonic way to do things is EAFTP . So just wrap it in a try/catch and catch the ValueError the float function may raise.

Then you need to assign a value before you can use it. Think of variable names as buckets. First you need to grab the bucket and give it a name, usually also decide to fill it(eg 0 or None or a desired value). So you cannot do EUR = EUR * YEN (think, combine both buckets using the multiply operation) before defining EUR and YEN first. Otherwise, what values is the computer to use?

Then you just multiply by your constant and print+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!

EDIT: Added how to check for a negative number.

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!

if you want to add continuous asking for input until it is a number you can use while alongside this corrected code.

So the input inputs a string variable, with try - except block you will check if the input can be converted to float (as a string of numbers can be converted to float, but a string of letters cannot). If the input is a number it will calculate the result, break the while loop and do the print - return.

If the input is not a number it will show the error message and ask for a number until it gets it.

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

Here is corrected code:-

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM