bhylu.com

Advertisements

Python Exercises

Practise combining several Python ideas in one small task. Start with correct behaviour on ordinary data, then test boundaries before making the code shorter.

Understand the idea

Task 1: total positive stock. Task 2: retain first-seen unique names. Task 3: return None for a missing course position while preserving zero. Task 4: parse a positive quantity and reject invalid text. The worked solution here answers task 1; attempt all four before comparing code.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

Your task

Practise combining several Python ideas in one small task. Start with correct behaviour on ordinary data, then test boundaries before making the code shorter.

Show the worked solution
Python

stock = [0, 5, 2, 0]
print(sum(count for count in stock if count > 0))

Check the result

The positive stock total is 7.

Test one more case

Add a test for empty input and a stated policy for malformed entries.