Exercise: Python

Questions for: Standard Libraries

How can you use the sqlite3 module in Python to connect to an SQLite database and execute a query?
A:
sqlite3.connect(database)
B:
sqlite3.query(database, sql)
C:
sqlite3.execute(database, sql)
D:
sqlite3.query(sql)
Answer: A
import sqlite3

# Example usage of sqlite3 module for connecting to an SQLite database and executing a query
connection = sqlite3.connect('example.db')
cursor = connection.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)')
connection.commit()
connection.close()
What is the purpose of the email module?
A:
Sorting elements in a list
B:
Handling email messages and MIME attachments
C:
Parsing JSON data
D:
Working with cryptographic hash functions
Answer: B
import email.message

# Example usage of email module for creating an email message
msg = email.message.EmailMessage()
msg.set_content("Hello, this is a test email.")
msg["Subject"] = "Test Email"
msg["From"] = "sender@example.com"
msg["To"] = "recipient@example.com"
How can you use the shutil module in Python to copy a file from one location to another?
A:
shutil.copy_file(src, dst)
B:
shutil.move_file(src, dst)
C:
shutil.copy(src, dst)
D:
shutil.move(src, dst)
Answer: C
import shutil

# Example usage of shutil module for copying a file
source_path = 'file.txt'
destination_path = 'copy_of_file.txt'
shutil.copy(source_path, destination_path)
How can you use the argparse module in Python to parse command-line arguments?
A:
argparse.parse_args()
B:
argparse.get_args()
C:
argparse.parse()
D:
argparse.ArgumentParser().parse_args()
Answer: D
import argparse

# Example usage of argparse module for parsing command-line arguments
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator')
args = parser.parse_args()
print(args.integers)
How can you use the urllib.request module in Python to make an HTTP GET request to a URL?
A:
urllib.get(url)
B:
urllib.urlopen(url)
C:
urllib.request.get(url)
D:
urllib.request.urlopen(url)
Answer: D
import urllib.request

# Example usage of urllib.request module for making an HTTP GET request
url = 'https://www.example.com'
response = urllib.request.urlopen(url)
content = response.read()
print(content)
Ad Slot (Above Pagination)
Quiz