Reputation: 49
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 :(
Upvotes: 0
Views: 75
Reputation: 1123970
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
Upvotes: 2