Practice: Import Statement
Q1. Import with an alias
Import math as m and print m.sqrt(144).
Goal: Use import as.
Q2. From import two names
Use one from-import line to bring floor and ceil from math, then print floor(2.7) and ceil(2.1) on one line separated by a space.
Goal: Use from import.
Q3. Count letters
Use Counter from collections to print how many times 'l' appears in 'hello world'.
Goal: Import a class by name.
Q4. Rename an imported name
Import pow from math as power and print power(3, 2).
Goal: Combine from and as.
Q5. Safe optional import
Write code that tries to import a module named fancy_colors and sets a variable fancy_colors to None if it is missing. Print whether it is None.
Goal: Handle ImportError.
Q6. Statistics mean
Import statistics as st and print the mean of [10, 20, 30].
Goal: Use a library module.
Q7. Import date
Use from datetime import date to create date(2024, 2, 29) and print its weekday name via strftime('%A').
Goal: Import one class.
Q8. Alias leaves no original
What does this print?
import math as m
try:
math
except NameError:
print('no math')
print(m.floor(2.5))Goal: Know alias behaviour.
Q9. Name overwritten by star
What does this print?
floor = 'text'
from math import *
print(floor(3.9))Goal: See star import risk.
Q10. From import value
What does this print?
from math import sqrt
print(sqrt(49))Goal: Read from-import.
Q11. Import error text
What does this print?
try:
import no_such_thing
except ModuleNotFoundError as e:
print(e.name)Goal: Read ImportError info.
Q12. Missing name
What does this print?
try:
from math import banana
except ImportError:
print('no such name')Goal: Know ImportError.
Q13. Same object
What does this print?
import math
from math import sqrt
print(sqrt is math.sqrt)Goal: Know shared modules.
Q14. Alias then original
This code raises NameError. Fix it so it prints 5.0.
import math as m
print(math.sqrt(25))Goal: Use aliases correctly.
Q15. Prefix after from-import
This code raises NameError. Fix it so it prints 4.
from math import sqrt
print(math.floor(4.5))Goal: Understand created names.
Q16. Wrong order of words
This line is a SyntaxError. Fix it so it imports ceil and prints 3.
import ceil from math
print(ceil(2.2))Goal: Know import syntax.
Q17. Why avoid star?
Give two reasons why from module import * is discouraged.
Goal: Explain star import.
Q18. ImportError relation
How are ModuleNotFoundError and ImportError related?
Goal: Know exception hierarchy.
Q19. Tidy report
You need floor and ceil from math and the whole statistics module (alias st). Write the imports and print floor(st.mean([4, 5])) , which is the floor of 4.5.
Goal: Mix import forms.