Intro to Data Types, Working with Strings and Numbers

Intro to Data Types, Working with Strings and Numbers

Python: Intro to Data Types, Working with Strings and Numbers

Intro to Data Types, Working with Strings and Numbers

In programming, a data type is a classification or categorization that specifies which type of value a variable can hold. Data types are essential because they determine how data is stored in memory and what operations can be performed on that data. Python, like many programming languages, supports several built-in data types. Here are some of the common data types in Python:

Numeric Data Types:

int: Represents integers (whole numbers). Example: x = 5

float: Represents floating-point numbers (numbers with decimal points). Example: y = 3.14

complex: Represents complex numbers. Example: z = 2 + 3j

Sequence Types:

str: Represents strings (sequences of characters). Example: text = "Hello, World"

list: Represents lists (ordered, mutable sequences). Example: my_list = [1, 2, 3]

tuple: Represents tuples (ordered, immutable sequences). Example: my_tuple = (1, 2, 3)

Mapping Type:

dict: Represents dictionaries (key-value pairs). Example: my_dict = {'name': 'John', 'age': 30}

Set Types:

set: Represents sets (unordered collections of unique elements). Example: my_set = {1, 2, 3}

frozenset: Represents immutable sets. Example: my_frozenset = frozenset([1, 2, 3])

Boolean Type:

bool: Represents Boolean values (True or False). Example: is_valid = True

Binary Types:

bytes: Represents immutable sequences of bytes. Example: data = b'Hello'

bytearray: Represents mutable sequences of bytes. Example: data = bytearray(b'Hello')

None Type:

NoneType: Represents the None object, which is used to indicate the absence of a value or a null value.

Custom Data Types:You can also define your custom data types using classes and objects.

Let's say we are writing the python programme. We just wrote something called “amit” but for compilers or interpreters when we execute this python program they consider it as a Data only. Whether writing any name like “amit “ or numbers 6 7 8 9 or 6.2 everything is a data or programme. The interpreter needs to understand what the type of data is ?

Python Data types are categorized into string data types, Then we have numeric data type & within numeric we have integer and float. We are having bunch of the sequence data types

Mapping data types and then we have Booleans. We are using these frequently.

How does the compiler understand when we write any data? How does he recognize which data types it is?

So Answer is the “Syntax” ( how we are going to declaring variable or writing that particular )

If we have just written the name amit & compiler doesn't understand that you are writing the string. We need to put double quotes or single quotes “amit” ‘amit” so then only python understands that this person is writing the list of the characters or strings.

Another example we just write only numbers then python will understand that this guy has written the integer data type . if we are writing in decimal line 6.3 then python considers it as a floating data type. We don't have to declare explicitly in Python. This type of programming is called Dynamically type programming language, Python has a programming language that has some inbuilt functions.

If we want to write the string called “amit” . If we have received a task to write a python programme which is having the list of the employee names which is having full names. I’ve the task of retrieving the first names only instead of the full name. In this case we will write the python programme. So we are going to use the inbuilt functions of the python programme.

Whenever we are going to write the programme first we have to search if they have an inbuilt function. Every programming language has an in-built function.

These inbuilt functions are written and managed by Python itself. If we are going to write our custom functions then we have to make sure it's working properly. For each data type ( Strings, Numeric, Sequence) we have in-built functions. Always learn the in-built functions of each and every data type.

One more example is that we got a list of ARN (Amazon Resource Numbers) for the IAM users so our task was to just get the user name from the ARN . What will we do? We can write the python programme. So using the python in-built function we can just say split (/) we can do practically for better understanding.

So we will create a new file that test.py.

I’m using the codespec utility within GitHub only.

arn:aws:iam::123456789012:user/johndoe  

So above example id for the string and we have assign the value variable called “arn”

Now our task is to just get this username out of the complete ARN.

We are using Codespecs to run the python program. Created the file called test.py file.

So this is the String

& this is the

arn is the variable which assigns the ARN value.

