TYPES OF DATA IN PYTHON

NUMERICAL TYPES

Let’s start talking about Basic Data Types in Python by introducing the numeric types which are divided into:

  • Integer
  • Floating-Point
  • Boolean

It is important to know that all numeric types in Python are immutable, once a number is created and therefore an object it cannot change. For example, I can create a variable a that first points to an object worth 3 then to an object worth 4. What you can’t do is change the value of the object, the number 3 is always the number 3.

type=int

int is the integer class that cannot contain a period because otherwise Python would consider it a floating-point. We can consider three other different bases besides the decimal:

  • Binary 0b1100100              100
  • Octal 0o1635                      925
  • Hexadecimal 0x1ff              511

type=bool

The Boolean type has 2 instances True and False. It is a particular type of integer, in fact True = 1 and False = 0.

type=float

Are floating point numbers for example 0.0, 123.89 etc. The scientific notation 10e4, 13e-2 etc. can also be used.

THE STRINGS

type=str

Strings are a prime example of a sequence, that is, an ordered set of elements in which each element has a certain position. A string is a sequence of characters that must belong to the Unicode set. As numbers, strings are immutable objects, we cannot alter the individual characters of a string, but for example we can copy part of a string. A string is created using a sequence of single or double quoted characters. The empty string a = ” has no characters but is perfectly legal. A newline string must have the backslash character for example:

You can write /

A multiline string with the backslash ‘

In addition, you can use three single or double quotes to go to line breaks.

“””you can write a multiline string using either three single or double quotes“””

SEQUENCES OF ESCAPE

\n            carriage return

\t             Tab

\\            Indicates to insert the backslash character

\’            It inserts a single quote into the string, not signaling that the string is finished

\\”          It inserts a double quote into the string, not signaling that the string is finished

FORMATTING THE STRINGS

THE F-STRING

By f-Strings we mean the formatting of text in Python.

str.Format () first form

We must prefer the version introduced in Python 3.6 and which is called f-String. In a very similar way to other programming languages, even in Python you can insert variables within a string. This clearly allows us to create texts that can change based on certain events. To achieve this we can use the f-strings introduced in Python 3.6.

Let’s take this practical example:

month = ‘August’

season = ‘summer’

x = f’s we are in the month of {month} and therefore in the season {season} ‘

print (x)

we are in August and therefore in the summer season

As you can appreciate, we started a new string by prefixing the letter “f” before the declaration quotes of the same. Actually declaring an “f-string”. Inside we recalled our “classic” variables previously initialized, enclosing them in curly brackets. In this way, by printing the “x” variable, we are going to compile a text that could be modified by assigning new objects to the month and season respectively.
It is interesting to note that we can also interact with the variables inside the f-strings, for example in this way:

month = ‘August’

season = ‘summer’

x = f’s we are in the month of {month.upper ()} and therefore in the season {season} ‘

print (x)

we are in the month of AUGUST and therefore in the summer season

EXPRESSIONS AND OPERATORS

An expression is a particular type of Statement that has the characteristic of being evaluated by the Python interpreter and producing a value. The simplest expressions are literals and identifiers.

def numeri():
    a = 123456789
    print(a)
    a=-800
    print(a)
    a=1_000_000  #L'underscore verrà ignorato. Introdotto
                 #in Python 3 con lo scopo di migliorare la lettura.
    print(bin(100))
    print(a)
    a=0b11001111        #numero binario
    print(a)
    a=0o1635            #numero ottale
    print(a)
    a=0x1ff             #numero esadecimale
    print(a)
    #Type = float
    a=0.0
    print(a)
    a=100.67
    print(a)
    a=-100.67
    print(a)
    a=10e+3
    print(a)
    a=10e-6
    print(a)
