Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 10.9 — Writing Modern Python: An Idiom Upgrade
Python · Example 2 of 3

Old and new give the same answer

Each pair computes the same thing the old way and the new way. The match version of old_style is the same logic with a clearer shape.

Python has changed a lot since the code in old tutorials was written. This topic puts the old way and the modern way side by side, so you can read old code, write current code, and know what each recent version added.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Rewrite "Total: %d items" % count with an f-string, for count = 7, and print it.

02

Merge {"a": 1} and {"a": 2, "b": 3} with the dictionary union operator and print the result. Which value of a wins?

03

Use zip(strict=True) on [1, 2] and ["a"] inside a try and print the error message.

04

Rewrite from typing import Optional, List hints Optional[List[str]] in the modern style and print it with typing.get_type_hints for a function using it.

Explain it without notes

01

Give five modern replacements for old Python idioms.

02

What does zip(a, b, strict=True) protect you from?

03

How would you modernise a large codebase safely?

04

What are template strings and what problem do they address?

05

Is a | b for dicts a deep merge? How does it differ from a |= b and {**a, **b}?

Old and new give the same answer
Sign in to run this example in your browser.

Expected output

merge dicts        same: True
format text        same: True
strip prefix       same: True
isinstance tuple   same: True
enumerate from 1   same: True
None none none
-5 negative negative
0 zero zero
7 positive positive
['alpha', 'gamma-delta'] last size seen: 11