We have to pull the username only out of the complete ARN . So with the help of the python programming language we will do this. We have got the below error. We can check if we are in the proper path

We have checked the permissions as well.

We have deleted the file and created Again.

Post executing the script we have got this below output:

So if we just want only username we can change the below parameters in the script.

 Appended [1]

& then we executed the script.

Yes, we pull only the username. With the help of python scripting. So when we use the split string function it separates the entire strings into two parts. With the help of the in-built functions of the particular data types. Before moving ahead we have to install the Extension of the Python.

Will take another example. Let's say I need a name with the upper case.

Next example is let's say we have to add the two different types of the strings

Above is not an additional kind of the programs though we were using the + over above. It is called string concatenation.

Now we can take the other example of if we are having a very long string and if we want to print the particular string i.e. how many characters are available in the strings. So we can use the function called len. So below is the programme.

Post this we can see the integer and float

Integers are whole numbers, and floats can represent both whole and fractional numbers. You can perform arithmetic operations on these types, including addition, subtraction, multiplication, division, and more.

Be aware of potential issues with floating-point precision, which can lead to small inaccuracies in calculations. Python also provides built-in functions for mathematical operations, such as abs(), round(), and math module for advanced functions.

We can do practical things to understand more.

Explanation:

  1. Integer Division (//): num1 // num2 gives the quotient when 10 is divided by 5, which is 2.

  2. Modulus (%): num1 % num2 gives the remainder when 10 is divided by 5, which is 0.

  3. Absolute Value (abs()): abs(-7) returns the absolute value of -7, which is 7.

Then we can see Floating.

Below is the result post execution of the code:

Here's what the Python code we've provided does:

Integer Division: The // operator performs integer division, which returns the quotient without the remainder.

Here’s what the Python code does when working with float variables:

Addition (+): Adds two numbers.

5.0 + 2.5 = 7.5

Subtraction (-): Subtracts the second number from the first.

5.0 - 2.5 = 2.5

Multiplication (*): Multiplies two numbers.

5.0 * 2.5 = 12.5

Division (/): Divides the first number by the second, resulting in a floating-point result.

5.0 / 2.5 = 2.0

Rounding (round()): Rounds a number to the specified number of decimal places: round(3.14159265359, 2) rounds the value 3.14159265359 to 2 decimal places, resulting in 3.14.

Regex

1. Regular Expressions for Text Processing:

Regular expressions (regex or regexp) are a powerful tool for pattern matching and text processing.

The re module in Python is used for working with regular expressions.

Common metacharacters: . (any character), * (zero or more), + (one or more), ? (zero or one), [] (character class), | (OR), ^ (start of a line), $ (end of a line), etc.

Examples of regex usage: matching emails, phone numbers, or extracting data from text.

re module functions include re.match(), re.search(), re.findall(), and re.sub() for pattern matching and replacement.

Will do some practical demonstration over here.

Then how does a devops Engineer use regular expressions on a day to day basis?

Let's say that there is a huge log file there will be a lot of logs we have to deal with on a day to day basis. There would be infra logs, application logs, audit logs and inside these logs let's say there are a bunch of error logs and a bunch of the warning logs as well.

So if we want to print the only errors in the particular pattern. Then we can use the regular expression. We can do practical things to demonstrate more.

This Python script uses the re module (which stands for regular expressions) to search for a specific pattern ("brown") within a string ("The quick brown fox").

Code Explanation:

Importing the re module:

import re: This imports the regular expression module in Python, which provides functions for working with text patterns.

Defining the text and pattern:

text = "The quick brown fox": The string that we want to search in.

pattern = r"brown": The regular expression pattern to search for. The r before the string makes it a raw string, meaning backslashes are treated literally (which is useful for regex patterns).

Performing the search:

re.search(pattern, text): This searches for the first occurrence of the pattern in the text. If the pattern is found, it returns a match object; otherwise, it returns None.

Checking if the pattern was found:

If a match is found, search.group() is used to get the matched text.

If no match is found, it prints "Pattern not found".

Happy Learning !!