First 50 of 200 questions. Each one lists the choices, the correct answer, and an explanation. The checker at the top of this page saves progress in this browser when it is available.
Continue in the practice tool above to load more questions, 50 at a time.
Question 1Python programming fundamentals and scripting for IT tasks
A script must read a configuration file and convert the string value "42" into an integer so it can be used in arithmetic. Which built-in function performs this conversion?
- input()
- int() Correct answer.
- str()
- float()
Explanation
The int() function parses a string of digits and returns an integer object, which is what arithmetic operations require. str() moves in the opposite direction, and float() would produce a decimal value rather than an integer.
Question 2Python programming fundamentals and scripting for IT tasks
An IT technician wants a script to repeat a cleanup routine once for each entry in a list of server names. Which Python construct is designed for iterating over the elements of a list?
- a try/except block
- a for loop Correct answer.
- a while loop with a manual counter
- a lambda expression
Explanation
A for loop iterates directly over the items of an iterable such as a list, binding each element to the loop variable in turn. A while loop can do the job but requires manual index bookkeeping, while try/except and lambda serve unrelated purposes.
Question 3Python programming fundamentals and scripting for IT tasks
A script stores output in a variable named `report` and needs to append a newline and a closing message to the existing text. Which operation accomplishes this?
- report += "\nDone" Correct answer.
- report.split("\n")
- report.strip()
- report.lower()
Explanation
The += operator concatenates the right-hand string onto the existing value, so the newline and message are appended in place. The other methods return modified copies for parsing or formatting and do not extend the original text.
Question 4Python programming fundamentals and scripting for IT tasks
A script defines `def check_disk(path, threshold=90):` and a caller invokes `check_disk("/var")`. What value does `threshold` hold inside the function?
- None
- 90 Correct answer.
- It raises a TypeError because the argument is missing.
- 0
Explanation
A parameter with a default value uses that default when the caller omits the corresponding argument. Since only path is supplied, threshold receives its declared default of 90.
Question 5Python programming fundamentals and scripting for IT tasks
A script opens a file with `with open("log.txt") as f:` and reads it. What is the main benefit of using the `with` statement here?
- It automatically closes the file when the block exits. Correct answer.
- It converts the file contents into a list of integers.
- It prevents other programs from reading the file.
- It compresses the file on disk.
Explanation
The with statement is a context manager that guarantees the file is closed when the block finishes, even if an exception occurs. It does not transform, compress, or lock the file's contents.
Question 6Python programming fundamentals and scripting for IT tasks
An administrator needs to store a set of unique usernames and repeatedly test whether a given name is present. Which built-in type provides fast membership testing with no duplicate entries?
- a tuple
- a list
- a string
- a set Correct answer.
Explanation
A set stores unique elements and uses hashing so the `in` operator runs in roughly constant time. Lists and tuples allow duplicates and require linear scans, and a string is a single sequence of characters.
Question 7Python programming fundamentals and scripting for IT tasks
A script executes `print(7 // 2)` and then `print(7 % 2)`. What two values are printed in order?
- 4 and 1
- 3 and 0
- 3 and 1 Correct answer.
- 3.5 and 1
Explanation
The // operator performs floor division, giving 3, and the % operator returns the remainder, which is 1. Together they show the quotient and remainder of integer division.
Question 8Python programming fundamentals and scripting for IT tasks
A script reads a line of text from a user with `name = input("User: ")`. What data type does `name` hold?
- list
- int
- bytes
- str Correct answer.
Explanation
The input() function always returns a string, regardless of what the user types. Converting to a number requires an explicit call such as int() or float().
Question 9Python programming fundamentals and scripting for IT tasks
A script contains `for i in range(3): print(i)`. What output does it produce?
- 0 1 2, each on its own line Correct answer.
- 3 2 1, each on its own line
- 1 2 3, each on its own line
- 0 1 2 3, each on its own line
Explanation
range(3) generates the integers starting at 0 up to but not including 3, so the loop prints 0, 1, and 2. The stop value is exclusive, which is a common source of off-by-one errors.
Question 10Python programming fundamentals and scripting for IT tasks
A script must handle a missing file gracefully instead of crashing. Which structure should wrap the file-opening code?
- with/as
- def/return
- try/except Correct answer.
- if/elif/else
Explanation
try/except catches exceptions such as FileNotFoundError so the program can respond instead of terminating. Conditional branches cannot intercept runtime exceptions, and with/as only manages resource cleanup.
Question 11Python programming fundamentals and scripting for IT tasks
A function is defined as `def log(msg, level):` and a caller writes `log(level="WARN", msg="disk full")`. What happens?
- It raises a SyntaxError at parse time.
- It raises a TypeError because arguments must follow definition order.
- It runs correctly because keyword arguments are matched by name. Correct answer.
- It runs but assigns level to msg and msg to level.
Explanation
Keyword arguments are bound to parameters by name, so their order in the call does not matter. The call supplies both msg and level, so the function executes normally.
Question 12Python programming fundamentals and scripting for IT tasks
A list named `ports` holds integers. A script needs a new list containing each port doubled. Which expression produces that result?
- [p * 2 for p in ports] Correct answer.
- ports * 2
- list(ports * 2)
- ports.append(2)
Explanation
A list comprehension applies the expression p * 2 to every element and builds a new list. Multiplying a list by 2 instead repeats the list itself rather than doubling each value.
Question 13Python programming fundamentals and scripting for IT tasks
A script reads `data = {"host": "srv1", "port": 22}` and executes `print(data["user"])`. What is the result?
- It prints "user".
- It prints None.
- It raises a KeyError. Correct answer.
- It prints an empty string.
Explanation
Dictionary subscripting raises KeyError when the key is absent; it does not return a default. To avoid the exception, code should use get() or test membership first.
Question 14Python programming fundamentals and scripting for IT tasks
A script needs to parse structured configuration text where each line is `key=value`. Which string method cleanly splits one line into the key and the value?
- line.replace("=", "")
- line.split("=") Correct answer.
- line.strip("=")
- line.find("=")
Explanation
split("=") returns a two-element list containing the text before and after the delimiter, which is exactly the key and value. strip() would only remove delimiter characters from the ends, and find() returns an index.
Question 15Python programming fundamentals and scripting for IT tasks
A script defines `def total(items=[]):` and appends to items across multiple calls. What behavior should the author expect?
- A fresh empty list is created on every call.
- The function raises an error when called without arguments.
- The default list is shared, so appended values persist between calls. Correct answer.
- The list is reset to empty each time the function returns.
Explanation
Default argument values are evaluated once when the function is defined, so a mutable default such as a list is reused across calls and accumulates state. The recommended fix is to default to None and create a new list inside the function.
Question 16Python programming fundamentals and scripting for IT tasks
A script must write several lines to a new file, overwriting any existing content. Which mode should be passed to open()?
- "r"
- "w" Correct answer.
- "x"
- "a"
Explanation
Mode "w" opens the file for writing and truncates existing content, which matches the requirement to overwrite. Mode "a" would append instead, and "r" is read-only.
Question 17Python programming fundamentals and scripting for IT tasks
A script iterates over a list of processes and needs to skip any entry whose status equals "stopped" while continuing with the rest. Which statement should be used inside the loop?
- break
- return
- continue Correct answer.
- pass
Explanation
continue skips the remainder of the current iteration and proceeds to the next item, which matches the requirement. break would exit the loop entirely and stop processing later entries.
Question 18Python programming fundamentals and scripting for IT tasks
A script must import only the `sleep` function from the time module. Which statement accomplishes this?
- from time import sleep Correct answer.
- import time.sleep
- import sleep from time
- include time.sleep
Explanation
The form `from module import name` brings a specific name into the current namespace so it can be called directly. `import time.sleep` treats sleep as a module path, which is invalid.
Question 19Python programming fundamentals and scripting for IT tasks
A script must sort a list of dictionaries by the "size" key in ascending order. Which call achieves this?
- sorted(disks, key=lambda d: d["size"]) Correct answer.
- sorted(disks)
- sorted(disks, reverse="size")
- disks.sort(reverse=True)
Explanation
The key parameter accepts a function that returns the value to sort on, and a lambda extracts d["size"] for each record. Calling sorted() without a key cannot order dictionaries by a field.
Question 20Python programming fundamentals and scripting for IT tasks
A script contains `try: risky() except ValueError: handle() else: report()`. When is `report()` executed?
- Only when a ValueError is raised and caught.
- Only when an uncaught exception propagates.
- Only when the try block finishes without raising an exception. Correct answer.
- Always, whether or not an exception occurred.
Explanation
The else clause of a try statement runs only when the try block completes without raising any exception. It is skipped when an exception is raised and handled by an except clause.
Question 21Python programming fundamentals and scripting for IT tasks
A function must return both a status code and a message to its caller. Which approach is idiomatic Python?
- Store them in global variables.
- Raise an exception containing the message.
- Return a tuple such as `return code, message`. Correct answer.
- Print both values and return None.
Explanation
Returning a tuple lets the caller unpack both values, for example `code, message = check()`, which is the standard Python idiom. Global variables create hidden coupling, and printing discards the values from the program's data flow.
Question 22Python programming fundamentals and scripting for IT tasks
A script builds a list with `result = []` then runs `for x in data: result.append(x * 2)`. Which single expression is equivalent?
- result = [x for x in data] * 2
- result = list(x * 2 for x in data)
- result = [x * 2 for x in data] Correct answer.
- result = map(lambda x: x * 2, data)
Explanation
The list comprehension applies x * 2 to each element and collects the results into a new list, matching the loop exactly. The map() call returns an iterator, and multiplying the list repeats its elements.
Question 23Python programming fundamentals and scripting for IT tasks
A script reads a large log file line by line and must avoid loading the whole file into memory. Which approach is most appropriate?
- lines = f.readlines(); then loop over lines
- Call f.seek(0) before every read
- content = f.read(); then split the string
- Iterate directly over the file object with `for line in f:` Correct answer.
Explanation
Iterating over a file object yields one line at a time, so memory use stays bounded regardless of file size. read() and readlines() both load the entire file into memory before processing begins.
Question 24Python programming fundamentals and scripting for IT tasks
A script defines `def outer(): count = 0` and an inner function that must modify `count`. Which declaration is required inside the inner function?
- extern count
- nonlocal count Correct answer.
- static count
- global count
Explanation
The nonlocal keyword lets a nested function rebind a variable from its enclosing function's scope. The global keyword would target module-level scope instead of the enclosing function's local variable.
Question 25Python programming fundamentals and scripting for IT tasks
A script compares two strings read from configuration files and finds them unequal even though they look identical. Which explanation is most likely?
- String comparison is case-insensitive by default.
- Hidden whitespace such as a trailing newline differs between them. Correct answer.
- The strings must be converted to bytes before comparison.
- Python strings cannot be compared with ==.
Explanation
Lines read from files often retain a trailing newline or spaces, so visually identical text can differ in content. Applying strip() before comparison removes that hidden difference.
Question 26Python programming fundamentals and scripting for IT tasks
An IT automation script reads a text file and must remove trailing newline characters from every line before comparing it to a known hostname. Which approach handles this correctly?
- Compare the raw line to the hostname directly without modification
- Compare line.upper() to the hostname without stripping either value
- Compare line.rstrip('\n') to the hostname with no other change to the hostname
- Compare the raw line to the hostname after calling line.strip() on both sides Correct answer.
Explanation
Iterating a text file yields each line with its terminating newline still attached, so a direct comparison against a literal hostname fails. Applying strip() to both the read line and the expected value removes surrounding whitespace, including the newline, on both operands. This makes the comparison robust even when the file uses trailing spaces or a different line ending.
Question 27Python programming fundamentals and scripting for IT tasks
A backup script must run an external command and capture its standard output as a string for later logging. Which standard library module provides the modern, recommended API for this?
- pickle
- threading
- socket
- subprocess Correct answer.
Explanation
The subprocess module is the standard-library tool for launching external programs, and functions such as run() with capture_output=True return the command's stdout for inspection. The older os.system and os.popen calls are discouraged because they offer weaker control over arguments and error handling. The other modules listed handle networking, concurrency, and serialization respectively.
Question 28Python programming fundamentals and scripting for IT tasks
An automation script processes a list of server records and must build a dictionary that maps each server name to its IP address. Which approach produces that mapping directly?
- mapping = set(r['name'] for r in records)
- names = [r['name'] for r in records]; ips = [r['ip'] for r in records]
- mapping = {r['name']: r['ip'] for r in records} Correct answer.
- mapping = [(r['name'], r['ip']) for r in records]
Explanation
A dictionary comprehension with the form {key_expr: value_expr for item in iterable} builds the mapping in a single pass. Here each record contributes its name as the key and its IP as the value. The result supports direct lookup such as mapping['srv1'].
Question 29Python programming fundamentals and scripting for IT tasks
A script stores a configuration path in a variable and prints it with print(f"Loading {path}"). What does the f prefix change about the string literal?
- It escapes all backslashes in the literal
- It encodes the literal as bytes before printing
- It marks the literal as a raw string with no escapes
- It enables expression substitution inside curly braces Correct answer.
Explanation
An f-string evaluates the expressions inside braces at runtime and inserts their string representations into the result. This is why f"Loading {path}" prints the value of path rather than the literal text. The prefix does not affect escaping or encoding.
Question 30Python programming fundamentals and scripting for IT tasks
A script parses a numeric port value from a configuration file and stores it as a string. Which call converts that value into an integer suitable for socket operations?
- int(port_text) Correct answer.
- float(port_text)
- str(port_text)
- repr(port_text)
Explanation
The int() constructor parses a string of digits into an integer, which is what socket functions expect for a port argument. It raises ValueError if the text is not a valid integer literal, so wrapping it in a try block is common in IT scripts. The other calls either keep the value as text or produce a different type.
Question 31Python programming fundamentals and scripting for IT tasks
An automation script must check whether a directory named /var/log/archive exists before writing to it. Which expression performs that check?
- os.path.getsize('/var/log/archive')
- os.listdir('/var/log/archive')
- os.path.isdir('/var/log/archive') Correct answer.
- os.path.isfile('/var/log/archive')
Explanation
os.path.isdir() returns True when the given path exists and refers to a directory, which is exactly the precondition for writing files into it. isfile() answers a different question about regular files. listdir() and getsize() raise errors when the path is missing, so they are unsuitable as existence checks.
Question 32Python programming fundamentals and scripting for IT tasks
A script needs to repeat a block of code until a remote service responds successfully, with no fixed iteration count. Which loop construct fits this requirement?
- A list comprehension over the service names
- A try block with no except clause
- A while loop with a condition that becomes False on success Correct answer.
- A for loop over range(10)
Explanation
A while loop re-evaluates its condition before each iteration, so it can keep retrying until a flag or status check signals success. This suits polling scenarios where the number of attempts is unknown in advance. A for loop over a fixed range imposes an arbitrary cap, and comprehensions are for building collections.
Question 33Python programming fundamentals and scripting for IT tasks
A script must define a reusable block of code that takes a hostname and returns a boolean indicating reachability, without printing anything itself. Which definition matches that contract?
- is_reachable = check(host)
- def is_reachable(host): print(check(host))
- def is_reachable(host): return check(host) Correct answer.
- def is_reachable: return check(host)
Explanation
A function that returns a value uses the return statement, and the caller decides what to do with the boolean. Printing inside the function would violate the stated contract of returning a value silently. The definition also needs a parameter list, even if it is empty.
Question 34Python programming fundamentals and scripting for IT tasks
A script processes a list of hostnames and must print each one in uppercase. Which code achieves this?
- for host in hosts: print(upper(host))
- print(hosts[0].upper())
- for host in hosts: print(host.upper()) Correct answer.
- print(hosts.upper())
Explanation
Iterating the list yields each hostname string, and the string method upper() returns an uppercase copy for printing. The method must be called on each element, not on the list itself. A bare upper() name is not defined in the builtins.
Question 35Python programming fundamentals and scripting for IT tasks
A script reads a JSON configuration file and needs its contents as Python dictionaries and lists. Which pair of calls is appropriate?
- pickle.load() on a file opened in binary mode
- csv.reader() on the file object
- yaml.safe_load() on the file object
- json.load() on the file object, or json.loads() on the file's text Correct answer.
Explanation
The json module deserializes JSON text into native Python types: json.load() reads from a file object, while json.loads() parses a string. Objects become dicts and arrays become lists. The other options parse different formats or require third-party packages.
Question 36Python programming fundamentals and scripting for IT tasks
A script opens a file with with open(path) as f: and processes it inside the block. What guarantee does the with statement provide when the block finishes or raises an exception?
- The file is deleted from the filesystem
- The file is automatically closed Correct answer.
- The file contents are flushed to disk before closing
- The file is reopened for the next iteration
Explanation
The with statement uses the context manager protocol, calling __exit__ on the file object when the block exits for any reason. For files, __exit__ closes the handle, so resources are released even if an exception propagates. This is why with is preferred over manual close() calls.
Question 37Python programming fundamentals and scripting for IT tasks
A script defines a function that logs a message and must be callable without arguments in quick tests, but also accept an optional destination path. Which signature supports both calls?
- def log(msg, *dest):
- def log(msg, dest=None): Correct answer.
- def log(msg, dest):
- def log(msg, **dest):
Explanation
Giving dest a default value of None makes the parameter optional, so log('started') and log('started', '/tmp/x') both succeed. The function body can then branch on whether dest is None. Required parameters without defaults must be supplied by every caller.
Question 38Python programming fundamentals and scripting for IT tasks
A script builds a report from a list of log entries and must join them into a single string separated by newlines. Which expression does that?
- '\n'.join(entries) Correct answer.
- entries.join('\n')
- '\n'.split(entries)
- entries.split('\n')
Explanation
The join() method belongs to the separator string, not the list, and returns a single string with the separator placed between elements. So '\n'.join(entries) produces newline-separated text. split() performs the inverse operation.
Question 39Python programming fundamentals and scripting for IT tasks
A script iterates over a list of dictionaries and must skip entries whose 'status' is 'ok' while still processing the rest. Which statement belongs inside the loop?
- pass
- return
- break
- continue Correct answer.
Explanation
The continue statement skips the remaining body of the current iteration and moves to the next element, which is exactly the behavior needed to ignore healthy entries. break would abandon the loop entirely, and pass would do nothing and let the rest of the body run.
Question 40Python programming fundamentals and scripting for IT tasks
An automation script defines a custom exception class for failed deployments. Which base class should it inherit from so it can be raised and caught like other exceptions?
- object
- Exception Correct answer.
- BaseException
- ValueError
Explanation
User-defined exceptions should subclass Exception, which is the standard root for ordinary errors and is caught by a bare except Exception clause. Subclassing BaseException directly is discouraged because it bypasses that convention. Inheriting from object alone produces a class that raise cannot use.
Question 41Python programming fundamentals and scripting for IT tasks
A script must iterate over the keys and values of a configuration dictionary at the same time. Which loop header provides both in each iteration?
- for k in config.keys():
- for v in config.values():
- for k in config:
- for k, v in config.items(): Correct answer.
Explanation
The items() method returns a view of (key, value) pairs, and tuple unpacking in the loop header binds each pair to k and v. Iterating the dictionary directly yields only keys, and keys() and values() yield one side only. This makes items() the idiomatic choice when both are needed.
Question 42Python programming fundamentals and scripting for IT tasks
A script uses a regular expression to extract IP addresses from log lines. Which module and function are appropriate for finding all matches in a string?
- re.sub(pattern, line)
- re.match(pattern, line)
- re.compile(pattern)
- re.findall(pattern, line) Correct answer.
Explanation
re.findall() scans the entire string and returns a list of every non-overlapping match, which is what extracting multiple addresses requires. re.match() only checks the beginning of the string. re.sub() performs replacement, and re.compile() merely builds a pattern object.
Question 43Python programming fundamentals and scripting for IT tasks
A script defines a class Server with an attribute host and creates an instance with s = Server('web1'). Which expression reads the host attribute from the instance?
- Server.host(s)
- host(s)
- s.host Correct answer.
- s['host']
Explanation
Attributes set on an instance are accessed with dot notation, so s.host returns the value stored during __init__. The class name alone refers to the type, not to a particular instance's data. Bracket syntax is for dictionaries and other subscriptable objects.
Question 44Python programming fundamentals and scripting for IT tasks
A script sets a module-level variable and a function that reads it, but the function assigns to the same name and the module-level value appears unchanged after the call. What explains this?
- Module-level variables are read-only from inside functions
- Python copies module-level variables into every function call
- The function must be declared with static before assigning
- The assignment creates a local variable that shadows the module-level name Correct answer.
Explanation
When a name is assigned anywhere in a function body, Python treats that name as local for the whole function unless a global or nonlocal declaration says otherwise. The local binding shadows the module-level variable, so the outer name is unaffected. Using the global keyword would make the assignment affect the module-level value.
Question 45Python programming fundamentals and scripting for IT tasks
A script needs to convert a list of string numbers such as ['10', '20', '30'] into integers and sum them. Which expression does this in one step?
- sum(str(x) for x in values)
- sum(values)
- sum(int(x) for x in values) Correct answer.
- int(sum(values))
Explanation
A generator expression applies int() to each string, and sum() adds the resulting integers. This avoids building an intermediate list and handles the conversion and aggregation together. Passing the raw strings to sum() raises a TypeError.
Question 46Python programming fundamentals and scripting for IT tasks
A script must read a binary file, such as a compressed archive, and pass its bytes to another function. Which open() mode is correct?
- open(path, 'w')
- open(path, 'rb') Correct answer.
- open(path, 'r')
- open(path, 'rt')
Explanation
The 'b' flag opens the file in binary mode, so read() returns bytes rather than decoded text. This is required for compressed archives and other non-text data. Text mode would attempt a decode and could fail on arbitrary byte sequences.
Question 47Python programming fundamentals and scripting for IT tasks
A script needs to append a timestamp to an existing log file without erasing its current contents. Which open() call is correct?
- open(path, 'x')
- open(path, 'w')
- open(path, 'a') Correct answer.
- open(path, 'r+')
Explanation
Mode 'a' opens the file for writing and positions the write cursor at the end, so existing content is preserved. Mode 'w' truncates the file first, and 'x' fails if the file already exists. 'r+' allows writing but places the cursor at the start, overwriting existing bytes.
Question 48Python programming fundamentals and scripting for IT tasks
A script defines a function that returns the average of a list of integers, but a caller passes an empty list. Which behavior should the function author design for?
- Return 0 silently for every empty input
- Raise an explicit exception such as ValueError with a clear message Correct answer.
- Rely on the caller to never pass an empty list
- Let a ZeroDivisionError propagate from the division
Explanation
An empty list makes the sum zero and the count zero, so dividing raises ZeroDivisionError, which is a low-level implementation detail. Raising ValueError with a descriptive message tells the caller precisely what precondition was violated. Documenting and enforcing preconditions in this way is the idiomatic approach.
Question 49Python programming fundamentals and scripting for IT tasks
A script runs on a schedule and must avoid overlapping runs when a previous invocation is still working. Which approach provides a reliable guard on a single machine?
- Call time.sleep(60) before doing any work
- Compare the current time to a hard-coded start hour
- Use a lock file created atomically with os.open(path, os.O_CREAT | os.O_EXCL) and remove it when finished Correct answer.
- Check a global variable named running at the start of the script
Explanation
Creating a file with O_CREAT | O_EXCL fails if the file already exists, and the operating system performs the check atomically, so only one process can win. The lock file is removed in a finally block when the work completes. In-process variables and sleeps cannot coordinate separate processes.
Question 50Python programming fundamentals and scripting for IT tasks
A script builds a dictionary that counts occurrences of each error code in a log. Which loop body correctly increments the count whether or not the code has been seen before?
- counts[code] = counts[code] + 1
- counts.append(code)
- counts = {code: 1}
- counts[code] = counts.get(code, 0) + 1 Correct answer.
Explanation
dict.get() returns the stored count or the supplied default of 0 when the key is absent, so the expression always has an integer to increment. Assigning the result back stores the updated count. Direct indexing on a missing key would raise KeyError on the first occurrence.