










Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Python for IT Automation — 50 Practice MCQs with Explanations
Typology: Exams
1 / 18
This page cannot be seen from the preview
Don't miss anything!











Question 1 You need to run a shell command asynchronously from Python and stream its output line-by-line as it's produced. Which approach is best?
A. subprocess.run() with capture_output=True B. subprocess.Popen() with stdout=subprocess.PIPE and reading line-by-line C. os.system() and redirecting to a file D. subprocess.call() with stdout=open('out.txt','w')
🟢 Correct answer: B
🔴 RATIONALE: subprocess.Popen() lets you stream output incrementally by reading from stdout=subprocess.PIPE as data arrives. run()/call() wait for completion before returning output.
Question 2 When parsing JSON responses from a REST API, which library and pattern is safest for handling missing keys without raising exceptions?
A. json.loads() and access dict keys directly B. json.load() and use dict.get(key, default) C. yaml.safe_load() and access keys directly D. xml.etree.ElementTree and iterate children
🟢 Correct answer: B
🔴 RATIONALE: Using dict.get(key, default) avoids KeyError when a key is missing. json.load() reads from a file, json.loads() reads from a string — both are valid, but the key safety pattern is get().
Question 3 You need to automate SSH login to multiple servers and run a command. Which Python library is most appropriate and secure?
A. paramiko B. subprocess with ssh -o StrictHostKeyChecking=no C. os.popen('ssh ...') D. requests with SSH in URL
🟢 Correct answer: A
🔴 RATIONALE: paramiko is a dedicated SSH library for Python supporting key-based auth, sessions, and secure channel management. subprocess/os.popen rely on external ssh and are less robust for automation.
Question 4 In IT automation, why is using environment variables for secrets preferred over hardcoding them?
A. It makes code faster B. It prevents secrets from being accidentally committed and allows per-environment configuration C. It removes the need for encryption D. It simplifies unit testing
🟢 Correct answer: B
🔴 RATIONALE: Environment variables keep secrets out of source code and enable per-deployment configuration, reducing risk of accidental exposure in repositories.
Question 5 Which testing approach is best for validating that an automation script correctly parses different log formats without executing external commands?
A. Unit tests with mocked data B. End-to-end tests running on real servers C. Performance tests with large datasets D. Security scans of the script
🟢 Correct answer: A
🔴 RATIONALE: Unit tests with mocked log data isolate parsing logic and validate behavior deterministically without external dependencies.
Question 6 You must ensure an automation script fails safely if a required file is missing. Which exception should you catch?
Question 9 You need to read a large CSV file line-by-line without loading the entire file into memory. Best approach?
A. pandas.read_csv() and iterate rows B. open() the file and iterate lines C. csv.reader() on the whole file content D. json.load() and parse
🟢 Correct answer: B
🔴 RATIONALE: Iterating over an open file handles line-by-line streaming efficiently without loading the full file into memory. pandas may load fully depending on usage.
Question 10 Which Ansible pattern is best for running a command only if a file's modification time changed?
A. shell with changed_when=False B. command with creates= C. shell with notify D. run_by
🟢 Correct answer: B
🔴 RATIONALE: The command module with creates=runs only if the specified file does not exist, often used to avoid re-running when a file already exists. For time-based checks, use stat + changed_when, but among choices, command with creates= is the standard conditional pattern.
Question 11 To securely store API keys for use in automation across multiple environments, which practice is best?
A. Store keys in a secrets manager and reference them via environment variables at runtime B. Hardcode keys in the script C. Store keys in a README D. Paste keys into the script when running
🟢 Correct answer: A
🔴 RATIONALE: Secrets managers protect keys and allow runtime injection without exposing them in code or config files.
Question 12 When automating backups, which approach ensures you can restore to a known point if the latest backup fails?
A. Overwrite the previous backup every run B. Keep versioned backups with timestamps and verify integrity C. Compress backups to a single file without versions D. Delete old backups immediately
🟢 Correct answer: B
🔴 RATIONALE: Versioned backups with timestamps and integrity checks allow restoration to prior successful states if the latest backup is corrupted.
Question 13 Which Python module provides functions for interacting with the operating system’s environment, including environment variables?
A. os B. sys C. pathlib D. json
🟢 Correct answer: A
🔴 RATIONALE: os.environ provides access to environment variables and os offers many OS interaction functions.
Question 14 You need to validate that a user-provided string is a valid IPv4 address. Best approach?
A. Use regex to match four 0–255 numbers separated by dots B. Use ipaddress.IPv4Address() and catch ValueError C. Split by '.' and check len == 4 D. Use str.isnumeric()
🟢 Correct answer: B
🔴 RATIONALE: 201 Created indicates successful resource creation. 200 is generic success; 204 is No Content; 400 is client error.
Question 18 Which Python construct is best for retrying a network request with exponential backoff?
A. for loop with time.sleep() B. while loop with retry counter and time.sleep(backoff) C. try...except without sleep D. recursive function with no sleep
🟢 Correct answer: B
🔴 RATIONALE: A while loop with a retry counter and increasing sleep durations implements exponential backoff cleanly and avoids unbounded recursion.
Question 19 You need to parse a log file with timestamps in ISO 8601 format. Which function is best?
A. datetime.strptime(ts, "%Y-%m-%d %H:%M:%S") B. datetime.fromisoformat(ts) C. time.strptime(ts, "%c") D. parse(ts) from dateutil without import
🟢 Correct answer: B
🔴 RATIONALE: datetime.fromisoformat() is designed for ISO 8601 strings and is simpler and more robust than custom strptime patterns.
Question 20 Which practice ensures automation scripts are reproducible across environments?
A. Hardcoding paths and versions B. Using a requirements.txt and virtual environment C. Installing packages globally D. Skipping dependency management
🟢 Correct answer: B
🔴 RATIONALE: requirements.txt + venv pins dependencies and ensures consistent installs across environments.
Question 21 When writing automation that modifies production systems, what is the most important safety step before running?
A. Run at midnight B. Test in a non-production environment and have a rollback plan C. Disable logging D. Use sudo for everything
🟢 Correct answer: B
🔴 RATIONALE: Testing in non-production and having a rollback plan minimizes risk of accidental damage to production systems.
Question 22 Which Python feature helps prevent accidental modification of shared configuration data passed to functions?
A. Passing mutable objects B. Using tuples or copying data before modification C. Using global variables D. Using classes without _init _
🟢 Correct answer: B
🔴 RATIONALE: Tuples are immutable; copying data before modification prevents accidental shared-state changes.
🔴 RATIONALE: INFO to stdout for operational visibility and ERROR to a separate file with rotation enables monitoring and post-failure analysis without overwhelming logs.
Question 26 When automating DNS updates, what is the most critical compliance consideration?
A. Use the fastest TTL B. Ensure changes are authorized, logged, and reversible per policy C. Bypass approval for speed D. Use hardcoded credentials
🟢 Correct answer: B
🔴 RATIONALE: Authorization, logging, and reversibility are core compliance requirements for infrastructure changes to prevent unauthorized or untracked modifications.
Question 27 Which Python pattern avoids resource leaks when working with files?
A. file = open(...); read(); (no close) B. with open(...) as f: ... C. open() in a global variable D. os.open() without os.close()
🟢 Correct answer: B
🔴 RATIONALE: The with statement ensures the file is closed automatically, preventing resource leaks even if exceptions occur.
Question 28 You must validate that an automation script doesn't accidentally delete user data. Which check is best?
A. Add a --force flag B. Require explicit confirmation and implement a whitelist of allowed paths C. Remove all checks for speed D. Use sudo for all deletions
🟢 Correct answer: B
🔴 RATIONALE: Explicit confirmation plus whitelisting paths prevents accidental deletion of unintended data and enforces safety controls.
Question 29 Which HTTP header is commonly used to send an API key securely?
A. Content-Type B. Authorization C. Accept D. User-Agent
🟢 Correct answer: B
🔴 RATIONALE: The Authorization header is the standard place for API credentials (e.g., token or API key).
Question 30 In automation, what is the main reason to use parameterized tests?
A. To make tests run slower B. To cover multiple input scenarios with a single test function C. To remove the need for assertions D. To avoid writing tests
🟢 Correct answer: B
🔴 RATIONALE: Parameterized tests allow running the same test logic with many inputs, increasing coverage succinctly.
Question 31 Which approach is best for handling timezones in automation that spans multiple regions?
A. Use local time everywhere B. Store and compare times in UTC and convert to local only for display C. Hardcode timezone strings D. Ignore timezones
🟢 Correct answer: B
🔴 RATIONALE: Least privilege limits the impact of a compromised script and reduces escalation opportunities.
Question 35 You need to automate a cron-like job that runs every 5 minutes. Best approach on Linux?
A. crontab with /5 * * * B. Windows Task Scheduler only C. Run a manual loop in a terminal D. Use systemd unit with OnActiveSec only
🟢 Correct answer: A
🔴 RATIONALE: cron with /5 * * * schedules a job every 5 minutes reliably on Linux.
Question 36 Which exception is raised when a dictionary key is missing and accessed directly?
A. FileNotFoundError B. KeyError C. ValueError D. IndexError
🟢 Correct answer: B
🔴 RATIONALE: KeyError occurs when accessing a missing dict key without using get().
Question 37 When automating user account creation, what is an ethical requirement?
A. Create accounts without consent B. Ensure consent, authorization, and audit logging for account changes C. Skip password policies D. Use default passwords
🟢 Correct answer: B
🔴 RATIONALE: Ethical automation requires authorization, consent where applicable, and auditability to prevent unauthorized changes.
Question 38 Which pattern is best for safely handling JSON responses that may be malformed?
A. json.loads(response) and ignore errors B. json.loads(response) inside try...except json.JSONDecodeError C. eval(response) D. xml.etree.parse(response)
🟢 Correct answer: B
🔴 RATIONALE: Wrapping json.loads() in try...except JSONDecodeError handles malformed JSON gracefully.
Question 39 You need to ensure automation logs are tamper-evident for compliance. Best approach?
A. Store logs in a shared folder B. Write logs to an immutable, signed, or WORM storage with rotation C. Delete old logs immediately D. Encrypt logs but allow editing
🔴 RATIONALE: Immutable or signed storage (WORM) provides tamper-evidence required for compliance audits.
🟢 Correct answer: B
Question 40 Which Python module is best for working with paths in a platform-independent way?
A. os B. pathlib C. sys D. glob
🟢 Correct answer: A
🔴 RATIONALE: smtplib supports TLS and MIME for secure email with attachments.
Question 44 Which practice ensures automation changes are auditable?
A. Run scripts without logging B. Record who ran what, when, and the parameters used, and store logs centrally C. Skip version control D. Use hardcoded credentials
🟢 Correct answer: B
🔴 RATIONALE: Auditing requires logging identity, timestamp, inputs, and central storage for traceability.
Question 45 When writing a script that modifies production databases, what is the safest transactional approach?
A. Run statements directly without transactions B. Use transactions with explicit commit and rollback on error C. Use auto-commit for all changes D. Disable constraints
🟢 Correct answer: B
🔴 RATIONALE: Transactions with explicit commit/rollback ensure changes are atomic and can be reverted if errors occur.
Question 46 Which Python pattern prevents accidental global state changes?
A. Use global variables extensively B. Pass needed data as arguments and avoid modifying globals C. Modify module-level dicts directly D. Skip function parameters
🟢 Correct answer: B
🔴 RATIONALE: Avoiding globals and passing data explicitly reduces unintended side effects and makes behavior predictable.
Question 47 You need to automate rotating secrets in a vault. Which property is essential?
A. Secrets are rotatable with minimal downtime and old versions are retained briefly for rollback B. Secrets are never changed C. Old secrets are deleted immediately D. No audit log for rotations
🟢 Correct answer: A
🔴 RATIONALE: Safe rotation requires minimal downtime and retaining old versions briefly for rollback if needed.
Question 48 Which HTTP method is used to update an existing resource idempotently?
🟢 Correct answer: C
🔴 RATIONALE: PUT is idempotent and used to update/replace an existing resource by ID.
Question 49 When automating across multiple cloud providers, what design principle reduces complexity?
A. Hardcode provider-specific logic in one script B. Use an abstraction layer or provider-neutral interface C. Run provider scripts sequentially without isolation D. Use one global credential for all providers