Practice by topic / Python & code / Python

Python Functions Exercises

Python is the most popular language for automating work: cleaning data, renaming files, crunching numbers. Each exercise runs your real code in the browser and checks it. These 5 exercises build up step by step, starting with define a function, apply a discount, default values.

3 of 5 free · no sign-up needed · instant feedback

1

Define a Function

Free

Write a function <code>add(a, b)</code> that returns the sum of its two inputs.

Show the solution

def add(a, b): return a + b

Right — return sends the answer back so other code can use it.

Try it in the live editor →
2

Apply a Discount

Free

Write <code>discounted(price, percent)</code> that returns the price after a percent discount, rounded to 2 decimal places.

Show the solution

return round(price * (1 - percent / 100), 2)

Good — one function, every price. That's why functions beat copy-pasting formulas.

Try it in the live editor →
3

Default Values

Free

Write <code>with_tax(amount, rate=0.09)</code> that returns the amount plus tax. The rate should default to 9% if not given.

Show the solution

return amount * (1 + rate)

Right — default arguments handle the common case without forcing every caller to repeat it.

Try it in the live editor →
4

Is It Valid?

Write <code>is_valid_email(text)</code> that returns <code>True</code> only if the text contains exactly one <code>@</code> and a <code>.</code> after it.

Solution and instant grading: open it in the practice app (use one of your 20 free picks, or Pro).

Try it in the live editor →