首页 > 解决方案 > IF 语句只响应最近的 if 语句的结果

问题描述

我将尽力解释这一点。我的任务是根据日期、持续时间和通话开始时间制作付费电话价格计算器。我做了两个 if 语句,并意识到每当我输入我的答案时,它所做的只是从最新的 if 语句中打印结果,并没有真正听我想要它做什么。这有点难以解释,所以我将只输入我的代码、我的输入和我的结果。

代码:

day = str(input('Enter the day the call started at: '))
start_time = float(input('Enter the time the call started at (hhmm): '))
duration = float(input('Enter the duration of the call (in minutes):'))
cost = duration

    if (start_time >= 08.00 and start_time <= 18.00 and day == "Mon" or "Tue" or "Wed" or "Thr" or "Fri"):
        cost = duration * 0.40
    
    if (start_time < 08.00 and start_time > 18.00 and day == "Mon" or "Tue" or "Wed" or "Thr" or "Fri"):
        cost = duration * 0.25
    
    print('$' + str(cost))

我的输入:

1: Fri, 2350, 22.  2: Sund, 2350, 22.

我的结果:

1: $5.5.  2: $5.5.

如您所见,它甚至没有执行 print 语句中的内容。它只是给了我上一个 if 语句的结果。我还尝试删除“and day ==”,之后所做的就是使第一个打印语句正常工作,而第二个不工作它只是打印我原来的持续时间,所以我认为我搞砸了。

标签: pythonpython-3.xif-statement

解决方案


当您尝试使用逻辑运算符连接多个条件时,您必须分别比较每个字符串。我的意思是它需要是这样的

day == "Mon" or day == "Tue" or day == "Wed"

等等...


推荐阅读