pass, and loops with else
pass
You know pass from the starter code of function tasks: it's a statement that does nothing. It exists because a block can't be empty: after if, for, while, def or except, Python wants at least one indented line. When a block should do nothing, at least for now, pass fills the place:
def save_report(data):
pass # to do: write the report to a file
save_report([1, 2, 3])
print("The program runs, though save_report does nothing yet")
The program runs, though save_report does nothing yetA function whose body is only pass returns None. Leave the pass out, and Python can't read the program, even with a comment in the block, because Python skips comments:
def save_report(data):
# to do: write the report to a file
print("Done")
File "main.py", line 4
print("Done")
^^^^^
IndentationError: expected an indented block after function definition on line 1pass is also how you ignore an error on purpose: except ValueError: followed by an indented pass catches the error and does nothing about it.
Loops with else
A for or while loop can have an else block. It runs when the loop ends normally, after its last round, but not when break ends the loop. That fits searching: if the search found nothing, the loop never hit break:
def first_negative(numbers):
for number in numbers:
if number < 0:
print("First negative:", number)
break
else:
print("No negative numbers")
first_negative([4, -2, 7, -9])
first_negative([1, 2, 3])
First negative: -2
No negative numbersWithout the else, the usual way is a helper variable such as found = False, set to True before the break and checked after the loop. The else block does the same with fewer lines.
Watch the indentation
The loop's else is lined up with for, not with if. Indent it one level deeper and it becomes an ordinary else of the if, which runs for every number that isn't negative:
for number in [4, 7, 9]:
if number < 0:
print("First negative:", number)
break
else:
print("No negative numbers")
No negative numbers
No negative numbers
No negative numbers