Solutions

Python Modules and Libraries Quiz – Solutions

1. Given the following code snippet:

import math
print(math.pi)

Answer: This code will output the mathematical constant Pi (π) to a high level of precision.

2. Which Python library would you use if you need to work with dates and times? Write an example code snippet that uses this library to get the current date and time.

Answer: The `datetime` module is used for manipulating dates and times. Example:

import datetime
print(datetime.datetime.now())

3. The following code snippet:

import os
os.system('mkdir new_directory')

Answer: This script creates a new directory named “new_directory” in the current working directory.

4. Consider the following code snippet:

import random
print(random.randint(1, 100))

Answer: This script will output a random integer between 1 and 100, inclusive.

5. What is the difference between `import module` and `from module import function` in Python? Provide a brief explanation and an example code snippet for each.

Answer: `import module` imports the whole module and you access its functions using the dot operator. `from module import function` imports only the specific function from the module and you can call it directly.

import math
print(math.pi)

from math import pi
print(pi)

6. What does the following code snippet do?

import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.dot(a, b))

Answer: This code calculates and prints the dot product of vectors `a` and `b`.

7. How would you use the `requests` library to send a GET request to `https://www.example.com`? Write a code snippet that sends this request and prints the HTTP status code of the response.

Answer:

import requests
response = requests.get('https://www.example.com')
print(response.status_code)

8. Given the following code snippet:

import pandas as pd
data = pd.read_csv('data.csv')
print(data.head())

Answer: This script reads a CSV file named “data.csv” into a pandas DataFrame and prints the first five rows of the DataFrame.

9. Write a code snippet that uses the `json` library to parse the following JSON string into a Python dictionary: `'{ “name”:”John”, “age”:30, “city”:”New York”}’`.

Answer:

import json
data = json.loads('{ "name":"John", "age":30, "city":"New York"}')
print(data)

10. How would you use the `matplotlib.pyplot` library to plot the graph of a function, say `y = x^2`, for `x` ranging from -10 to 10? Write a code snippet that accomplishes this.

Answer:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-10, 10, 100)
y = x ** 2

plt.plot(x, y)
plt.show()

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top