Python Essentials for DevOps Engineers: Understanding Data Types

Python Essentials for DevOps Engineers: Understanding Data Types

#90daysofdevops Day13 and Day 14

ยท

10 min read

What is Python?

Python is a programming language, similar to C, C++, Java, and JavaScript. However, Python is easier to learn compared to other languages. It also includes a standard library that helps reduce coding errors, enhances programmer efficiency, and results in smaller software sizes. Because of these characteristics, Python is often referred to as a beginner programming language.

It was created by Guido van Rossum ๐Ÿ‘‡

Guido van Rossum

Some popular examples of these libraries and frameworks are Django, TensorFlow, Flask, Pandas, and Keras. These tools allow developers to work with web development, machine learning, data analysis, and more, expanding the capabilities of Python and making it a versatile language for various applications.

How to Install Python?

here I am showing the installation for Ubuntu.

  1. Open the Ubuntu terminal.
#Update the package lists for upgrades and new installations by running the following command:
sudo apt update

#Install Python 3 by entering the command:
sudo apt install python3.11 #This command installs the latest version of Python 3.11 available in the Ubuntu package repository

#Verify the installation by checking the Python version with:
python3 --version

Data Types in Python.

  1. Numeric: Numeric data types that are used to represent numeric values. Numeric data types are used to store numbers, including integers, floating-point numbers, and complex numbers. These data types allow you to perform mathematical operations and calculations.

     #assigning the value to the variable 
     #integer 
     a = 5 (here we are assigning the value 5 to a)
    
     #float
     a = 3.23 (fractional values called float)
    
     #complex
     a = 4+5x (complex number)
    
  1. int: represents signed integers. which are whole numbers without any fractional part. For example, 10, -5, and 0 are integers.

  2. float*:* The float data type is used to represent floating-point real values, which are numbers with a fractional part. Floats can represent both whole numbers and decimal numbers. For example, 3.14, -0.5, and 1.0 are floats.

  3. complex: The complex data type is used to represent complex numbers, which consist of a real part and an imaginary part. Complex numbers are represented in the form of a + bj, where a is the real part, b is the imaginary part, and j is the imaginary unit (โˆš-1). For example, 2 + 3j and -1.5 + 0j are complex numbers.

  1. String: is one of the most commonly used data types in Python as they allow you to work with textual data. The string type, represented by the str class in Python, is used to represent a sequence of characters.

    Strings can be created by enclosing characters in either single quotes ('') or double quotes (""). For example name = "Gurudath"

    Strings in Python are immutable, which means once a string is created, it cannot be modified. However, you can create new strings by performing operations on existing strings.

  2. Sequences allow you to store and manipulate multiple items as a single entity, In Python, the Sequence data type represents an ordered collection of elements.

    1. List:

      • Lists are created using square brackets ([]) and can contain elements of different data types.

      • Lists are mutable, meaning you can modify, add, or remove elements after creation.

      • Elements in a list are ordered and can be accessed using index positions starting from 0.

      • Example: my_list = [1, 2, 'a', 'b', True]

    2. Tuple:

      • Tuples are created using parentheses (()) and can also contain elements of different data types.

      • Tuples are immutable, meaning they cannot be modified once created. However, you can create new tuples by concatenating or slicing existing tuples.

      • Elements in a tuple are ordered and can be accessed using index positions starting from 0.

      • Example: my_tuple = (1, 2, 'a', 'b', True)

    3. Range:

      • The range type represents an immutable sequence of numbers and is commonly used in looping constructs.

      • Ranges are created using the range() function and specify the start, stop, and step values.

      • Ranges are not directly accessible like lists or tuples. They are typically used with loops to generate a sequence of numbers.

      • Example: my_range = range(1, 10, 2)

        # List
        fruits = ['apple', 'banana', 'orange', 'grape']
        print("List:", fruits)
        print("First fruit:", fruits[0])
        print("Length of the list:", len(fruits))

        #output
        List: ['apple', 'banana', 'orange', 'grape']
        First fruit: apple
        Length of the list: 4

        # Tuple
        colors = ('red', 'green', 'blue')
        print("Tuple:", colors)
        print("Second color:", colors[1])
        print("Length of the tuple:", len(colors))

        #output
        Tuple: ('red', 'green', 'blue')
        Second color: green
        Length of the tuple: 3

        # Range
        numbers = range(1, 10)
        print("Range:", numbers)
        print("First number:", numbers[0])
        print("Length of the range:", len(numbers))

        #output
        Range: range(1, 10)
        First number: 1
        Length of the range: 9
  1. Binary:

    • bytes: represents a sequence of bytes.

    • byte array: represents a mutable sequence of bytes.

    • memory view: represents a memory view of an object.

    # Bytes
    data_bytes = b'Hello World'
    print("Bytes:", data_bytes)
    print("Length of bytes:", len(data_bytes))
    print("Accessing byte at index 0:", data_bytes[0])

    """ First, we create a bytes object data_bytes that represents 
    a sequence of bytes using the b prefix. We print the bytes, 
    determine the length of the bytes using the len() function, 
    and access a specific byte using indexing (data_bytes[0])."""

    #Output
    Bytes: b'Hello World'
    Length of bytes: 11
    Accessing byte at index 0: 72

    # Bytearray
    data_bytearray = bytearray(b'Python')
    print("Bytearray:", data_bytearray)
    print("Length of bytearray:", len(data_bytearray))
    print("Accessing byte at index 2:", data_bytearray[2])

    """we create a bytearray object data_bytearray from a bytes object. 
    We print the bytearray, determine the length of the bytearray, 
    and access a specific byte using indexing (data_bytearray[2])."""

    #Output
    Bytearray: bytearray(b'Python')
    Length of bytearray: 6
    Accessing byte at index 2: 116

    # Memoryview
    data_memoryview = memoryview(b'OpenAI')
    print("Memoryview:", data_memoryview)
    print("Accessing byte at index 3:", data_memoryview[3])

    """we create a memoryview object data_memoryview from a bytes object. 
    We print the memoryview and access a specific byte using indexing 
    (data_memoryview[3])."""

    #Output
    Memoryview: <memory at 0x7fd52c08e040>
    Accessing byte at index 3: 101
  1. Mapping: the mapping data type refers to objects that store a collection of key-value pairs. The key-value pairs allow you to map or associate values with corresponding keys, providing a way to access values based on their unique keys. The main mapping data type in Python is the dict (dictionary).

    A dictionary is an unordered collection of key-value pairs, where each key is unique within the dictionary. The keys are used to retrieve the associated values. Dictionaries are commonly used when you want to store and retrieve data based on specific labels or identifiers.

     # Creating a dictionary
     student = {
         'name': 'John',
         'age': 20,
         'grade': 'A'
     }
    
     # Accessing dictionary elements
     print("Name:", student['name'])
     print("Age:", student['age'])
     print("Grade:", student['grade'])
    

    In the above example, we create a dictionary called student. It has three key-value pairs: 'name': 'John', 'age': 20, and 'grade': 'A'. We can access the values in the dictionary using the keys. For example, student['name'] will return the value 'John'.

  2. Boolean: the boolean data type represents a binary value that can be either True or False. Booleans are used to represent the truth values of logical expressions and conditions.

    Boolean values are often the result of a comparison or a logical operation. For example, when you compare two values using a comparison operator like == (equality), < (less than), > (greater than), etc., the result will be a boolean value indicating whether the comparison is true or false.

     # Comparison
     x = 5
     y = 10
     is_equal = x == y
     print(is_equal)  # False
    
     # Logical operations
     a = True
     b = False
     logical_and = a and b
     logical_or = a or b
     logical_not = not a
     print(logical_and)  # False
     print(logical_or)   # True
     print(logical_not)  # False
    
  3. Set: the set are defined by enclosing the elements in curly braces {} or by using the set() function. Sets are commonly used for tasks that involve membership testing, removing duplicates, and performing mathematical set operations like union, intersection, and difference.

     # Creating a set
     fruits = {'apple', 'banana', 'orange'}
     print(fruits)  # {'apple', 'banana', 'orange'}
    
     # Adding elements to a set
     fruits.add('mango')
     print(fruits)  # {'apple', 'banana', 'orange', 'mango'}
    
     # Removing an element from a set
     fruits.remove('banana')
     print(fruits)  # {'apple', 'orange', 'mango'}
    
     # Checking membership in a set
     print('apple' in fruits)  # True
     print('grape' in fruits)  # False
    
     # Set operations
     set1 = {1, 2, 3, 4, 5}
     set2 = {4, 5, 6, 7, 8}
    
     # Union of sets
     union_set = set1.union(set2)
     print(union_set)  # {1, 2, 3, 4, 5, 6, 7, 8}
    
     # Intersection of sets
     intersection_set = set1.intersection(set2)
     print(intersection_set)  # {4, 5}
    
     # Difference of sets
     difference_set = set1.difference(set2)
     print(difference_set)  # {1, 2, 3}
    
    • frozenset: frozenset is an immutable version of a set. It is similar to a regular set, but once created, its elements cannot be modified or changed. It is defined using the frozenset() function or by enclosing the elements in curly braces {}.

        # Creating a frozenset
        numbers = frozenset([1, 2, 3, 4, 5])
        print(numbers)  # frozenset({1, 2, 3, 4, 5})
      
        # Accessing elements of a frozenset
        for num in numbers:
            print(num)
      
        # Trying to modify a frozenset (results in an error)
        # numbers.add(6)
        # numbers.remove(2)
      
        # Performing set operations with frozensets
        set1 = frozenset([1, 2, 3, 4, 5])
        set2 = frozenset([4, 5, 6, 7, 8])
      
        # Union of frozensets
        union_set = set1.union(set2)
        print(union_set)  # frozenset({1, 2, 3, 4, 5, 6, 7, 8})
      
        # Intersection of frozensets
        intersection_set = set1.intersection(set2)
        print(intersection_set)  # frozenset({4, 5})
      
        # Difference of frozensets
        difference_set = set1.difference(set2)
        print(difference_set)  # frozenset({1, 2, 3})
      

      In the code above, we create a frozenset called numbers containing the elements 1, 2, 3, 4, and 5. We can access the elements of a frozenset using a loop or other iterable operations. However, attempting to modify a frozenset, such as adding or removing elements, will result in an error since frozensets are immutable.

      We can also perform set operations on frozensets, just like regular sets. These operations include finding the union, intersection, and difference between frozensets. The results of these operations are also frozensets.

  4. None: is a special constant representing the absence of a value or the lack of a value. It is often used to indicate that a variable or a function does not have a meaningful value assigned to it.

