Fred Fred - 1 month ago 20x
Python Question

IF statement picking first option in currency converter (python)

print "Pound Sterling converter"
print "You can convert pounds to either dollars, euros or yen"


dollar = 0
euro = 0
yen = 0

convert_to = input ("What currency do you want to convert to? ")
amount = input("How much would you like to convert? ")


if convert_to == dollar:
amount = amount * 1.3
elif convert_to == euro:
amount = amount * 1.17
elif convert_to == yen:
amount = amount * 133.66
print "You must pick either dollar, euro or yen."

print amount

I'm a beginner in Python, as you can probably tell. All I want this program to do is have the user choose a currency (convert_to) and then choose how much they want to convert (amount) and then the program will convert it for them.

When I run the program, the if statement does not work correctly. Instead of seeing what convert_to is, it goes through the convert_to == dollar part regardless of if you type euro or yen. The numbers they are being multiplied by are simply the conversion rates from pounds.

also, a side note but less important one, the final else part does not work. The program brings up a "input not defined" error instead of printing "You must pick either dollar, euro or yen."

Thanks in advance


If i understand correctly, the user will input either "0", "1" or "2" as a input, for the convertion for dollar, euro or yen respectively. So you need to change the initial values of dollar, euro and yen. Changing that, the version with integer input will work.

dollar = 0
euro = 1
yen = 2

If the input is a string such as "dollar", "euro" or "yen", the variables need to be changed to these respective strings, so firstly you need to set the variable as:

dollar = "dollar"
euro = "euro"
yen = "yen"

Then change the input type for raw_input, as python requires this type of input to recognize a String input. So change convert_to to:

convert_to = raw_input ("What currency do you want to convert to? ")

If you try to pass a string to a input variable it will always return 0. And since the initial values for all the variable are 0, the if statements returns true when comparing convert_to to dollar , euro or yen. Because the comparsion to the dollar is hapening first, it always goes to that case. These are the changes necessary for the code to run.

Extra: You also don't need the variables in this case, since you're only using them in one field. So on your if statements, you can just compare them to the specific strings, as:

if convert_to == "dollars":
    amount *= 1.3
elif convert_to == "euros":
     amount *=  1.17
elif convert_to == "yen":
    amount *= 133.66
    print "You must pick either dollar, euro or yen." 

Hope it helps.