Practice: Built-in Modules

« Read the chapter

Q1. Factorial of six

BeginnerCoding

Use the math module to print the factorial of 6.

Goal: Use math.

Q2. Greatest common divisor

BeginnerCoding

Print the greatest common divisor of 48 and 36.

Goal: Use math.gcd.

Q3. Days between dates

IntermediateCoding

Print how many days there are from 2024-02-01 to 2024-03-01.

Goal: Use datetime.

Q4. Count words

BeginnerCoding

Use Counter to print the count of 'to' in the list ['to','be','or','not','to','be'].

Goal: Use Counter.

Q5. Dictionary to JSON

IntermediateCoding

Print the JSON text of the dictionary {'a': 1, 'b': [2, 3]}.

Goal: Use json.

Q6. Float comparison

IntermediateCoding

Print whether 0.1 + 0.2 is close to 0.3 using the right function.

Goal: Compare floats safely.

Q7. Pairs from a list

IntermediateCoding

Use itertools.combinations to print all pairs from ['x','y','z'] as a list.

Goal: Use itertools.

Q8. Rounding negatives

BeginnerOutput

What does this print?

Code
import math
print(math.floor(-1.2), math.ceil(-1.2))

Goal: Know floor and ceil.

Q9. Date plus days

IntermediateOutput

What does this print?

Code
from datetime import date, timedelta
print(date(2023, 12, 25) + timedelta(days=10))

Goal: Add timedelta.

Q10. Most common

IntermediateOutput

What does this print?

Code
from collections import Counter
print(Counter('banana').most_common(1))

Goal: Read Counter.

Q11. JSON round trip

IntermediateOutput

What does this print?

Code
import json
data = json.loads('{"x": [1, 2, 3], "ok": true}')
print(data['ok'], sum(data['x']))

Goal: Read JSON.

Q12. Chain joins

BeginnerOutput

What does this print?

Code
from itertools import chain
print(list(chain('ab', [1, 2])))

Goal: Use chain.

Q13. Seeded safety

BeginnerOutput

What does this print?

Code
import random
random.seed(3)
print(random.randint(5, 5))

Goal: Know randint ends.

Q14. Floats with ==

IntermediateDebugging

This code prints False. Change only the comparison so it prints True.

Code
print(0.1 + 0.2 == 0.3)

Goal: Fix float comparison.

Q15. dump versus dumps

IntermediateDebugging

This code raises an error because json.dumps is used with a file argument. Fix it so it prints the JSON text.

Code
import json
print(json.dumps([1, 2], 'out.json'))

Goal: Know dump vs dumps.

Q16. Missing import

BeginnerDebugging

This code raises NameError. Fix it so it prints 3.

Code
print(Counter('aaabb')['a'])

Goal: Import names.

Q17. Choose a module

BeginnerConceptual

Which module would you use to count the most common words in a text and which to find the number of days between two dates?

Goal: Pick the right module.

Q18. Random for passwords?

AdvancedConceptual

Why should random not be used to create passwords?

Goal: Know security limits.

Q19. Next birthday gap

IntermediateApplication

Today is replaced by date(2024, 6, 1) and the birthday by date(2024, 12, 25). Print the number of days left.

Goal: Compute date gaps.