Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

An Example That Runs

You've checked what code does by running it: you worked out by hand what a walk should cost, printed the price and compared the two. A test writes that comparison into the program:

print(walk_price(45) == 12)

You know == from conditions: it compares two values and gives True or False. This line calls the function with 45 minutes and compares what it returns with 12, the price you worked out: two half hours, the second of them started, at £6 each, as Mia charges again now that her week at £7 is over. If it prints True, the function returns what you expected. If it prints False, the function and your expectation disagree, and one of them is wrong.

A test is an example that runs. Once it's written, it checks the function again every time you run the program: after you change the function, and after you paste in code from an AI. A few tests are enough if they are the right ones: an ordinary case, and the boundaries, where mistakes hide. With Mia's prices, that's a walk of exactly 30 minutes, which is one half hour, and a walk of 31 minutes, where the second half hour has just started.

This exercise has no chat: the tests are yours. Its check also runs them on a broken walk_price(), because a test is worth something only if it prints False when the function is wrong.

Instructions

  1. 1

    Under the function, write the test print(walk_price(45) == 12) and run the program. It prints True.

  2. 2

    Write two more tests in the same way: one for a walk of exactly 30 minutes and one for a walk of 31 minutes. Work out yourself what each should cost. Run the program: it prints True three times.

Back

1/7

  1. 1. An Example That Runs
  2. 2. Tests First, Then the Code
  3. 3. Check the Tests Too
  4. 4. Quiz: The Function or the Test?
  5. 5. Tests with assert
  6. 6. Quiz: Which Line Is Wrong?
  7. 7. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.