我的if-else语句和变量分配有什么问题?

时间:2018-09-30 22:43:22

标签: python-3.x if-statement input variable-assignment

目标: 我试图允许用户为某些自动服务输入不同的拼写,但仍使我的代码正常工作。我的目标是使用if-else语句来确保如果用户拼错了服务,则代码可以通过将变量分配更改为与我的字典键匹配的字符串来纠正错误。

问题: 代码将输出:我为auto_serv输入的任何输入的轮胎旋转。我在哪里弄错了?有更好的想法对此编程吗?请记住,我是第一次在课堂上这样做的程序员,而且我刚刚学习了if-else语句。

代码:

# dictionary assigns the cost for each service
services = {'Oil change': 35,
            'Tire rotation': 19,
            'Car wash': 7,
            'Car wax': 12}
# auto_serv is the user's desired car service
auto_serv = input('Desired auto service:')
# The following four 'if' statements are to allow the user multiple variances in spelling of desired auto service
if auto_serv == 'Tirertation' or 'tirerotation':

    auto_serv = 'Tire rotation'
elif auto_serv == 'Oilchange' or 'oilchange':

    auto_serv = 'Oil change'
elif auto_serv == 'Carwash' or 'carwash':

    auto_serv = 'Car wash'
elif auto_serv == 'Carwax' or 'carwax':

    auto_serv = 'Car wax'

# the if-else statements are to give a result for each service the user requests
if auto_serv == 'Tire rotation':

    print('You entered:', auto_serv)

    print('Cost of %s: $%d' % (auto_serv, services[auto_serv]))
elif auto_serv == 'Oil change':

    print('You entered:', auto_serv)

    print('Cost of %s: $%d' % (auto_serv, services[auto_serv]))
# ...there are more elif statements that follow this code with the other auto services

1 个答案:

答案 0 :(得分:0)

Python中的操作顺序将在==之前处理or,并且'tirerotation'始终为True。

请改用in运算符,例如::

if auto_serv in ['Tirertation', 'tirerotation']: