diff --git a/Day-06/02-Assignment/Questions/assignment.md b/Day-06/02-Assignment/01-Questions/assignment.md similarity index 100% rename from Day-06/02-Assignment/Questions/assignment.md rename to Day-06/02-Assignment/01-Questions/assignment.md diff --git a/Day-06/02-Assignment/Answers/task-01-answer.py b/Day-06/02-Assignment/02-Answers/task-01-answer.py similarity index 100% rename from Day-06/02-Assignment/Answers/task-01-answer.py rename to Day-06/02-Assignment/02-Answers/task-01-answer.py diff --git a/Day-06/02-Assignment/Answers/task-02-answer.py b/Day-06/02-Assignment/02-Answers/task-02-answer.py similarity index 100% rename from Day-06/02-Assignment/Answers/task-02-answer.py rename to Day-06/02-Assignment/02-Answers/task-02-answer.py diff --git a/Day-06/02-Assignment/Answers/task-03-answer.py b/Day-06/02-Assignment/02-Answers/task-03-answer.py similarity index 100% rename from Day-06/02-Assignment/Answers/task-03-answer.py rename to Day-06/02-Assignment/02-Answers/task-03-answer.py diff --git a/Day-06/02-Assignment/Answers/task-04-answer.py b/Day-06/02-Assignment/02-Answers/task-04-answer.py similarity index 100% rename from Day-06/02-Assignment/Answers/task-04-answer.py rename to Day-06/02-Assignment/02-Answers/task-04-answer.py diff --git a/Day-06/02-Assignment/Answers/task-05-answer.py b/Day-06/02-Assignment/02-Answers/task-05-answer.py similarity index 100% rename from Day-06/02-Assignment/Answers/task-05-answer.py rename to Day-06/02-Assignment/02-Answers/task-05-answer.py diff --git a/Day-08/01-Notes/01-list.md b/Day-08/01-Notes/01-list.md new file mode 100644 index 00000000..817edf8c --- /dev/null +++ b/Day-08/01-Notes/01-list.md @@ -0,0 +1,60 @@ +# Understanding Lists and List Data Structure + +## What is a List? +A list is a fundamental data structure in programming that allows you to store a collection of items. Lists are ordered and can contain elements of various data types, such as numbers, strings, and objects. + +## Creating Lists +You can create a list in various programming languages. In Python, for example, you create a list using square brackets: +```python +my_list = [1, 2, 3, 'apple', 'banana'] +``` + +## List Indexing +List elements are indexed, starting from 0 for the first element. You can access elements by their index. +```python +first_element = my_list[0] # Access the first element (1) +``` + +## List Length +You can find the length of a list using the `len()` function. +```python +list_length = len(my_list) # Length of the list (5) +``` + +# List Manipulation and Common List Operations + +## Appending to a List +You can add elements to the end of a list using the `append()` method. +```python +my_list.append(4) # Adds 4 to the end of the list +``` + +## Removing from a List +You can remove elements by their value using the `remove()` method. +```python +my_list.remove('apple') # Removes 'apple' from the list +``` + +## Slicing a List +Slicing allows you to create a new list from a subset of the original list. +```python +subset = my_list[1:4] # Creates a new list with elements at index 1, 2, and 3 +``` + +## Concatenating Lists +You can combine two or more lists to create a new list. +```python +new_list = my_list + [5, 6] # Concatenates my_list with [5, 6] +``` + +## Sorting a List +You can sort a list in ascending or descending order using the `sort()` method. +```python +my_list.sort() # Sorts the list in ascending order +``` + +## Checking for an Element +You can check if an element exists in a list using the `in` keyword. +```python +is_present = 'banana' in my_list # Checks if 'banana' is in the list (True) +``` diff --git a/Day-08/01-Notes/02-tuple.md b/Day-08/01-Notes/02-tuple.md new file mode 100644 index 00000000..527e1ad0 --- /dev/null +++ b/Day-08/01-Notes/02-tuple.md @@ -0,0 +1,58 @@ +# Understanding Tuples + +## What is a Tuple? +A tuple is a data structure similar to a list, but unlike lists, tuples are immutable, meaning their contents cannot be changed after creation. Tuples are typically used for grouping related data. + +## Creating Tuples +You can create a tuple in various programming languages. In Python, for example, you create a tuple using parentheses: +```python +my_tuple = (1, 2, 'apple', 'banana') +``` + +## Tuple Indexing +Tuple elements are indexed, starting from 0 for the first element. You can access elements by their index, just like lists. +```python +first_element = my_tuple[0] # Access the first element (1) +``` + +## Tuple Length +You can find the length of a tuple using the `len()` function. +```python +tuple_length = len(my_tuple) # Length of the tuple (4) +``` + +# Common Tuple Operations + +## Accessing Tuple Elements +Tuples are immutable, so you can only access their elements. +```python +second_element = my_tuple[1] # Access the second element (2) +``` + +## Tuple Packing and Unpacking +You can pack multiple values into a tuple and unpack them into separate variables. +```python +coordinates = (3, 4) +x, y = coordinates # Unpack the tuple into x and y (x=3, y=4) +``` + +## Concatenating Tuples +You can concatenate two or more tuples to create a new tuple. +```python +new_tuple = my_tuple + (3.14, 'cherry') # Concatenates my_tuple with a new tuple +``` + +## Checking for an Element +You can check if an element exists in a tuple using the `in` keyword. +```python +is_present = 'apple' in my_tuple # Checks if 'apple' is in the tuple (True) +``` + +## Using Tuples for Multiple Return Values +Tuples are often used to return multiple values from a function. +```python +def get_coordinates(): + return (3, 4) + +x, y = get_coordinates() # Unpack the returned tuple (x=3, y=4) +``` \ No newline at end of file diff --git a/Day-08/01-Notes/03-list-vs-tuple.md b/Day-08/01-Notes/03-list-vs-tuple.md new file mode 100644 index 00000000..dc77c02a --- /dev/null +++ b/Day-08/01-Notes/03-list-vs-tuple.md @@ -0,0 +1,58 @@ +# Differences Between Tuples and Lists + +Tuples and lists are both common data structures used in programming, but they have some fundamental differences that make them suitable for different purposes. Let's explore these differences: + +## 1. Mutability + +**List:** Lists are mutable, meaning their elements can be added, removed, or modified after creation. You can use methods like `append()`, `remove()`, and `pop()` to change the contents of a list. + +**Tuple:** Tuples are immutable, and once created, their elements cannot be changed, added, or removed. You can't use methods to modify the tuple. + +## 2. Syntax + +**List:** Lists are created using square brackets `[ ]`. Elements are separated by commas. + +```python +my_list = [1, 2, 3, 'apple', 'banana'] +``` + +**Tuple:** Tuples are created using parentheses `( )`. Elements are also separated by commas. + +```python +my_tuple = (1, 2, 'apple', 'banana') +``` + +## 3. Performance + +**List:** Lists may have slightly slower performance compared to tuples because they are mutable. Modifying a list requires memory reallocation, which can be slower for large lists. + +**Tuple:** Tuples have better performance, especially for read-only operations, because of their immutability. They do not require memory reallocation. + +## 4. Use Cases + +**List:** Lists are used when you need a collection of elements that can change, such as a dynamic list of items or data that needs to be modified. + +**Tuple:** Tuples are used when you need an ordered collection of elements that should not change, such as representing a point in 2D space (x, y), or when you want to ensure the integrity of the data. + +## 5. Iteration + +**List:** You can use a for loop or other iteration methods to iterate over the elements of a list. + +```python +for item in my_list: + # Process each item +``` + +**Tuple:** You can iterate over the elements of a tuple in the same way as lists using a for loop. + +```python +for item in my_tuple: + # Process each item +``` + +## 6. Memory Usage + +**List:** Lists generally consume more memory than tuples because they need to store additional information to support their mutability. + +**Tuple:** Tuples consume less memory because they are immutable, and the interpreter can optimize memory usage. + diff --git a/Day-08/01-Notes/04-faq.md b/Day-08/01-Notes/04-faq.md new file mode 100644 index 00000000..1db09f25 --- /dev/null +++ b/Day-08/01-Notes/04-faq.md @@ -0,0 +1,52 @@ +**Q1: What is a list in Python, and how is it used in DevOps?** + +*Answer:* +A list in Python is a collection of ordered and mutable elements. In DevOps, lists are often used to manage and manipulate data, such as configurations, server names, and deployment targets. For example, you can use a list to store a list of servers that need to be provisioned or configured. + +**Q2: How do you create a list in Python, and can you provide an example related to DevOps?** + +*Answer:* +In Python, you create a list using square brackets `[]`. Here's an example related to DevOps: + +```python +servers = ['web-server-01', 'db-server-01', 'app-server-01'] +``` + +This list can be used to represent a list of servers in a DevOps environment. + +**Q3: What is the difference between a list and a tuple in Python, and when would you choose one over the other in a DevOps context?** + +*Answer:* +The key difference is mutability; lists are mutable, while tuples are immutable. In DevOps, if you need a collection of items that won't change (e.g., server configurations, deployment steps), you would use a tuple. If the data can change (e.g., a list of active servers, configuration settings that may be updated), you would use a list. + +**Q4: How can you access elements in a list, and provide a DevOps-related example?** + +*Answer:* +You can access elements in a list by using their index. In a DevOps context, if you have a list of server names and want to access the first server, you would do the following: + +```python +servers = ['web-server-01', 'db-server-01', 'app-server-01'] +first_server = servers[0] +``` + +**Q5: How do you add an element to the end of a list in Python? Provide a DevOps example.** + +*Answer:* +You can add an element to the end of a list using the `append()` method. In DevOps, if you want to add a new server to a list of servers, you can do this: + +```python +servers = ['web-server-01', 'db-server-01'] +servers.append('app-server-01') +``` + +Now, `servers` will contain 'app-server-01'. + +**Q6: How can you remove an element from a list in Python, and can you provide a DevOps use case?** + +*Answer:* +You can remove an element from a list using the `remove()` method. In a DevOps use case, you might want to remove a server from a list of servers that are no longer needed: + +```python +servers = ['web-server-01', 'db-server-01', 'app-server-01'] +servers.remove('db-server-01') +``` \ No newline at end of file diff --git a/Day-08/02-Assigment/01-list-questions.md b/Day-08/02-Assigment/01-list-questions.md new file mode 100644 index 00000000..8ca5ea75 --- /dev/null +++ b/Day-08/02-Assigment/01-list-questions.md @@ -0,0 +1,14 @@ +# Basic-Level List Questions + +**Q1: What is a list in Python, and how is it used in DevOps?** + +**Q2: How do you create a list in Python, and can you provide an example related to DevOps?** + +**Q3: What is the difference between a list and a tuple in Python, and when would you choose one over the other in a DevOps context?** + +**Q4: How can you access elements in a list, and provide a DevOps-related example?** + +**Q5: How do you add an element to the end of a list in Python? Provide a DevOps example.** + +**Q6: How can you remove an element from a list in Python, and can you provide a DevOps use case?** + diff --git a/Day-08/02-Assigment/02-list-answers.md b/Day-08/02-Assigment/02-list-answers.md new file mode 100644 index 00000000..fe056819 --- /dev/null +++ b/Day-08/02-Assigment/02-list-answers.md @@ -0,0 +1,34 @@ +# Basic-Level List Answers + +**Q1: What is a list in Python, and how is it used in DevOps?** +A list in Python is a collection of ordered and mutable elements. In DevOps, lists are often used to manage and manipulate data, such as configurations, server names, and deployment targets. For example, you can use a list to store a list of servers that need to be provisioned or configured. + +**Q2: How do you create a list in Python, and can you provide an example related to DevOps?** +In Python, you create a list using square brackets `[]`. Here's an example related to DevOps: +```python +servers = ['web-server-01', 'db-server-01', 'app-server-01'] +``` + +**Q3: What is the difference between a list and a tuple in Python, and when would you choose one over the other in a DevOps context?** +The key difference is mutability; lists are mutable, while tuples are immutable. In DevOps, if you need a collection of items that won't change (e.g., server configurations, deployment steps), you would use a tuple. If the data can change (e.g., a list of active servers, configuration settings that may be updated), you would use a list. + +**Q4: How can you access elements in a list, and provide a DevOps-related example?** +You can access elements in a list by using their index. In a DevOps context, if you have a list of server names and want to access the first server, you would do the following: +```python +servers = ['web-server-01', 'db-server-01', 'app-server-01'] +first_server = servers[0] +``` + +**Q5: How do you add an element to the end of a list in Python? Provide a DevOps example.** +You can add an element to the end of a list using the `append()` method. In DevOps, if you want to add a new server to a list of servers, you can do this: +```python +servers = ['web-server-01', 'db-server-01'] +servers.append('app-server-01') +``` + +**Q6: How can you remove an element from a list in Python, and can you provide a DevOps use case?** +You can remove an element from a list using the `remove()` method. In a DevOps use case, you might want to remove a server from a list of servers that are no longer needed: +```python +servers = ['web-server-01', 'db-server-01', 'app-server-01'] +servers.remove('db-server-01') +``` \ No newline at end of file diff --git a/Day-08/README.md b/Day-08/README.md index e69de29b..3179cb44 100644 --- a/Day-08/README.md +++ b/Day-08/README.md @@ -0,0 +1 @@ +# Lists and Tuples \ No newline at end of file diff --git a/Day-09/01-loops.md b/Day-09/01-loops.md new file mode 100644 index 00000000..b9fdb002 --- /dev/null +++ b/Day-09/01-loops.md @@ -0,0 +1,66 @@ +# Loops in Python (for and while) + +## Introduction + +Loops are a fundamental concept in programming, and they allow you to perform repetitive tasks efficiently. In Python, there are two primary types of loops: "for" and "while." + +## For Loop + +The "for" loop is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a set of statements for each item in the sequence. The loop continues until all items in the sequence have been processed. + +**Syntax:** + +```python +for variable in sequence: + # Code to be executed for each item in the sequence +``` + +**Example:** + +```python +fruits = ["apple", "banana", "cherry"] +for fruit in fruits: + print(fruit) +``` + +**Output:** + +``` +apple +banana +cherry +``` + +In this example, the loop iterates over the "fruits" list, and in each iteration, the "fruit" variable takes on the value of the current item in the list. + +#### While Loop + +The "while" loop continues to execute a block of code as long as a specified condition is true. It's often used when you don't know in advance how many times the loop should run. + +**Syntax:** + +```python +while condition: + # Code to be executed as long as the condition is true +``` + +**Example:** + +```python +count = 0 +while count < 5: + print(count) + count += 1 +``` + +**Output:** + +``` +0 +1 +2 +3 +4 +``` + +In this example, the "while" loop continues to execute as long as the "count" is less than 5. The "count" variable is incremented in each iteration. diff --git a/Day-09/02-loop-controls.md b/Day-09/02-loop-controls.md new file mode 100644 index 00000000..1f522e20 --- /dev/null +++ b/Day-09/02-loop-controls.md @@ -0,0 +1,83 @@ +# Loop Control Statements (break and continue) + +## Introduction + +Loop control statements are used to modify the behavior of loops, providing greater control and flexibility during iteration. In Python, two primary loop control statements are "break" and "continue." + +## `break` Statement + +The "break" statement is used to exit the loop prematurely. It can be applied to both "for" and "while" loops, allowing you to terminate the loop when a particular condition is met. + +**Example:** + +```python +numbers = [1, 2, 3, 4, 5] +for number in numbers: + if number == 3: + break + print(number) +``` + +**Output:** + +``` +1 +2 +``` + +In this example, the loop stops when it encounters the number 3. + +## `continue` Statement + +The "continue" statement is used to skip the current iteration of the loop and proceed to the next one. It can be used in both "for" and "while" loops, enabling you to bypass certain iterations based on a condition. + +**Example:** + +```python +numbers = [1, 2, 3, 4, 5] +for number in numbers: + if number == 3: + continue + print(number) +``` + +**Output:** + +``` +1 +2 +4 +5 +``` + +In this example, the loop skips the iteration where the number is 3 and continues with the next iteration. + +## Practice Exercise - Automating Log File Analysis + +#### Introduction + +In this practice exercise, we use a "for" loop to automate the analysis of a log file and identify lines containing the word "error." This demonstrates how loops can be used to process data and extract relevant information efficiently. + +**Example:** + +```python +log_file = [ + "INFO: Operation successful", + "ERROR: File not found", + "DEBUG: Connection established", + "ERROR: Database connection failed", +] + +for line in log_file: + if "ERROR" in line: + print(line) +``` + +**Output:** + +``` +ERROR: File not found +ERROR: Database connection failed +``` + +In this exercise, the loop iterates through the "log_file" list and prints lines containing the word "ERROR." \ No newline at end of file diff --git a/Day-09/03-for-loop-devops-usecases.md b/Day-09/03-for-loop-devops-usecases.md new file mode 100644 index 00000000..cf3bb412 --- /dev/null +++ b/Day-09/03-for-loop-devops-usecases.md @@ -0,0 +1,67 @@ +# For Loop DevOps use-cases + +1. **Server Provisioning and Configuration:** + + DevOps engineers use "for" loops when provisioning multiple servers or virtual machines with the same configuration. For example, when setting up monitoring agents on multiple servers: + + ```bash + servers=("server1" "server2" "server3") + for server in "${servers[@]}"; do + configure_monitoring_agent "$server" + done + ``` + +2. **Deploying Configurations to Multiple Environments:** + + When deploying configurations to different environments (e.g., development, staging, production), DevOps engineers can use a "for" loop to apply the same configuration changes to each environment: + + ```bash + environments=("dev" "staging" "prod") + for env in "${environments[@]}"; do + deploy_configuration "$env" + done + ``` + +3. **Backup and Restore Operations:** + + Automating backup and restore operations is a common use case. DevOps engineers can use "for" loops to create backups for multiple databases or services and later restore them as needed. + + ```bash + databases=("db1" "db2" "db3") + for db in "${databases[@]}"; do + create_backup "$db" + done + ``` + +4. **Log Rotation and Cleanup:** + + DevOps engineers use "for" loops to manage log files, rotate logs, and clean up older log files to save disk space. + + ```bash + log_files=("app.log" "access.log" "error.log") + for log_file in "${log_files[@]}"; do + rotate_and_cleanup_logs "$log_file" + done + ``` + +5. **Monitoring and Reporting:** + + In scenarios where you need to gather data or perform checks on multiple systems, a "for" loop is handy. For example, monitoring server resources across multiple machines: + + ```bash + servers=("server1" "server2" "server3") + for server in "${servers[@]}"; do + check_resource_utilization "$server" + done + ``` + +6. **Managing Cloud Resources:** + + When working with cloud infrastructure, DevOps engineers can use "for" loops to manage resources like virtual machines, databases, and storage across different cloud providers. + + ```bash + instances=("instance1" "instance2" "instance3") + for instance in "${instances[@]}"; do + resize_instance "$instance" + done + ``` diff --git a/Day-09/04-while-loop-devops-usecases.md b/Day-09/04-while-loop-devops-usecases.md new file mode 100644 index 00000000..c0736b2c --- /dev/null +++ b/Day-09/04-while-loop-devops-usecases.md @@ -0,0 +1,66 @@ +# While Loop DevOps Usecases + +DevOps engineers often use "while" loops in various real-time use cases to automate, monitor, and manage infrastructure and deployments. Here are some practical use cases from a DevOps engineer's perspective: + +1. **Continuous Integration/Continuous Deployment (CI/CD) Pipeline:** + + DevOps engineers often use "while" loops in CI/CD pipelines to monitor the deployment status of applications. They can create a "while" loop that periodically checks the status of a deployment or a rolling update until it completes successfully or fails. For example, waiting for a certain number of pods to be ready in a Kubernetes deployment: + + ```bash + while kubectl get deployment/myapp | grep -q 0/1; do + echo "Waiting for myapp to be ready..." + sleep 10 + done + ``` + +2. **Provisioning and Scaling Cloud Resources:** + + When provisioning or scaling cloud resources, DevOps engineers may use "while" loops to wait for the resources to be fully provisioned and ready. For instance, waiting for an Amazon EC2 instance to become available: + + ```bash + while ! aws ec2 describe-instance-status --instance-ids i-1234567890abcdef0 | grep -q "running"; do + echo "Waiting for the EC2 instance to be running..." + sleep 10 + done + ``` + +3. **Log Analysis and Alerting:** + + DevOps engineers can use "while" loops to continuously monitor logs for specific events or errors and trigger alerts when a certain condition is met. For example, tailing a log file and alerting when an error is detected: + + ```bash + while true; do + if tail -n 1 /var/log/app.log | grep -q "ERROR"; then + send_alert "Error detected in the log." + fi + sleep 5 + done + ``` + +4. **Database Replication and Data Synchronization:** + + DevOps engineers use "while" loops to monitor database replication and ensure data consistency across multiple database instances. The loop can check for replication lag and trigger corrective actions when necessary. + + ```bash + while true; do + replication_lag=$(mysql -e "SHOW SLAVE STATUS\G" | grep "Seconds_Behind_Master" | awk '{print $2}') + if [ "$replication_lag" -gt 60 ]; then + trigger_data_sync + fi + sleep 60 + done + ``` + +5. **Service Health Monitoring and Auto-Recovery:** + + DevOps engineers can use "while" loops to continuously check the health of services and automatically trigger recovery actions when services become unhealthy. + + ```bash + while true; do + if ! check_service_health; then + restart_service + fi + sleep 30 + done + ``` + diff --git a/Day-09/README.md b/Day-09/README.md index e69de29b..d31a16aa 100644 --- a/Day-09/README.md +++ b/Day-09/README.md @@ -0,0 +1 @@ +# Loops \ No newline at end of file diff --git a/Day-10/01-convert-string-to-list.py b/Day-10/01-convert-string-to-list.py new file mode 100644 index 00000000..c3a6e442 --- /dev/null +++ b/Day-10/01-convert-string-to-list.py @@ -0,0 +1 @@ +folder_paths = input("Enter a list of folder paths separated by spaces: ").split() \ No newline at end of file diff --git a/Day-10/02-main-construct.py b/Day-10/02-main-construct.py new file mode 100644 index 00000000..95a84c5d --- /dev/null +++ b/Day-10/02-main-construct.py @@ -0,0 +1,10 @@ +def main(): + folder_paths = input("Enter a list of folder paths separated by spaces: ").split() + print(folder_paths) + + # Print elements in the list + #for folder_path in folder_paths: + # print(folder_path) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/Day-10/03-list-files-in-folders.py b/Day-10/03-list-files-in-folders.py new file mode 100644 index 00000000..7710c4bb --- /dev/null +++ b/Day-10/03-list-files-in-folders.py @@ -0,0 +1,25 @@ +import os + +def list_files_in_folder(folder_path): + try: + files = os.listdir(folder_path) + return files, None + except FileNotFoundError: + return None, "Folder not found" + except PermissionError: + return None, "Permission denied" + +def main(): + folder_paths = input("Enter a list of folder paths separated by spaces: ").split() + + for folder_path in folder_paths: + files, error_message = list_files_in_folder(folder_path) + if files: + print(f"Files in {folder_path}:") + for file in files: + print(file) + else: + print(f"Error in {folder_path}: {error_message}") + +if __name__ == "__main__": + main() diff --git a/Day-10/README.md b/Day-10/README.md index e69de29b..c85d0b1a 100644 --- a/Day-10/README.md +++ b/Day-10/README.md @@ -0,0 +1 @@ +# Lists Part-2 \ No newline at end of file diff --git a/Day-11/01-dictionaries.md b/Day-11/01-dictionaries.md new file mode 100644 index 00000000..baedd1f0 --- /dev/null +++ b/Day-11/01-dictionaries.md @@ -0,0 +1,37 @@ +# Dictionaries + +## Overview: +A dictionary in Python is a data structure that allows you to store and retrieve values using keys. It is also known as a hashmap or associative array in other programming languages. Dictionaries are implemented as hash tables, providing fast access to values based on their keys. + +## Creating a Dictionary: +```python +my_dict = {'name': 'John', 'age': 25, 'city': 'New York'} +``` + +## Accessing Values: +```python +print(my_dict['name']) # Output: John +``` + +## Modifying and Adding Elements: +```python +my_dict['age'] = 26 # Modifying a value +my_dict['occupation'] = 'Engineer' # Adding a new key-value pair +``` + +## Removing Elements: +```python +del my_dict['city'] # Removing a key-value pair +``` + +## Checking Key Existence: +```python +if 'age' in my_dict: + print('Age is present in the dictionary') +``` + +## Iterating Through Keys and Values: +```python +for key, value in my_dict.items(): + print(key, value) +``` \ No newline at end of file diff --git a/Day-11/02-sets.md b/Day-11/02-sets.md new file mode 100644 index 00000000..e76ea735 --- /dev/null +++ b/Day-11/02-sets.md @@ -0,0 +1,60 @@ +# Sets and Set Operations + +#### Overview: +A set in Python is an unordered collection of unique elements. It is useful for mathematical operations like union, intersection, and difference. + +#### Creating a Set: +```python +my_set = {1, 2, 3, 4, 5} +``` + +#### Adding and Removing Elements: +```python +my_set.add(6) # Adding an element +my_set.remove(3) # Removing an element +``` + +#### Set Operations: +```python +set1 = {1, 2, 3, 4} +set2 = {3, 4, 5, 6} + +union_set = set1.union(set2) # Union of sets +intersection_set = set1.intersection(set2) # Intersection of sets +difference_set = set1.difference(set2) # Difference of sets +``` + +#### Subset and Superset: +```python +is_subset = set1.issubset(set2) # Checking if set1 is a subset of set2 +is_superset = set1.issuperset(set2) # Checking if set1 is a superset of set2 +``` + +### Practice Exercises and Examples + +#### Example: Managing a Dictionary of Server Configurations and Optimizing Retrieval + +##### Scenario: +Suppose you are managing server configurations using a dictionary. + +```python +server_config = { + 'server1': {'ip': '192.168.1.1', 'port': 8080, 'status': 'active'}, + 'server2': {'ip': '192.168.1.2', 'port': 8000, 'status': 'inactive'}, + 'server3': {'ip': '192.168.1.3', 'port': 9000, 'status': 'active'} +} +``` + +##### Function for Retrieval: +```python +def get_server_status(server_name): + return server_config.get(server_name, {}).get('status', 'Server not found') +``` + +##### Example Usage: +```python +server_name = 'server2' +status = get_server_status(server_name) +print(f"{server_name} status: {status}") +``` + diff --git a/Day-11/03-lists-vs-sets.md b/Day-11/03-lists-vs-sets.md new file mode 100644 index 00000000..35e81023 --- /dev/null +++ b/Day-11/03-lists-vs-sets.md @@ -0,0 +1,92 @@ +# Lists vs. Sets + +## Lists + +- **Ordered Collection:** + - Lists are ordered collections of elements. The order in which elements are added is preserved. + - Elements can be accessed by their index. + + ```python + my_list = [1, 2, 3, 4, 5] + print(my_list[0]) # Output: 1 + ``` + +- **Mutable:** + - Lists are mutable, meaning you can modify their elements after creation. + + ```python + my_list[1] = 10 + ``` + +- **Allows Duplicate Elements:** + - Lists can contain duplicate elements. + + ```python + my_list = [1, 2, 2, 3, 4] + ``` + +- **Use Cases:** + - Use lists when you need an ordered collection with the ability to modify elements. + +## Sets + +- **Unordered Collection:** + - Sets are unordered collections of unique elements. The order in which elements are added is not preserved. + - Elements cannot be accessed by their index. + + ```python + my_set = {1, 2, 3, 4, 5} + ``` + +- **Mutable:** + - Sets are mutable, meaning you can add and remove elements after creation. + + ```python + my_set.add(6) + ``` + +- **No Duplicate Elements:** + - Sets do not allow duplicate elements. If you try to add a duplicate, it won't raise an error, but the set won't change. + + ```python + my_set = {1, 2, 2, 3, 4} # Results in {1, 2, 3, 4} + ``` + +- **Use Cases:** + - Use sets when you need an unordered collection of unique elements, and you want to perform set operations like union, intersection, and difference. + +### Common Operations: + +- **Adding Elements:** + - Lists use `append()` or `insert()` methods. + - Sets use `add()` method. + +- **Removing Elements:** + - Lists use `remove()`, `pop()`, or `del` statement. + - Sets use `remove()` or `discard()` methods. + +- **Checking Membership:** + - Lists use the `in` operator. + - Sets use the `in` operator as well, which is more efficient for sets. + +```python +# Lists +if 3 in my_list: + print("3 is in the list") + +# Sets +if 3 in my_set: + print("3 is in the set") +``` + +### Choosing Between Lists and Sets + +- **Use Lists When:** + - You need to maintain the order of elements. + - Duplicate elements are allowed. + - You need to access elements by index. + +- **Use Sets When:** + - Order doesn't matter. + - You want to ensure unique elements. + - You need to perform set operations like union, intersection, or difference. diff --git a/Day-11/04-demo-github-integration.py b/Day-11/04-demo-github-integration.py new file mode 100644 index 00000000..d6c96ff9 --- /dev/null +++ b/Day-11/04-demo-github-integration.py @@ -0,0 +1,33 @@ +# Program to demonstrate integration with GitHub to fetch the +# details of Users who created Pull requests(Active) on Kubernetes Github repo. + +import requests + +# URL to fetch pull requests from the GitHub API +url = f'https://api.github.com/repos/kubernetes/kubernetes/pulls' + +# Make a GET request to fetch pull requests data from the GitHub API +response = requests.get(url) # Add headers=headers inside get() for authentication + +# Only if the response is successful +if response.status_code == 200: + # Convert the JSON response to a dictionary + pull_requests = response.json() + + # Create an empty dictionary to store PR creators and their counts + pr_creators = {} + + # Iterate through each pull request and extract the creator's name + for pull in pull_requests: + creator = pull['user']['login'] + if creator in pr_creators: + pr_creators[creator] += 1 + else: + pr_creators[creator] = 1 + + # Display the dictionary of PR creators and their counts + print("PR Creators and Counts:") + for creator, count in pr_creators.items(): + print(f"{creator}: {count} PR(s)") +else: + print(f"Failed to fetch data. Status code: {response.status_code}") diff --git a/Day-11/04-practicals.md b/Day-11/04-practicals.md new file mode 100644 index 00000000..bfb5b9ef --- /dev/null +++ b/Day-11/04-practicals.md @@ -0,0 +1,29 @@ +# Practice Exercises and Examples + +## Example: Managing a Dictionary of Server Configurations and Optimizing Retrieval + +### Scenario: +Suppose you are managing server configurations using a dictionary. + +```python +server_config = { + 'server1': {'ip': '192.168.1.1', 'port': 8080, 'status': 'active'}, + 'server2': {'ip': '192.168.1.2', 'port': 8000, 'status': 'inactive'}, + 'server3': {'ip': '192.168.1.3', 'port': 9000, 'status': 'active'} +} +``` + +### Function for Retrieval: +```python +def get_server_status(server_name): + return server_config.get(server_name, {}).get('status', 'Server not found') +``` + +### Example Usage: +```python +server_name = 'server2' +status = get_server_status(server_name) +print(f"{server_name} status: {status}") +``` + +In this example, the function `get_server_status` optimizes the retrieval of the server status by using the `get` method and providing a default value if the server name is not found. \ No newline at end of file diff --git a/Day-11/04-practicals.py b/Day-11/04-practicals.py new file mode 100644 index 00000000..9d0aeb9e --- /dev/null +++ b/Day-11/04-practicals.py @@ -0,0 +1,15 @@ +# Server configurations dictionary +server_config = { + 'server1': {'ip': '192.168.1.1', 'port': 8080, 'status': 'active'}, + 'server2': {'ip': '192.168.1.2', 'port': 8000, 'status': 'inactive'}, + 'server3': {'ip': '192.168.1.3', 'port': 9000, 'status': 'active'} +} + +# Retrieving information +def get_server_status(server_name): + return server_config.get(server_name, {}).get('status', 'Server not found') + +# Example usage +server_name = 'server2' +status = get_server_status(server_name) +print(f"{server_name} status: {status}") diff --git a/Day-11/README.md b/Day-11/README.md index e69de29b..1ff79071 100644 --- a/Day-11/README.md +++ b/Day-11/README.md @@ -0,0 +1 @@ +# Dictionaries and Sets \ No newline at end of file diff --git a/Day-12/README.md b/Day-12/README.md deleted file mode 100644 index e69de29b..00000000 diff --git a/Day-12/server.conf b/Day-12/server.conf new file mode 100644 index 00000000..e9d46d83 --- /dev/null +++ b/Day-12/server.conf @@ -0,0 +1,17 @@ +# Server Configuration File + +# Network Settings +PORT = 8080 +MAX_CONNECTIONS=600 +TIMEOUT = 30 + +# Security Settings +SSL_ENABLED = true +SSL_CERT = /path/to/certificate.pem + +# Logging Settings +LOG_LEVEL = INFO +LOG_FILE = /var/log/server.log + +# Other Settings +ENABLE_FEATURE_X = true \ No newline at end of file diff --git a/Day-12/update_server.py b/Day-12/update_server.py new file mode 100644 index 00000000..65677891 --- /dev/null +++ b/Day-12/update_server.py @@ -0,0 +1,25 @@ +def update_server_config(file_path, key, value): + # Read the existing content of the server configuration file + with open(file_path, 'r') as file: + lines = file.readlines() + + # Update the configuration value for the specified key + with open(file_path, 'w') as file: + for line in lines: + # Check if the line starts with the specified key + if key in line: + # Update the line with the new value + file.write(key + "=" + value + "\n") + else: + # Keep the existing line as it is + file.write(line) + +# Path to the server configuration file +server_config_file = 'server.conf' + +# Key and new value for updating the server configuration +key_to_update = 'MAX_CONNECTIONS' +new_value = '600' # New maximum connections allowed + +# Update the server configuration file +update_server_config(server_config_file, key_to_update, new_value) diff --git a/Day-14/README.md b/Day-14/README.md index e69de29b..9b1a3075 100644 --- a/Day-14/README.md +++ b/Day-14/README.md @@ -0,0 +1 @@ +# Github-JIRA intergration Project \ No newline at end of file diff --git a/Day-14/examples/create-jira.py b/Day-14/examples/create-jira.py new file mode 100644 index 00000000..e9618ad0 --- /dev/null +++ b/Day-14/examples/create-jira.py @@ -0,0 +1,54 @@ +# This code sample uses the 'requests' library: +# http://docs.python-requests.org +import requests +from requests.auth import HTTPBasicAuth +import json + +url = "https://veeramallaabhishek.atlassian.net/rest/api/3/issue" + +API_TOKEN = "" + +auth = HTTPBasicAuth("", API_TOKEN) + +headers = { + "Accept": "application/json", + "Content-Type": "application/json" +} + +payload = json.dumps( { + "fields": { + "description": { + "content": [ + { + "content": [ + { + "text": "My first jira ticket", + "type": "text" + } + ], + "type": "paragraph" + } + ], + "type": "doc", + "version": 1 + }, + "project": { + "key": "AB" + }, + "issuetype": { + "id": "10006" + }, + "summary": "First JIRA Ticket", + }, + "update": {} +} ) + +response = requests.request( + "POST", + url, + data=payload, + headers=headers, + auth=auth +) + +print(json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": "))) \ No newline at end of file diff --git a/Day-14/examples/list_projects.py b/Day-14/examples/list_projects.py new file mode 100644 index 00000000..93ecf2ca --- /dev/null +++ b/Day-14/examples/list_projects.py @@ -0,0 +1,28 @@ +# This code sample uses the 'requests' library: +# http://docs.python-requests.org +import requests +from requests.auth import HTTPBasicAuth +import json + +url = "https://veeramallaabhishek.atlassian.net/rest/api/3/project" + +API_TOKEN="" + +auth = HTTPBasicAuth("", API_TOKEN) + +headers = { + "Accept": "application/json" +} + +response = requests.request( + "GET", + url, + headers=headers, + auth=auth +) + +output = json.loads(response.text) + +name = output[0]["name"] + +print(name) \ No newline at end of file diff --git a/Day-15/README.md b/Day-15/README.md index e69de29b..781a8c42 100644 --- a/Day-15/README.md +++ b/Day-15/README.md @@ -0,0 +1 @@ +# Github-JIRA intergration Project - (Part-2) \ No newline at end of file diff --git a/Day-15/examples/hello-world.py b/Day-15/examples/hello-world.py new file mode 100644 index 00000000..3d602756 --- /dev/null +++ b/Day-15/examples/hello-world.py @@ -0,0 +1,10 @@ +from flask import Flask + +app = Flask(__name__) + +@app.route('/') +def hello_world(): + return 'Hello, World!' + +if __name__ == '__main__': + app.run("0.0.0.0") diff --git a/Day-15/github-jira.py b/Day-15/github-jira.py new file mode 100644 index 00000000..c5003813 --- /dev/null +++ b/Day-15/github-jira.py @@ -0,0 +1,65 @@ +# This code sample uses the 'requests' library: +# http://docs.python-requests.org +import requests +from requests.auth import HTTPBasicAuth +import json +from flask import Flask + +app = Flask(__name__) + +# Define a route that handles GET requests +@app.route('/createJira', methods=['POST']) +def createJira(): + + url = "https://veeramallaabhishek.atlassian.net/rest/api/3/issue" + + API_TOKEN="" + + auth = HTTPBasicAuth("", API_TOKEN) + + headers = { + "Accept": "application/json", + "Content-Type": "application/json" + } + + payload = json.dumps( { + "fields": { + "description": { + "content": [ + { + "content": [ + { + "text": "Order entry fails when selecting supplier.", + "type": "text" + } + ], + "type": "paragraph" + } + ], + "type": "doc", + "version": 1 + }, + "project": { + "key": "AB" + }, + "issuetype": { + "id": "10006" + }, + "summary": "Main order flow broken", + }, + "update": {} + } ) + + + response = requests.request( + "POST", + url, + data=payload, + headers=headers, + auth=auth + ) + + return json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": ")) + +if __name__ == '__main__': + app.run(host='0.0.0.0', port=5000) \ No newline at end of file diff --git a/Day-16/README.md b/Day-16/README.md index e69de29b..d8728f2d 100644 --- a/Day-16/README.md +++ b/Day-16/README.md @@ -0,0 +1,244 @@ +# Interview Questions (Beginner and Intermediate) + +## Describe a real-world example of how you used Python to solve a DevOps challenge. + +- Here you can talk about the projects that we did in this series + - GitHub Webhooks + - JIRA integration + - File Operations + +## Discuss the challenges that you faced while using Python for DevOps and how did you overcome it. + +- Here you can mention about a challenge that you faced while implementating a Python project for DevOps that we learnt. + +## How can you secure your Python code and scripts? + +- Handle any sensetive information using Input variables, command line arguments or env vars. + +## Explain the difference between mutable and immutable objects. + +In Python, mutable objects can be altered after creation, while immutable objects cannot be changed once created. For instance: + +Mutable objects like lists can be modified: + +``` +my_list = [1, 2, 3] +my_list[0] = 0 # Modifying an element in the list +print(my_list) # Output: [0, 2, 3] +``` + +Immutable objects like tuples cannot be altered: + +``` +my_tuple = (1, 2, 3) +# Attempting to change a tuple will result in an error +# my_tuple[0] = 0 +``` + +## Differentiate between list and tuple in Python. + +Lists are mutable and typically used for storing collections of items that can be changed, while tuples are immutable and commonly used to store collections of items that shouldn't change. Examples: + +List: + +``` +my_list = [1, 2, 3] +my_list.append(4) # Modifying by adding an element +print(my_list) # Output: [1, 2, 3, 4] +``` + +Tuple: + +``` +my_tuple = (1, 2, 3) +# Attempting to modify a tuple will result in an error +# my_tuple.append(4) +``` + +## Explain the use of virtualenv. + +Virtualenv creates isolated Python environments, allowing different projects to use different versions of packages without conflicts. Example: + +Creating a virtual environment: + +### Creating a virtual environment named 'myenv' +virtualenv myenv + +Activating the virtual environment: + +### On Windows +``` +myenv\Scripts\activate +``` + +### On Unix or MacOS +``` +source myenv/bin/activate +``` + +## What are decorators in Python? + +Decorators modify the behavior of functions. They take a function as an argument, add some functionality, and return another function without modifying the original function's code. Example: + +Defining a simple decorator: + +``` +def my_decorator(func): + def wrapper(): + print("Something is happening before the function is called.") + func() + print("Something is happening after the function is called.") + return wrapper + +@my_decorator +def say_hello(): + print("Hello!") + +say_hello() +``` + +## How does exception handling work in Python? + +Exception handling in Python uses try, except, else, and finally blocks. Example: + +Handling division by zero exception: + +``` +try: + result = 10 / 0 +except ZeroDivisionError: + print("Division by zero is not allowed.") +else: + print("Division successful:", result) +finally: + print("Execution completed.") +``` + +## What's the difference between append() and extend() for lists? + +append() adds a single element to the end of a list, while extend() adds multiple elements by appending elements from an iterable. Example: + +Using append(): +``` +my_list = [1, 2, 3] +my_list.append(4) +print(my_list) # Output: [1, 2, 3, 4] +``` + +Using extend(): + +``` +my_list = [1, 2, 3] +my_list.extend([4, 5]) +print(my_list) # Output: [1, 2, 3, 4, 5] +``` + +## Explain the use of lambda functions in Python. + +Lambda functions are anonymous functions used for short tasks. Example: + +Defining and using a lambda function: + +``` +square = lambda x: x**2 +print(square(5)) # Output: 25 +``` + +## What are the different types of loops in Python? + +Python has for loops and while loops. + +Example: + +Using for loop: +``` +for i in range(5): + print(i) +``` + +Using while loop: +``` +i = 0 +while i < 5: + print(i) + i += 1 +``` + +## Explain the difference between == and is operators. + +The == operator compares the values of two objects, while the is operator checks if two variables point to the same object in memory. + +Example: + +Using ==: + +``` +a = [1, 2, 3] +b = [1, 2, 3] +print(a == b) # Output: True (because values are equal) +``` + +Using is: + +``` +a = [1, 2, 3] +b = a +print(a is b) # Output: True (because they reference the same object) +``` + +## What is the use of the pass keyword? + +The pass keyword is a no-operation placeholder used when a statement is syntactically needed but no action is required. Example: + +Using pass: +``` +def placeholder_function(): + pass # To be implemented later +``` + +## What is the difference between global and local variables? + +Global variables are defined outside functions and can be accessed anywhere in the code, while local variables are defined inside functions and are only accessible within that function's scope. Example: + +Using a global variable: +``` +global_var = 10 + +def my_function(): + print(global_var) + +my_function() # Output: 10 +``` + +Using a local variable: + +``` +def my_function(): + local_var = 5 + print(local_var) + +my_function() # Output: 5 +# Attempting to access local_var outside the function will result in an error +``` + +## Explain the difference between open() and with open() statement. + +open() is a built-in function used to open a file and return a file object. +However, it's crucial to manually close the file using file_object.close(). +Conversely, with open() is a context manager that automatically handles file closure, ensuring clean-up even if exceptions occur. + +Example: +``` +file = open('example.txt', 'r') +content = file.read() +file.close() +``` + +Using with open(): +``` +with open('example.txt', 'r') as file: + content = file.read() +# File is automatically closed when the block exits +``` + + diff --git a/README.md b/README.md index 655c5a89..0dc09cb5 100644 --- a/README.md +++ b/README.md @@ -60,61 +60,43 @@ - List comprehensions. - Nested lists and advanced list operations. - Practice exercises and examples: - - Example: Parsing a complex configuration file with nested lists. + - Example: Print list of files in the list of folders provided -## Day 11: Working with Dictionaries and Sets +## Day 11: Working with Dictionaries and Sets (Project-1) - Dictionaries and key-value pairs. - Sets and set operations. - Practice exercises and examples: - Example: Managing a dictionary of server configurations and optimizing retrieval. -## Day 12: Functions and Modules -- Introduction to functions in Python. -- Writing functions and function parameters. -- Return values and modular code. +## Day 12: Python Tasks for DevOps (Part 1) - File Operations (Project-2) +- Introduction to File Operations and Boto3. +- Automating File operations. - Practice exercises and examples: - - Example: Creating a function to automate server status checks. + - Example: Update a server resources in the server.conf file up on external notification. -## Day 13: Functions and Modules (Part 2) -- Advanced function topics (recursion, lambda functions). -- Function libraries and built-in functions. -- Practice exercises and examples: - - Example: Developing a library of custom functions for DevOps automation. - -## Day 14: Python Libraries for DevOps (Part 1) -- Introduction to external libraries like Paramiko, Fabric, and Boto3. -- Automating SSH connections with Paramiko. -- Running commands on remote servers. -- Practice exercises and examples: - - Example: Using Paramiko to create a secure remote backup solution. - -## Day 15: Python Libraries for DevOps (Part 2) +## Day 13: Python Tasks for DevOps (Part 2) (Project-3) - Using Fabric for remote task automation. - AWS automation with Boto3. - Managing EC2 instances, S3 buckets, and more. - Practice exercises and examples: - - Example: Creating a Fabric script for deploying applications to remote servers. + - Example: Creating a aws script for deploying applications to remote servers. -## Day 16: Working with RESTful APIs +## Day 14: Github-JIRA intergration Project - (Project-4) - Introduction to RESTful APIs. - Making HTTP requests using Python. - Parsing JSON responses and error handling. - Practice exercises and examples: - - Example: Developing a script to monitor RESTful API endpoints for your DevOps tools. - -## Day 17: Data Serialization and Configuration Files -- Serializing and deserializing data (JSON, YAML). -- Managing configuration data. -- DevOps use cases for configuration files. -- Practice exercises and examples: - - Example: Building a configuration manager to handle application settings in JSON format. + - Example: Write a Python API which listens on a github comment and creates a ticket in JIRA. -## Day 18: Automation with Cron Jobs -- Scheduling automated tasks using cron. -- Creating Python scripts for scheduled automation. -- Handling periodic tasks and reports. +## Day 15: Github-JIRA intergration Project - (Project-4) - (Part-2) +- Introduction to Flask. +- Write your first API in python. +- How to handle API calls and deploy your API to a server. - Practice exercises and examples: - - Example: Using cron and Python to schedule regular backups of your data. + - Example: Write a Python API which listens on a github comment and creates a ticket in JIRA. -## Day 19: Python Interview Questions & Answers +## Day 16: Python Interview Questions & Answers +- Beginner and intermediate Level +## Day 17: Python Interview Questions & Answers +- Advanced Level diff --git a/simple-python-app/app.py b/simple-python-app/app.py new file mode 100644 index 00000000..0c9d9e60 --- /dev/null +++ b/simple-python-app/app.py @@ -0,0 +1,10 @@ +from flask import Flask + +app = Flask(__name__) + +@app.route('/') +def hello_world(): + return 'Hello, World!' + +if __name__ == '__main__': + app.run(debug=True, host='0.0.0.0', port=8000) \ No newline at end of file diff --git a/simple-python-app/requirements.txt b/simple-python-app/requirements.txt new file mode 100644 index 00000000..fdceace4 --- /dev/null +++ b/simple-python-app/requirements.txt @@ -0,0 +1,2 @@ +Flask==2.1.0 +Werkzeug==2.2.2 \ No newline at end of file