Python:使用Try和ValueError问题进行数据验证

时间:2014-12-09 17:21:02

标签: python python-3.x

所以我正在编写一个简单的货币转换程序。我正在尝试验证数据,因此如果您键入错误的数据类型,则会要求您再次键入数据。

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)

这是我在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) 

请帮帮我,我真的很困惑:(

1 个答案:

答案 0 :(得分:2)

你正在测试错误的东西:

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

如果change'y'怎么办?然后第一个测试是错误的,但第二个测试是真的。同样适用于'n';第一次测试是真的,所以整个表达也是如此。事实上,无论你输入什么,表达式总是为真。

您想在此处使用and两者必须为true才能继续循环:

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

您可以使用会员资格测试:

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

您可能想要学习规范性的“请求输入”。有关更多建议的问题请参阅Stack Overflow:Asking the user for input until they give a valid response