1
Which function is used to open a file in Python?
A. read()
B. start()
C. open()
D. file()
Correct Answer: open()
Explanation:
The built-in function open() is used to open a file and returns a file object.
2
What is the default mode when opening a file using the open() function?
A. Binary ('b')
B. Write ('w')
C. Append ('a')
D. Read ('r')
Correct Answer: Read ('r')
Explanation:
If the mode argument is omitted, Python defaults to 'r', which opens the file for reading.
3
Which file mode opens a file for writing and creates the file if it does not exist, but truncates it if it does?
A. 'x'
B. 'w'
C. 'a'
D. 'r'
Correct Answer: 'w'
Explanation:
The 'w' mode opens a file for writing. It creates a new file if it doesn't exist or truncates (overwrites) the file if it exists.
4
To write a variable that is an integer to a text file, what must be done first?
A. Pickle it
B. Cast it to a float
C. Write it directly
D. Cast it to a string
Correct Answer: Cast it to a string
Explanation:
Text files accept only strings. Integers must be converted using str() before writing.
5
Which method is used to read the entire content of a file as a single string?
A. readline()
B. readlines()
C. read()
D. scan()
Correct Answer: read()
Explanation:
The read() method reads the whole file content into a single string variable.
6
What is the return type of the readlines() method?
A. Dictionary
B. String
C. List of strings
D. Integer
Correct Answer: List of strings
Explanation:
readlines() reads all lines in a file and returns them as a list of strings.
7
Which keyword is used to handle file closing automatically in Python?
A. with
B. for
C. try
D. do
Correct Answer: with
Explanation:
The 'with' statement acts as a context manager and automatically closes the file once the block of code is executed.
8
Which module allows you to interact with the operating system to handle directories?
A. os
B. file
C. sys
D. dir
Correct Answer: os
Explanation:
The 'os' module provides a portable way of using operating system-dependent functionality, including directory manipulation.
9
Which function is used to create a new directory?
A. os.mkdir()
B. os.newdir()
C. os.create_dir()
D. os.make()
Correct Answer: os.mkdir()
Explanation:
os.mkdir() is the standard function to create a directory named path.
10
What does 'Pickling' refer to in Python?
A. Compressing a file
B. Converting a byte stream back into an object
C. Converting an object hierarchy into a byte stream
D. Encrypting a file
Correct Answer: Converting an object hierarchy into a byte stream
Explanation:
Pickling (serialization) is the process of converting a Python object into a byte stream.
11
Which module is required to perform pickling?
A. json
B. os
C. pickle
D. serialize
Correct Answer: pickle
Explanation:
The standard module for object serialization in Python is named 'pickle'.
12
Which file mode must be used when writing pickled data to a file?
A. 'r'
B. 'rb'
C. 'wb'
D. 'w'
Correct Answer: 'wb'
Explanation:
Pickling creates a byte stream, so the file must be opened in binary write mode ('wb').
13
Which function is used to deserialize a byte stream back into a Python object?
A. pickle.dump()
B. pickle.load()
C. pickle.push()
D. pickle.write()
Correct Answer: pickle.load()
Explanation:
pickle.load() reads the pickled byte stream from a file and reconstructs the object.
14
What exception is raised when a number is divided by zero?
A. ZeroDivisionError
B. TypeError
C. ArithmeticError
D. ValueError
Correct Answer: ZeroDivisionError
Explanation:
Python raises a ZeroDivisionError when the second argument of a division or modulo operation is zero.
15
Which block contains the code that might raise an exception?
A. finally
B. except
C. try
D. else
Correct Answer: try
Explanation:
The 'try' block lets you test a block of code for errors.
16
When is the code inside the 'else' block of a try-except statement executed?
A. When the try block fails
B. Always
C. When no exception occurs
D. When an exception occurs
Correct Answer: When no exception occurs
Explanation:
The else block allows you to execute code if the try block does not raise an exception.
17
What exception is raised when trying to open a file that does not exist in read mode?
A. IOError
B. FileError
C. FileNotFoundError
D. NameError
Correct Answer: FileNotFoundError
Explanation:
FileNotFoundError is raised when a file or directory is requested but cannot be found.
18
Which of the following correctly handles a specific exception named 'MyError'?
A. catch MyError:
B. handle MyError:
C. except MyError:
D. try MyError:
Correct Answer: except MyError:
Explanation:
The syntax to handle a specific exception in Python is 'except ExceptionName:'.
19
What is the primary purpose of the 'finally' block?
A. To execute code regardless of errors
B. To handle errors
C. To return a value
D. To stop the program
Correct Answer: To execute code regardless of errors
Explanation:
The finally block lets you execute code, regardless of the result of the try- and except blocks (often used for cleanup).
20
How can you access the error message associated with an exception?
A. catch Exception e:
B. except Exception with e:
C. except e in Exception:
D. except Exception as e:
Correct Answer: except Exception as e:
Explanation:
Using 'as e' assigns the exception object to the variable 'e', allowing access to its details.
21
Which module supports Regular Expressions in Python?
A. re
B. regexp
C. regex
D. pyre
Correct Answer: re
Explanation:
The built-in module for regular expressions in Python is named 're'.
22
What does the special character '^' represent in a regular expression?
A. End of string
B. Any character
C. Start of string
D. Escape character
Correct Answer: Start of string
Explanation:
The caret symbol '^' matches the start of the string.
23
Which regular expression quantifier matches 0 or more occurrences of the preceding character?
Correct Answer: *
Explanation:
The asterisk '*' matches 0 or more repetitions of the preceding regex.
24
What does the pattern '.' (dot) match?
A. Start of string
B. Any digit
C. Only a literal dot
D. Any character except a newline
Correct Answer: Any character except a newline
Explanation:
In default mode, the dot matches any character except the newline character.
25
Which function searches for a pattern only at the beginning of a string?
A. re.search()
B. re.findall()
C. re.match()
D. re.find()
Correct Answer: re.match()
Explanation:
re.match() checks for a match only at the beginning of the string.
26
What does the special sequence '\d' match?
A. Any alphabet
B. Any digit (0-9)
C. Any non-digit
D. Any whitespace
Correct Answer: Any digit (0-9)
Explanation:
\d matches any decimal digit; this is equivalent to the class [0-9].
27
Which function returns a list of all non-overlapping matches in the string?
A. re.findall()
B. re.match()
C. re.search()
D. re.group()
Correct Answer: re.findall()
Explanation:
re.findall() scans the string and returns all non-overlapping matches as a list of strings.
28
What does the quantifier '+' match?
A. Exactly 1 occurrence
B. 0 or 1 occurrence
C. 0 or more occurrences
D. 1 or more occurrences
Correct Answer: 1 or more occurrences
Explanation:
The plus sign '+' matches 1 or more repetitions of the preceding regex.
29
Which character is used to define a range of characters, like 'a' through 'z'?
Correct Answer: []
Explanation:
Square brackets [] are used to indicate a set of characters or a range, e.g., [a-z].
30
What is the output of re.sub()?
A. A match object
B. A boolean
C. A string with replacements made
D. A list
Correct Answer: A string with replacements made
Explanation:
re.sub(pattern, repl, string) returns the string obtained by replacing the leftmost non-overlapping occurrences of pattern with repl.
31
Which regex pattern would match a valid email address roughly containing an '@' symbol?
A. \w#\w
B. \w+@\w+.\w+
C. \d+@\w+
D. email:\w
Correct Answer: \w+@\w+.\w+
Explanation:
This pattern looks for alphanumeric characters (\w+), followed by '@', followed by domain name characters, a dot, and an extension.
32
In the context of web scraping with regex, what are usually targeted to extract links?
A. href attributes
B. src attributes
C. <div> tags
D. span tags
Correct Answer: href attributes
Explanation:
In HTML, hyperlinks are defined in the 'href' attribute of <a> tags, making them the target for extracting links.
33
What does the '?' quantifier signify?
A. Match 0 or more times
B. Match 0 or 1 times
C. Match 1 or more times
D. Match exactly 1 time
Correct Answer: Match 0 or 1 times
Explanation:
The question mark '?' causes the resulting RE to match 0 or 1 repetitions of the preceding RE.
34
Which special sequence matches any whitespace character (space, tab, newline)?
Correct Answer: \s
Explanation:
\s matches any whitespace character.
35
Why are raw strings (r'text') preferred for regular expressions in Python?
A. They allow binary data
B. They avoid conflict with Python's escape characters
C. They run faster
D. They match case insensitively
Correct Answer: They avoid conflict with Python's escape characters
Explanation:
Raw strings treat backslashes as literal characters, preventing Python from interpreting things like '\b' (backspace) before the regex engine sees it.
36
What method of a match object returns the string matched by the regex?
A. match()
B. get()
C. return()
D. group()
Correct Answer: group()
Explanation:
The group() method returns the part of the string where there was a match.
37
Which flag is used to perform case-insensitive matching?
A. re.A
B. re.C
C. re.I
D. re.M
Correct Answer: re.I
Explanation:
re.I (or re.IGNORECASE) performs case-insensitive matching.
38
How do you define a 'group' within a regular expression to extract specific parts?
A. Using []
B. Using ()
C. Using ||
D. Using {}
Correct Answer: Using ()
Explanation:
Parentheses () are used to create capturing groups.
39
What happens if re.match() does not find a match?
A. Returns -1
B. Returns False
C. Returns None
D. Raises an error
Correct Answer: Returns None
Explanation:
re.match() returns None if no match is found.
40
In Web Scraping, why might regex be used on HTML content?
A. To render the page
B. To connect to the server
C. To extract text matching specific patterns
D. To execute JavaScript
Correct Answer: To extract text matching specific patterns
Explanation:
Regex is used to parse the raw HTML string and extract specific information like emails, phone numbers, or links.
41
What is the function os.getcwd() used for?
A. Generate Code Working Directory
B. Get Current Write Directory
C. Get Count Working Directory
D. Get Current Working Directory
Correct Answer: Get Current Working Directory
Explanation:
os.getcwd() returns a string representing the current working directory.
42
Which method is used to check if a file exists at a specified path?
A. os.exists()
B. os.check()
C. file.exists()
D. os.path.exists()
Correct Answer: os.path.exists()
Explanation:
os.path.exists(path) returns True if the path refers to an existing path or open file descriptor.
43
To write a list of strings to a file, which method is most direct?
A. write()
B. writelines()
C. putlines()
D. print()
Correct Answer: writelines()
Explanation:
writelines() writes a list of strings to the file.
44
What does the '$' symbol represent in regex?
A. Currency
B. Variable
C. Start of string
D. End of string
Correct Answer: End of string
Explanation:
The dollar sign '$' matches the end of the string or just before the newline at the end of the string.
45
Which of the following is NOT a valid file mode?
Correct Answer: z
Explanation:
'z' is not a standard file opening mode in Python.
46
If a try block raises an exception that is not defined in the except block, what happens?
A. The program crashes (terminates)
B. It is ignored
C. The else block runs
D. The try block repeats
Correct Answer: The program crashes (terminates)
Explanation:
If an unhandled exception occurs, the program terminates with a traceback error.
47
Which regex pattern matches any non-digit character?
Correct Answer: \D
Explanation:
\D matches any character that is not a decimal digit (inverse of \d).
48
What is the purpose of the re.split() function?
A. To split a string by the occurrences of a pattern
B. To find duplicates
C. To remove patterns
D. To join strings
Correct Answer: To split a string by the occurrences of a pattern
Explanation:
re.split() splits the string by the occurrences of the pattern.
49
When using pickle.dump(obj, file), what is the 'file' argument?
A. The file path string
B. A string of data
C. The directory name
D. A file object opened in binary write mode
Correct Answer: A file object opened in binary write mode
Explanation:
The second argument must be a file object (created via open()) capable of writing binary data.
50
What is the standard Python library used to fetch URLs for web scraping before using regex?
A. sys
B. os
C. urllib
D. pickle
Correct Answer: urllib
Explanation:
urllib (specifically urllib.request) is a standard library used to open URLs to get HTML content for scraping.