Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSabeen Azhar
440 PointsWhy is python asking for a colon?
hello, I was wondering why the function is asking to put a colon even thought one is already there.
def math(question):
if question = 1:
answer = num1 + num2
elif question = 2:
answer = num1 - num2
elif question = 3:
answer = num1 * num2
return answer
2 Answers
Chris Freeman
Treehouse Moderator 68,454 PointsHey Sabeen Azhar, good question.
A colon marks the start of an expected indented block. Since eachelif
/else
has its own code block, a colon is needed.
The elif
ended the previous code block by being indented only as far as the previous if
of elif
.
**Edit: are you using Python 3.8+? Python might be thing you mean to use the walrus operator. That is, it might be guessing you mean:
if question := 1:
It helps if you post the complete error stacktrace for context.
Post back if you need more help. Good luck!!
jb30
44,806 PointsThe number of colons you currently have in your function is fine.
In the line if question = 1:
, you get a SyntaxError. You probably meant to use if question == 1:
with two equal signs to check equality. The lines starting with elif
have the same issue.
Your function does not have any parameters named num1
or num2
, so they might not be defined when the function is run. If you want them to be parameters, you could change your first line to def math(question, num1, num2):
.
Chris Freeman
Treehouse Moderator 68,454 PointsIām now wonder if this is a walrus operator error.