I have a quick question regarding the syntax of an if statement.
This is in regards to the solution in code challenge 1 in advanced control flow.
def in_range(num, lower, upper):
if(num >= lower and num <= upper):
Can we have an if statement without an else clause? If so why doesn’t it violate the rules of Python?
Yes, you can have a if statement without an else. Python uses spacing or indention to separate the if statement from other parts of the code. I assume the “return True” line is actually indented in your code and the “return False” line is on the same indention level as the if statement. I also assume the if statement is indented from your def (function) line. The if statement only needs to return a true or false, if the statement is true, then it completes the lines of indented code under the if statement otherwise, it skips all of the indentation and continues with the next line of code, equal to the indentation level of the if statement.
Hope that helps.