Data types in Python

Data types in Python

Types in Python are a representation of data because it does not require variables to declare their type, because all types are automatically converted

We can use the function type to know the type of a variable

Type boolean

The Boolean type simply distinguishes between two states, a success or enabled state, true value, True, and a failure or deactivated state, false value, False

Both states are not case sensitive

Typically, the result of operators that return a Boolean value are passed to the control structures

Numeric types

In Python there are 4 different types of numeric variables:

  • int

    integer with fixed precision

  • long

    integer if the size of an int is exceeded

  • float

    double precision floating point number

  • complex

    complex number (real part + j imaginary part)

It is the interpreter who decides the type of variable according to what we define

However, we may want to force it ourselves through a cast

Type string

A string is a string of characters delimited by quotation marks

A string literal can be specified in two different ways:

  • single quote

    are specified between the characters opening and closing

    To specify a literal single quotation mark, you must escape with a backslash (\). To specify a literal backslash, it is duplicated (\\)

    All other instances of backslashes will be treated as a literal backslash: this means that other escape sequences that could be used, such as \r o \n, will be displayed literally as specified, instead of having any other special meaning

  • double quotes

    are specified between the characters " opening and " closing

    Python will interpret the following escape sequences as special characters:

    Code Description
    \n line feed (LF or 0x0A (10) in ASCII)
    \r carriage return (CR or 0x0D (13) in ASCII)
    \t horizontal tab (HT or 0x09 (9) in ASCII)
    \\ backslash
    \" double quotes

Methods

Let's look at some of the most everyday methods for strings

Formatting methods

They affect the formatting of the text contained in the string

  • capitalize()

    Make a copy of the string with the first letter in uppercase

  • lower()

    Returns a copy of the string in lowercase

  • upper()

    Returns a copy of the string in uppercase

  • swapcase()

    Returns a copy of the string in which they are case-sensitive and vice versa

  • title()

    Returns a copy of the string in which the first letter of each word is uppercase and the other lowercase letters

  • center(length, 'fill character')

    Returns a copy of the input string centered on the specified length and between the specified fill character

  • ljust(length, 'fill character'): Returns a copy of the left aligned string

  • rjust(length, 'fill character')

    Returns a copy of the left/right aligned string

  • zfill(length)

    Returns a copy of the string filled with zeros to the left until it reaches the indicated length

Search methods

They allow us to search within a certain string to check whether a substring is contained in the string or how many times a substring appears

  • count (‘substring’)

    Returns an integer representing the number of occurrences of the substring within the string

  • find(‘substring’)

    Returns an integer representing the position at which the substring begins within the string

Validation methods

They always give us back a boolean, that is, True or False

They serve to check if a chain meets a certain condition

  • startswith(‘substring’)

    It tells us if a string starts with a certain string

  • endswith(‘substring’)

    It tells us if a string ends up by a certain string

  • isalnum()

    It tells us if a substring is alphanumeric

  • isalpha()

    It tells us if a string is alphabetical

  • isdigit()

    It tells us if a string is numeric

  • islower()

    It tells us if a string contains only lowercase

  • isupper()

    It tells us if a string contains only capital letters

  • isspace()

    It tells us if a string contains only blanks

  • istitle()

    It tells us if a string is formatted as a title

Substitution methods

They allow us to replace text to unify the format of different strings that have come to us in different ways

  • format(arguments)

    We may have a chain that is prepared to receive a certain amount of arguments

    Calling this function and entering the necessary arguments returns a copy of the already formatted string

  • replace('searched substring', 'substring to put')

    Searches within the string for a substring and replaces it with the indicated string

  • strip()

    Removes the character we specify from the right and left of the string

    By default it looks for the space character

  • lstrip()

    Removes characters to the left of a string

    If we enter a substring as an argument, look for that substring and the combinations of the substring characters from the left until it finds no more

  • rstrip()

    Removes characters to the right of a string

    If we enter a substring as an argument, look for that substring and the combinations of the substring characters from the right until it finds no more

Methods of union and division

They allow us to replace text to unify different strings that have come to us by different ways or to separate a string into several

  • join(iterable)

    It receives as an argument an iterable and returns as a result the elements of the iterable joined by the character of the string on which it is applied

  • partition('separator')

    Returns a 3 elements tuple

    The first element is to the left of the 'separator', the second element is the separator, and the third element is to the right of the separator

  • split('separator')

    Returns a list of all items found when splitting the string by the separator

  • splitlines()

    Returns a list where each item is a fraction of the string divided into lines

Lists

They are defined by putting the contents of the list in square brackets, separating each of the elements by a comma

Each item in the list can contain items of different types

The lists are mutable, that is, their elements can be modified

In Python, items in a list are numbered from 0 to length – 1

To access the item in a list, the name of the list is put and then the index that we want to access (if we put the index with a negative sign will start at the end of the list)

To access a range within a list we have different options:

  • Take items from the start: lista[:a]
  • Take items from position to (included) to end: lista[a:]
  • Take items from a to b (not including b): lista[a:b]

The start of the range always includes the element in that position, but not the end of the range

