🔧 Python Training - Day 3

Functions, Arrays, String Manipulation & Recursion

📊 Quick Comparison

Topic Key Idea Example
Function Reusable block def f(x): return x*2
String slice Substring via indices s[0:3]
Array method Mutate array a.append(x)

📝 Quick Quiz (5 Questions)

  1. A function that returns a value is called:
  2. Strings in Python are:
  3. Select valid slice:
  4. Recursion is:
  5. Global scope variable lives:
Answer all questions and click Submit.

🔧 Fruitful Functions

Return Values and Parameters

Functions that return a value and take parameters to perform operations.

def calculate_bandwidth(ports, speed): """Calculate total bandwidth""" return ports * speed # Usage total_bandwidth = calculate_bandwidth(48, 1000) print(f"Total bandwidth: {total_bandwidth} Mbps")

Local and Global Scope

Variables defined inside a function have local scope, while those defined outside have global scope.

# Global variable network_name = "Corporate Network" def configure_device(device_name): # Local variable local_config = f"Configuring {device_name}" print(local_config) print(f"Network: {network_name}") # Access global variable configure_device("Switch01")

Function Composition

Combining multiple functions to solve a problem.

def validate_ip(ip): """Validate IP address format""" parts = ip.split('.') return len(parts) == 4 and all(0 <= int(part) <= 255 for part in parts) def configure_interface(interface, ip): """Configure interface with IP""" if validate_ip(ip): return f"Interface {interface} configured with {ip}" else: return f"Invalid IP address: {ip}" result = configure_interface("GigabitEthernet0/1", "192.168.1.1") print(result)

Recursion

A function that calls itself to solve a problem.

def countdown(n): """Countdown using recursion""" if n <= 0: print("Network ready!") return print(f"Initializing network in {n} seconds...") countdown(n - 1) countdown(5)

📝 String Manipulation

String Slices

Extracting parts of a string using indices.

device_name = "GigabitEthernet0/1" print(device_name[0:8]) # Output: Gigabit print(device_name[8:]) # Output: Ethernet0/1 print(device_name[-3:]) # Output: 0/1

Immutability

Strings cannot be changed after they are created.

device_name = "GigabitEthernet0/1" # device_name[0] = "g" # This will raise an error # Instead, create a new string new_name = "g" + device_name[1:] print(new_name) # Output: gigabitEthernet0/1

String Methods

Built-in methods to manipulate strings.

device_name = "GigabitEthernet0/1" print(device_name.lower()) # gigabitethernet0/1 print(device_name.upper()) # GIGABITETHERNET0/1 print(device_name.replace("0/1", "0/2")) # GigabitEthernet0/2 print(device_name.startswith("Gigabit")) # True print(device_name.endswith("0/1")) # True

String Module

Additional string functionalities.

import string print(string.ascii_letters) # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ print(string.digits) # 0123456789 print(string.punctuation) # !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

📊 Python Arrays

Definition and Accessing Elements

Arrays store multiple values in a single variable.

from array import array # Create array of IP addresses ip_addresses = array('u', ['192.168.1.1', '192.168.1.2', '192.168.1.3']) # Accessing elements print(ip_addresses[0]) # 192.168.1.1 print(ip_addresses[1]) # 192.168.1.2 print(ip_addresses[2]) # 192.168.1.3

Array Methods

Built-in methods to manipulate arrays.

from array import array # Create array devices = array('u', ['SW101', 'SW102', 'SW110']) # Append an element devices.append('SW103') print(devices) # array('u', 'SW101SW102SW110SW103') # Get array length print(len(devices)) # 4 # Count occurrences print(devices.count('SW101')) # 1

🎮 Interactive Demo: Function Practice

Try different function concepts:

Function with Return Value

Enter values to calculate total bandwidth!

String Manipulation

Enter a device name to see string operations!

🔄 Recursion Deep Dive

Recursive Network Configuration

Let's see how recursion can be used for network automation tasks.

def configure_vlans(vlan_list, index=0): """Recursively configure VLANs""" if index >= len(vlan_list): print("All VLANs configured!") return vlan_id, vlan_name = vlan_list[index] print(f"Configuring VLAN {vlan_id}: {vlan_name}") configure_vlans(vlan_list, index + 1) # Usage vlans = [(10, "Management"), (20, "Data"), (30, "Voice")] configure_vlans(vlans)

Recursive Network Discovery

def discover_network(devices, current=0): """Recursively discover network devices""" if current >= len(devices): print("Network discovery complete!") return device = devices[current] print(f"Discovering {device}...") print(f" Status: Active") print(f" Ports: 48") print(f" Uptime: 99.9%") print() discover_network(devices, current + 1) # Usage network_devices = ["SW101", "SW102", "SW110", "R101"] discover_network(network_devices)

🌐 Scope and Variable Lifetime

Understanding Variable Scope

# Global scope network_config = { "name": "Corporate Network", "vlan_count": 0 } def add_vlan(vlan_id, vlan_name): # Local scope local_vlan = { "id": vlan_id, "name": vlan_name } # Modify global variable global network_config network_config["vlan_count"] += 1 print(f"Added VLAN: {local_vlan}") print(f"Total VLANs: {network_config['vlan_count']}") return local_vlan # Test scope vlan1 = add_vlan(10, "Management") vlan2 = add_vlan(20, "Data") print(f"Network config: {network_config}")

🎮 Interactive Demo: Complete Network Automation

Run the complete network automation script:

Click a button to see the automation scripts in action!

📚 Summary

This guide covers essential Python concepts of fruitful functions, string manipulation, and array handling with practical examples related to network automation.

Key Concepts Covered:

  • Functions: Return values, parameters, scope, composition, recursion
  • Strings: Slicing, immutability, methods, string module
  • Arrays: Creation, accessing elements, array methods
  • Recursion: Self-calling functions for complex problems

Best Practices:

  • Use meaningful function names and docstrings
  • Keep functions focused on a single task
  • Be careful with recursion depth
  • Understand variable scope

▶️ Run the code (Python in your browser)

Execute Python below using Pyodide. Edit the code and click Run.

Initializing Python runtime...

🎥 Video Lesson

© NexIQ AI Automation Pvt Ltd | https://nexiq.netlify.app/ | hr@nexiq.in