Can else ever check a condition?


#1

Question

Can else ever check a condition?

Answer

Nope! Think of else as the code you want to happen if everything checked before it failed to enter. If you try putting a condition for an else to check, it will give you a somewhat unhelpful error message like this: SyntaxError: invalid syntax. But! It will point to the line where the issue is, and it’s up to you to know that you cannot write a condition for else to check.


FAQ: Learn Python - Conditionals & Control Flow - Else Problems, I Feel Bad for You, Son
#2

I seem to understand the practical part of the code. As you mentioned

"Think of else as the code you want to happen if everything checked before it failed to enter."I do what I seem that I can’t comprehend is the actual functionality of the code.
how would

answer = “'Tis but a scratch!”

def black_knight():
if answer == “'Tis but a scratch!”:
return True
else:
return # Make sure this returns False

def french_soldier():
if answer == “Go away, or I shall taunt you a second time!”:
return True
else:
return # Make sure this returns False
be used as a part of a scene or answer selection. I definitely understand whats begin defined.

I’m definitely looking at it through a macrocosm way look rather than a microcosmic way, and uncertain whether this is beneficial or not.


#3

If not ‘night’ then ‘day’…

>>> night = False
>>> is_day = not night
>>> print (is_day)
True
>>> 

#4

else, by itself, cannot test for a condition. However you can use an else / if combination to ‘nest’ as many conditions as you wish, e.g.
if condition is true:
return True
else:
if new condition is true:
return Tue
else:
if …


#5

for some reason, the above example did not recognize my spacing for indentations. Each new ‘if’ statement has to begin an additional indentation.


#6

Python and other languages have elif (Python) or elsif (Ruby) or elseif (PHP), etc. to prevent excessive nesting and indentation. When if statements get too complex, the indication is there that clearly the logic needs to be streamlined.


#7

Wrap code blocks in three backticks.

```python
code block here
```