英文:
My python 'if' statement is causing a syntax error
问题
I'll provide the translated code without the code-related parts:
抱歉,我知道这些问题很常见,但我在任何快速文章中都找不到答案。
我的代码开始一个while True循环,然后是一个输入,接着是一个if语句,一个elif,然后是一个else。if和elif语句都在完成后跳出循环,而else会要求你再次输入,直到满足其中之一。
sleep(1)
print("午餐是在12:00pm之前还是之后开始的?")
while True:
lunch_time = input()
if lunch_time == "before" or lunch_time == "Before":
avgrams *= 0.98
STDEV *= 0.98
break
elif lunch_time == "after" or lunch_time == "After":
break
else:
sleep(1)
print("抱歉,我不明白。")
sleep(1)
print("请只用'before'或'after'来回答(不带标点符号)。")
你的代码的中文翻译已提供。
英文:
Sorry, I know these are common but I couldn't find any answers on any quick articles.
My code starts a while True loop, followed by an input and then an if statement, an elif and then an else. The if and elif statements both break out of the loop once completed, and the else makes you input again until you fulfill one of the other two.
sleep(1)
print("Did lunch start before or after 12:00pm?")
while True:
lunch_time = input()
if lunch_time == "before" or if lunch_time == "Before":
avgrams*=0.98
STDEV*=0.98
break
elif lunch_time == "after" or if lunch_time == "After":
break
else:
sleep(1)
print("Sorry, I don't understand.")
sleep(1)
print("Please only answer with 'before' or 'after' (with no punctuation).")
I started my code, when I got to this part (the first line here is line 84) I was expecting to answer something random to make sure the else statement worked, then answer one of the other two to break out of the loop and continue. However upon running my code this if statement causes a syntax error, with invalid syntax.
File "main.py", line 88
if lunch_time == "before" or if lunch_time == "Before":
^
SyntaxError: invalid syntax
答案1
得分: 2
在使用逻辑运算符时,在if
块内,您无需在输入逻辑运算符(and
,or
,not
)后再声明if
。您的程序失败是因为您在if
语句内再次包含了if
语句。
另一个问题是,在您的elif
语句内又有另一个if
语句。如果包括elif
,顺序应始终为if->elif->else
。如果有任何进一步的问题,请告诉我!
祝好!
英文:
When using your logical operators within an if
block, you do not need to declare if
again after you type the logical operator (and
, or
, not
). Your program is failing because you are including the if
statement once more within your if statement.
Another problem that is that you have another if-statement within your elif
statement. The order, if including an elif
, should always be if->elif->else
. Please let me know if you have any further questions!
Cheers.
答案2
得分: 1
你可以将Python中的if-elif-else理解为这样:
if <条件> 或者/和 <条件> . . .:
# 代码
elif <条件> 或者/和 <条件> . . .:
# 代码
else:
# 代码
英文:
You can think if-elif-else in python like this.
if <condition> or/and <condition> . . .:
# code
elif <condition> or/and <condition> . . .:
# code
else:
#code
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论