Python Programming - Standard Libraries

Exercise : Standard Libraries - General Questions
  • Standard Libraries - General Questions
81.
What is the purpose of the socket module?
Sorting elements in a list
Handling exceptions and errors
Working with cryptographic hash functions
Implementing network communication
Answer: Option
Explanation:
import socket

# Example usage of socket module for creating a simple server
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 8080))
server_socket.listen(1)
connection, address = server_socket.accept()
print(f"Connected by {address}")

82.
How can you use the logging module in Python to configure a logger with a specific log level and output format?
logging.create_logger(level=logging.DEBUG, format='%(message)s')
logging.configure_logger(level=logging.INFO, format='%(asctime)s - %(message)s')
logging.create_logger(logging.INFO, '%(message)s')
logging.basicConfig(level=logging.DEBUG, format='%(message)s')
Answer: Option
Explanation:
import logging

# Example usage of logging module for configuring a logger
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(message)s')
logger = logging.getLogger('my_logger')
logger.debug('This is a debug message')

83.
How can you use the hashlib module in Python to calculate the SHA-256 hash of a string?
hashlib.sha256(string.encode()).hexdigest()
hashlib.hash256(string.encode())
hashlib.sha256(string).hexdigest()
hashlib.hash256(string)
Answer: Option
Explanation:
import hashlib

# Example usage of hashlib module for calculating the SHA-256 hash of a string
string = 'Hello, World!'
hashed_string = hashlib.sha256(string.encode()).hexdigest()
print(hashed_string)

84.
What is the purpose of the gzip module?
Sorting elements in a list
Handling exceptions and errors
Compressing and decompressing files using the gzip format
Parsing JSON data
Answer: Option
Explanation:
import gzip

# Example usage of gzip module for compressing a file
with open('file.txt', 'rb') as f_in:
    with gzip.open('file.txt.gz', 'wb') as f_out:
        f_out.writelines(f_in)

85.
How can you use the turtle module in Python to draw a square?
turtle.draw_square()
turtle.square()
turtle.forward(100); turtle.right(90); turtle.forward(100); turtle.right(90); turtle.forward(100); turtle.right(90); turtle.forward(100)
turtle.draw('square')
Answer: Option
Explanation:
import turtle

# Example usage of turtle module for drawing a square
for _ in range(4):
    turtle.forward(100)
    turtle.right(90)

turtle.done()