DevNet Associate (DEVASC) v1.0Software Development and DesignEasy
A network engineer is writing a Python script to automate the configuration of multiple devices. They need to define a reusable block of code that takes device credentials and configuration commands as input, connects to a device, applies the commands, and then disconnects. This block of code will be called multiple times with different inputs. Which Python construct is most appropriate for encapsulating this reusable logic?
- AA loop
- BA function
- CA module
- DA class
Show answer & explanationAnswer & explanation
Correct answer: B. A function
A function is a block of organized, reusable code that is used to perform a single, related action. It can take inputs (arguments) and return outputs, making it ideal for encapsulating specific tasks that need to be called multiple times.
Why the other options are wrong
- A. A loop is used for repetitive execution of code, but it doesn't encapsulate a distinct, callable block of logic with inputs and outputs.
- C. A module is a file containing Python definitions and statements, used for organizing related functions and classes, but not the construct for the reusable logic itself.
- D. A class is used for object-oriented programming to define objects and their behaviors, which is more complex than needed for a simple reusable block of code.
Python Function
A Python function is a block of organized, reusable code that performs a specific task. Functions improve code modularity, reusability, and readability.
- Defined using the `def` keyword.
- Can accept zero or more arguments (inputs).
- Can return a value using the `return` statement.
- Promotes the DRY (Don't Repeat Yourself) principle.
Memory trick: Functions make code flow like a well-oiled machine.