Python Arena
Step 2 of 4

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")
Output
The program runs, though save_report does nothing yet

A 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")
Python stops with
  File "main.py", line 4
    print("Done")
    ^^^^^
IndentationError: expected an indented block after function definition on line 1

pass 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])
Output
First negative: -2
No negative numbers

Without 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")
Output
No negative numbers
No negative numbers
No negative numbers

Your task

Challenge 1 of 3

What does this program print? Type each line it prints.

Challenge 2

The program should add up the numbers in a line of comma-separated values and skip anything that isn't a number. The except block is meant to do nothing, but it's empty, so Python can't even read the program. Fix it, so that it prints, for example:

Values: 12,x,30,,8
Total: 50

Challenge 3

Write a program that asks for a PIN code at most three times. The right PIN is 4321. For a right one it prints Welcome! and stops asking; for a wrong one, Wrong PIN. After three wrong tries it prints Card locked. Use a loop with an else block for the last message. For example:

PIN: 1111
Wrong PIN
PIN: 4321
Welcome!