【问题标题】:What is wrong with my if-else statements and variable assignments?我的 if-else 语句和变量赋值有什么问题?
【发布时间】:2019-03-06 01:41:29
【问题描述】:

目标: 我试图让用户为某些汽车服务输入不同的拼写,并且仍然让我的代码正常工作。我的目标是使用 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

【问题讨论】:

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


【解决方案1】:

Python 中的运算顺序会在处理or 之前处理==,并且'tirerotation' 始终为True。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多