0

So I'm writing a program which is a simple currency converter. I'm trying to validate the data so if you type in the wrong data type you are asked to type it again.

GBP_USD = 1.57
print('The current exchange rate is',GBP_USD)
change = input('Would you like to change this?(Y/N) ')
if change.lower() == 'y':
    GBP_USD = input('New Rate: ')
    while True:
        try:
            float(GBP_USD)
            break
        except ValueError:
            print('That is not valid.')
            GBP_USD = input('New Rate: ')
            continue
while (change.lower() != 'y') or (change.lower() != 'n'):
    print('Please enter Y or N.')
    change = input('Would you like to change this?(Y/N) ')
    if change.lower() == 'y':
        GBP_USD = float(input('New Rate: '))
        break       
money = float(input('Money: '))
exchange = money * GBP_USD
rounded = ceil(exchange * 100) / 100.00
print('Dollars:',rounded)

This is what I get in the shell

The current exchange rate is 1.57
Would you like to change this?(Y/N) y
New Rate: three
That is not valid.
New Rate: 4
Please enter Y or N.
Would you like to change this?(Y/N) n
Please enter Y or N.
Would you like to change this?(Y/N) n
Please enter Y or N.
Would you like to change this?(Y/N) n
Please enter Y or N.
Would you like to change this?(Y/N) n
Please enter Y or N.
Would you like to change this?(Y/N) y
New Rate: 6
Money: 4
Dollars: 24.0
Would you like to quit?(Y/N) 

Please help me I'm really confused :(

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
person101
  • 51
  • 1
  • 8

1 Answers1

2

You are testing the wrong thing:

while (change.lower() != 'y') or (change.lower() != 'n'):

What if change is 'y'? Then the first test is false, but the second is true. The same goes for 'n'; the first test will be true, so the whole expression is true too. In fact, the expression is always true, no matter what you enter.

You want to use and here instead, both must be true for you to continue with the loop:

while (change.lower() != 'y') and (change.lower() != 'n'):

You could use a membership test instead:

while change.lower() not in 'ny':

You may want to study the canonical 'ask for input' question here on Stack Overflow for some more advice: Asking the user for input until they give a valid response

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thank You very much for this. I did not realize that not in existed. After a quick google I now understand this and have applied it to some other areas of my code. – person101 Dec 09 '14 at 22:10