Methods

Let's look at some of the methods for most everyday lists

  • append()

    adds an item to the bottom of the list

  • insert()

    is used to insert an item into the assigned index

  • pop()

    deletes and returns the value at the position of the assigned index

  • reverse()

    reorders the list in reverse

  • sort()

    rearrange the list in ascending order

We can find all the methods in your documentation

Tuples

Tuples are similar to lists, defined with parentheses instead of brackets

They have the peculiarity of being immutable

As you can see, items are accessed in the same way as with lists

Dictionaries

Dictionaries define a one to one relationship between key value between {} and they're mutable

They are defined by placing a comma separated list of pairs key:value

Once defined, we can access the value associated with a key by searching by key

In addition, we can search whether or not a certain key exists in our dictionary

Dictionaries are a type of collection in Python that, unlike lists, are indexed by words and not by numbers

Values can be of any type

We can think of a dictionary as an unordered set of pairs key:value with the requirement that the keys have to be unique

Methods

Let's look at some of the methods for more everyday dictionaries

  • keys()

    returns us an iterable containing the dictionary keys

  • values()

    returns us an iterable containing the dictionary values

  • items()

    returns us an iterable with the pairs key:value of the dictionary

Objects

Objects consist of a set of values, properties, and a set of methods applied to those values

It is these methods that allow us to modify the state of that object, that is, the value of its properties

In Python, objects have the following characteristics:

  • Everything is an object, including types and classes
  • Allows multiple inheritance
  • There are no private methods or attributes
  • Attributes can be modified directly
  • Allows monkey patching

    Classes are created at run time but can be modified after they are created

  • Allows duck typing

    The dynamic typing style of data in which the current set of methods and properties determines the semantic validity, rather than inheritance of a class

  • Allows operator overload
  • Allows the creation of new data types

Let's create a academic sample object where you have the properties: Name, Surname, Age and Identity card

We'll create the object instance by mapping it to a variable as follows:

It is possible to query the class of an object with the function type, but you can also query through its special attribute __class__

[/tp”]

A su vez las clases tienen un atributo especial __name__ que nos devuelve su nombre en forma de cadena sin adornos:

You can initialize all variables to have the kind we want, we will use the class constructor passing the arguments we need

The constructor is a method that is called automatically when you create an object and is defined with the name __init__ and through the reserved word self we can reference to the current object

If a constructor exists, there must also be a destructor that is called when deleting the object to handle cleanup tasks such as emptying the memory

All objects are automatically deleted from memory at the end of the program, although to remove them automatically we have the special method __del__

It is not advisable to overwrite this method because it is handled automatically, but it is interesting to know that it is possible

The method __str__ is the one that returns the representation of an object in the form of a string

It is called automatically is when we print a variable per screen with the function print

By default the objects print their class and a memory address, but we can change it by overwriting their behavior

For example, for the university object we overwrite the method __str__ to show us the name, age, surname and dni

An interesting special method is the one that returns the length

It is usually linked to collections, but nothing prevents it from defining it in a class and not redefining it, because by default it does not exist in objects even if it is the one that is executed when passed to the function __len__

In our example of the university object it doesn't make much sense to count its length, but I include it to show its use

The properties of an object can be described by other objects or even collections of them

The definition of methods associated with an object can be specified in the object definition

For example, for the university object we overwrite the method __str__ to show the student's first name, age, surname, dni and mean student's notes

To access the properties or methods we will use the operator .

Inheritance

Inheritance is the ability of one class to inherit attributes and methods from another, something that allows us to reuse code

To see its usefulness, let's develop an example by modifying the university object

We will start from a base class that will be the father (superclass) of other daughters who inherited from it (subclasses)

We start from a class Person that will contain all the common attributes and two child classes Student and Teacher who inherit from it and have their own attributes or methods

To inherit the attributes and methods of one class in another, you just have to pass it in parentheses during its definition

It is possible to use the behavior of a superclass without defining anything in the subclass, although in our example we will give them behavior

Thanks to the flexibility of Python we can handle objects of different classes massively in a very simple way

Let's start by creating a list with our two People from different subclasses

One of the few flaws in Python is that if we modify the values within an object, these changes will be reflected outside the same

Just as in collections, objects are passed to functions by reference

It affects when making copies, creating instead an access to the object instead of a new one with its previous values

To make a copy from its values we can use the function copy of the module with the same name

The function copy can also be used to copy collections

Multiple inheritance allows a subclass to inherit from multiple superclasses

This involves a problem, which is that if multiple superclasses have the same attributes or methods, the subclass can only inherit from one of them

In addition to superclasses you can also inherit multiple subclasses

In these cases Python will prioritize the leftmost classes at the time of subclass declaration

We've used the reserved word pass to instruct the interpreter to ignore the body code and use the one in the class object or the superclasses (subclases) we tell you to

Null value

In Python variables can be assigned a value that indicates the empty value, this value is the value NULL

A variable is considered None if:

  • has been assigned the constant None
  • has not passed an attribute to a function

The constant None is insensitive to case sensitive