Tasks:

  1. Give the Difference between List, Tuple and set. Do Handson and put screenshots as per your understanding.

    --> the differences between lists, tuples, and sets in Python:
    Lists:

    • Lists are ordered, mutable sequences of elements.

    • Elements in a list are enclosed in square brackets [] and separated by commas.

    • Lists allow duplicate elements.

    • Elements in a list can be modified, added, or removed after creation.

Tuples:

  • Tuples are ordered, immutable sequences of elements.

  • Elements in a tuple are enclosed in parentheses () and separated by commas.

  • Tuples allow duplicate elements.

  • Once a tuple is created, its elements cannot be modified, added, or removed.

Trying to modify a tuple (will raise an error) # numbers[0] = 5 # TypeError: 'tuple' object does not support item assignment

Sets:

  • Sets are unordered collections of unique elements.

  • Elements in a set are enclosed in curly braces {} or created using the set() constructor.

  • Sets do not allow duplicate elements.

  • Sets are mutable, meaning you can add or remove elements.

    Note: Sets are particularly useful when you want to store unique elements and perform set operations such as union, intersection, difference, etc.

    the main differences between lists, tuples, and sets are their mutability, order, and handling of duplicate elements. Lists are mutable and allow duplicates, tuples are immutable and allow duplicates, while sets are mutable, unordered, and do not allow duplicates.

  1. Create below Dictionary and use Dictionary methods to print your favourite tool just by using the keys of the Dictionary.
fav_tools = 
{ 
  1:"Linux", 
  2:"Git", 
  3:"Docker", 
  4:"Kubernetes", 
  5:"Terraform", 
  6:"Ansible", 
  7:"Chef"
}

We specify the favorite_key variable with the key corresponding to your favorite tool. Then we use the get() method of the dictionary to retrieve the value associated with that key. If the key exists in the dictionary, the favorite tool is printed. Otherwise, a message indicating that the tool was not found is displayed.

  1. Create a List of cloud service providers eg.
cloud_providers = ["AWS","GCP","Azure"]

Write a program to add Digital Ocean to the list of cloud_providers and sort the list in alphabetical order.

[Hint: Use keys to built in functions for Lists]

cloud_providers = ["AWS", "GCP", "Azure"]
cloud_providers.append("Digital Ocean")  
cloud_providers.sort()  

print(cloud_providers)


In this article, I am providing a comprehensive overview of Python data types and their applications, serving as a valuable resource to advance your skills in Python development. Thank you!

ย