How do you turn a plain English sentence into a working def — and why can the whole if/else collapse into a single returned Boolean?
Short drills on what this video just taught. Write the code, run the checks, and reveal the answer only if you are stuck.
Here is the English task: "Given a whole number, tell me whether it is even." Turn it into a function named is_even with a single parameter that returns True when the number is even and False otherwise. A short docstring is filled in for you.
Hint: % gives the remainder after division, and == tests equality and produces a Boolean.
The def header line and its indentation
Write out def is_even(i): and mark which pieces vary — the name and the comma-separated parameters — and that the closing colon forces the block below it to be indented.
The docstring and body of is_even
Copy a triple-quoted specification saying i is a positive integer and the result is True for even and False otherwise, then the if/else body with its two return statements.
Five-step process from English to code
List the steps in order: state the problem, pick an action name, pick the inputs, fill in the docstring, then solve the problem and return a value.
Collapsing the if/else into one return
Put the four-line version beside return i % 2 == 0 and record that the comparison i % 2 == 0 is itself already True or False.