Python - Data Types for DevOps Engineers

Python - Data Types for DevOps Engineers

#90DaysofDevOps Challenge - Day 13 + Day 14

▶What is Python?

It is one of the most popular programming languages. It is an interpreted high-level general-purpose language. Its syntax is very beginner-friendly and easy to learn. That’s the reason why most people suggest Python language to beginners as their first programming language to learn. In this post, we are going to discuss top Python commands that can make your Python learning journey easier.

In the Python programming language, commands basically refer to different functions or methods that we can execute on the Python shell to work them as commands.

Python consists of vast libraries and various frameworks like Django, Tensorflow, Flask, Pandas, Keras etc.

According to the official documentation of Python, there are no “commands” in Python but we have different kinds of functions like input(), type(), len(), so on and so forth. So in this Blog, we’re going to use the terms commands and functions interchangeably. Now, let’s get started with the Python commands list and discuss each command in detail.

▶How to install Python on Ubuntu Linux?

$ sudo apt-get install python3.6

Checking the version installed:

$ python3 --version

▶Python Data Types

They are used to define the type of a variable. It defines what type of data we are going to store in a variable. The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters.

Python has various built-in data types which we will discuss in this tutorial:

  • Numeric - int, float, complex

  • String - str

  • Sequence - list, tuple, range

  • Binary - bytes, bytearray, memoryview

  • Mapping - dict

  • Boolean - bool

  • Set - set, frozenset

  • None - NoneType

-Numeric Data Type

Python numeric data types store numeric values. Number objects are created when you assign a value to them.

i.e.

Python supports four different numerical types −

  • int (signed integers)

  • long (long integers, they can also be represented in octal and hexadecimal)

  • float (floating point real values)

  • complex (complex numbers)

Examples

Here are some examples of numbers:

  • Python allows you to use a lowercase l with long, but it is recommended that you use only an uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase L.

  • A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and y are the real numbers and j is the imaginary unit

# integer variable.
a=100
print("The type of variable having value", a, " is ", type(a))

# float variable.
b=20.345
print("The type of variable having value", b, " is ", type(b))

# complex variable.
c=10+3j
print("The type of variable having value", c, " is ", type(c))

- String Data Type

They are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pair of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 at the beginning of the string and working their way from -1 at the end.

The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator in Python.

For example:

str = 'Hello World!'

print (str)          # Prints complete string
print (str[0])       # Prints first character of the string
print (str[2:5])     # Prints characters starting from 3rd to 5th
print (str[2:])      # Prints string starting from 3rd character
print (str * 2)      # Prints string two times
print (str + "TEST") # Prints concatenated string

- List Data Type

Python Lists are the most versatile compound data types. A Python list contains items separated by commas and enclosed within square brackets ([]). To some extent, Python lists are similar to arrays in C. One difference between them is that all the items belonging to a Python list can be of different data types whereas a C array can store elements related to a particular data type.

The values stored in a Python list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 at the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.

For example:

#Creating a List
List = []
print( "Blank List: ")
print(List)

#Creating a List of numbers
List = [10, 20, 17]
print( "\nList of numbers: ")
print(List)

#Creating a List of strings and accessing using index
List = [ "AWS", "Kubernetes", "Terraform"]
print( "\nList Items: ")
print(List[0])
print(List[2])

- Tuple Data Type

It is another sequence data type that is similar to a list. A Python tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.

The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists.

For example:

#Creating a empty Tuple
Tuple1 = ()
print( "Empty Tuple: ")
print(Tuple1)

#Creating a Tuple with the us of list
list1 = [1, 2, 4, 5, 6]
print( "\nTuplet using List: ")
print(tuple(list1))

#Creating a Tuple with the use of built-in function
Tuple1 = tuple( 'DevOps')
print( "\nTuple with the use of function: ")
print(Tuple1)

- Set