numeri()
def stringhe():
    titolo="L'isola Misteriosa"
    autore="Giulio Verne"
    print(f"Titolo: {titolo.upper()}, Autore: {autore}.")
    #Gli operatori + e * possono essere utilizzati per la manipolazione di stringhe.
    #La precedenza tra gli operatori viene mantenuta.
    #CONCATENAZIONE
    a="Hello"
    print(a+a+a)
    print(a*4)
    #Le stringhe sono, come ogni entità in
    #Python , oggetti e dispongono di una
    #serie di funzionalità accessibili tramite dei metodi built in
    #split([sep, [maxsplit]])
    #replace(old , new[, count])
    #strip([chars])
    s="Ciao Mondo"
    print(s.split('a',1))
    print(s.replace('a','U',1))
    print(s.strip('C'))
    #Formattazione: allineamento, maiuscole, minuscole
    #center(width[, fillchar]) ,ljust[,fillchar ]), rjust[, fillchar ])
    #upper() ,lower()) ,swapcase()
    s="Questa è una STRINGA su una riga"
    print(s.center(50,'.'))
    print(s.ljust(50,'.'))
    print(s.lower())
    #RICERCA : ricerca e interrogazione sulla stringa
    #find(sub[,start[,end]])  index(sub[,start[,end]])
    #rindex(sub[,start[,end]])  rfind (sub[,start[,end]])
    #count(sub[, start[,end]])
    #isupper() islower()
    #startswith(prefix[,start[,end]]) ,endswith(prefix[,start[,end]])
    print(s.find('riga',0,50))
    print(s.index('u',0,5))
    print(s.count('a',0,50))
    print(s.rindex('a',0,50))
    #Una stringa vuota è valutata
    #False mentre qualsiasi stringa
    #non vuota è valutata True
    #Le funzioni
    #min , max e cmp possono essere utilizzate anche sulle
    #stringhe.
    #Le stringhe sono inoltre dotate dell’operatore
    #in e not in
    s='Hello'
    print(min(s),max(s))
    print('e' in s)
stringhe()
Expressions

You can create more complex expressions than literals by using operators. An operator is a symbol that is used to represent an operation that is performed on a certain number of elements called operands. In this example we introduce the arithmetic operator + to the right of the assignment symbol we see a compound operation is not a simple expression because the sum is performed on two operands 10 and 5 through an operator that when evaluated together with these two operands produces the value 15 which is then assigned to the variable x.

Operator

ARITHMETIC OPERATORS

In Python 3 dividing 2 integers gives a float number. In Python 2 it gave an integer, truncating the result; in Python 3, to get a truncated result, use the integer division operator: ‘//’, both on integers and floats. Operations between integers give integers, if one of the 2 operands is a float a float is produced; Python in these cases does automatic conversions.

Arithmetic operators

ASSIGNMENT OPERATORS

There are several assignment operators in Python; each numeric operation can be combined with an assignment, to modify a variable and reassign it to itself.

Assignment operators

COMPARISON OPERATORS

Return: True or False. You can check if a variable is in a range with the compact syntax like: 1<a <3. In Python 2 there was also the “<>” operator with the same meaning as “! =”

Comparison operators

PRECEDENCE AMONG THE OPERATORS

The precedence of the operators is in the following list: from those with higher precedence to those with lower precedence:

dictionary creation: {}
creating lists []
tuple creation (),
functions, slicing, indexes
references to attributes of objects
exponent: **
“unary” operators: + x, -x, ~ x
numeric operators: / //% * – +
logical operators: ==! = <> <<=>> =
Membership operators: is in
logical operators: not and or

Round brackets can be used to change precedence.

Operator precedence

LOGICAL OPERATORS

Logical operators

TABLE OF TRUTH AND LOGICAL

AND

TABLE OF TRUTH OR LOGICAL

OR

NOT LOGICAL TRUTH TABLE

NOT

In Basic Data Types in Python All objects in Python can be tested as truth values because regardless of the type of object there is something that unites them all. In fact, all objects have an implicit truth value as indicated in the following figure. The first group has an implicit value of False, all the others True.

TRUTH VALUES TEST

BASIC DATA TYPES IN PYTHON OPERATIONS ON SEQUENCES

In Basic Data Types in Python strings are a particular type of sequence, it is a sequence of characters taken from the Unicode set. To take a single character from a string, an Offset is specified within a pair of square brackets. The offset is an index that starts from zero and reaches the string length -1. You can extract a substring from a string. A Slicing is built using square brackets and inserting or not values. Slicings can contain characters ranging from start to stop-1. Start and Stop represent the beginning and end of the slicing.

s [:] Returns the entire string.

s [1: 4] Returns the substring specified by start and stop excluded.

s [: 4] If we do not specify the start, Python starts from the beginning of the string and ends with the indicated offset.

s [9:] In this case Python starts at start and goes to the end of the string.

s [1: 12: 3] Here we see the use of the step with this instruction we tell Python to start from position 1 to 12, skipping three characters each time.

s [-2:] Negative indices can be used to start from the bottom of the string.

Indexing
slicing

OTHER OPERATIONS ON SEQUENCES

min(s) returns the minimum of the string taken in alphabetical order, max(s) is the dual.

Concatenation
len

TYPE CONVERSIONS

Basic Data Types in Python
Basic Data Types in Python
Basic Data Types in Python

LINK TO GITHUB CODE

GITHUB

LINKS TO PREVIOUS POST

PREVIOUS POST LINKS