Use python -m pip install matplotlib instead -> Option C
Quick Check:
python -m pip install = A [OK]
Hint: Run pip via python -m pip if pip command fails [OK]
Common Mistakes:
Restarting without fixing path issues
Reinstalling Python unnecessarily
Trying to uninstall before installing
5. You want to create a Python script that uses Matplotlib but ensure it works even if Matplotlib is not installed. Which code snippet correctly handles this?
hard
A. try:
import matplotlib.pyplot as plt
except ImportError:
print('Matplotlib not installed')
B. import matplotlib.pyplot as plt
if plt is None:
print('Matplotlib missing')
C. if 'matplotlib' in sys.modules:
import matplotlib.pyplot as plt
D. import matplotlib.pyplot as plt
except ImportError:
print('Error')
Solution
Step 1: Use try-except to catch import errors
Wrapping the import in a try block catches ImportError if Matplotlib is missing.
Step 2: Handle ImportError gracefully
The except block prints a message instead of crashing the script.
Final Answer:
try:\n import matplotlib.pyplot as plt\nexcept ImportError:\n print('Matplotlib not installed') -> Option A
Quick Check:
try-except ImportError = C [OK]
Hint: Use try-except ImportError to handle missing packages [OK]
Common Mistakes:
Using if without try-except for imports
Incorrect except syntax without try
Checking sys.modules before import
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.