Python Sets is an unordered collection of elements. Sets cannot contain duplicates. This will be placed inside the curly brackets.

#Creating a Set
set1 = set()
print( "Initial Blank Set: ")
print(set1)

#Creating a Set with the use of List
set1 = set(["Dev", "Ops", "Engineer", "Dev"])
print( "\nSet with the use of List: ")
print(set1)

- Ranges

Python range() is an in-built function in Python which returns a sequence of numbers starting from 0 and increments to 1 until it reaches a specified number.

We use the range() function with for and while loop to generate a sequence of numbers. Following is the syntax of the function:

range(start, stop, step)

Here is the description of the parameters used:

  • start: Integer number to specify starting position, (Its optional, Default: 0)

  • stop: Integer number to specify starting position (It's mandatory)

  • step: Integer number to specify increment, (Its optional, Default: 1)

Examples:

Following is a program which uses for loop to print numbers from 0 to 4:

for i in range(5):
  print(i)

Now let's modify the above program to print the number starting from 1 instead of 0:

for i in range(1, 5):
  print(i)

Again, let's modify the program to print the number starting from 1 but with an increment of 2 instead of 1:

for i in range(1, 5, 2):
  print(i)

- Dictionary

Python dictionaries are a kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type but is usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.

Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).

For example:

dict = {}
dict['one'] = "This is one"
dict[2]     = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}


print (dict['one'])       # Prints value for 'one' key
print (dict[2])           # Prints value for 2 key
print (tinydict)          # Prints complete dictionary
print (tinydict.keys())   # Prints all the keys
print (tinydict.values()) # Prints all the values

#Creating a Dictionary
fav_tools = {
    1: "Linux",
    2: "Git",
    3: "Docker",
    4: "Kubernetes",
    5: "Terraform",
    6: "Ansible"
}
one = 5
print( "My fav tool: ", fav_tools[one])
second = 4
print( "Now the second fav tool is: ", fav_tools[second])

#Creating a Dictionary
cloud_providers = [ "AWS", "GCP", "Azure", "OCI"]
print( "Available Cloud Providers: ", cloud_providers)

print( "Add OpenStack" )
cloud_providers.sort()
cloud_providers.append( "OpenStack" )
cloud_providers.sort()
print("Updated list of available Cloud Providers: ", cloud_providers)

Python dictionaries have no concept of order among elements. It is incorrect to say that the elements are "out of order"; they are simply unordered.

- Boolean Data Types

Python boolean type is one of the built-in data types which represents one of the two values either True or False. Python bool() function allows you to evaluate the value of any expression and returns either True or False based on the expression.

For examples:

Following is a program which prints the value of boolean variables a and b.

a = True
# display the value of a
print(a)

# display the data type of a
print(type(a))

Following is another program which evaluates the expressions and prints the return values:

# Returns false as a is not equal to b
a = 2
b = 4
print(bool(a==b))

# Following also prints the same
print(a==b)

# Returns False as a is None
a = None
print(bool(a))

# Returns false as a is an empty sequence
a = ()
print(bool(a))

# Returns false as a is 0
a = 0.0
print(bool(a))

# Returns false as a is 10
a = 10
print(bool(a))

- Data Type Conversion

When you may need to perform conversions between the built-in data types. To convert data between different Python data types, you simply use the type name as a function.

Conversion to int

Following is an example to convert number, float and string into integer data type:

a = int(1)     # a will be 1
b = int(2.2)   # b will be 2
c = int("3")   # c will be 3

print (a)
print (b)
print (c)

Conversion to float

Following is an example to convert number, float and string into float data type:

a = float(1)     # a will be 1.0
b = float(2.2)   # b will be 2.2
c = float("3.3") # c will be 3.3

print (a)
print (b)
print (c)

Conversion to string

Following is an example to convert number, float and string into string data type:

There are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value.

This was a nutshell of Python and its Data Structure types.

I hope this article is helpful to someone.