0% found this document useful (0 votes)
12 views14 pages

Python Basic Data Types Explained

The document discusses basic data types in programming, particularly in Python, including number types (integers, floats, complex numbers, and booleans) and strings. It explains how to create, manipulate, and convert these types, as well as their properties such as immutability for strings. Additionally, it covers binary data representation and the encoding of integers as binary numbers.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views14 pages

Python Basic Data Types Explained

The document discusses basic data types in programming, particularly in Python, including number types (integers, floats, complex numbers, and booleans) and strings. It explains how to create, manipulate, and convert these types, as well as their properties such as immutability for strings. Additionally, it covers binary data representation and the encoding of integers as binary numbers.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

3 BasicTypes

October 7, 2014

Figure 1: BY-SA

1 Basic types
All the different programming languages provide some basic data types. These types provides a way to
store, manipulate and interchange information inside a program, or between them. The basic types are
highly related with the CPU ones, and every language tries to use them as much as possible. This is also
the case of Python. Let’s analyze them.

1.1 Number types


They represent mathematical values, and are used to make calculations. The available types are:

1.1.1 Integer
As its name indicates, it is used to operate with integer numbers. They work with infinite precission or, said
in other words, it can work with any number of digits. Examples of its use are:

• Sum

In [1]: 1 + 1

Out[1]: 2

• Multiply

In [2]: 3 * 5

Out[2]: 15

• Create an integer variable

In [3]: # Creating an integer variable for my test of integer numbers.


integer_var = 4

integer_var

Out[3]: 4

1
• Determine the type of an integer variable
In [4]: type(integer_var)
Out[4]: int
In [5]: integer_var + 5
Out[5]: 9

1.1.2 Float
Are floating point numbers, and are used to represent real numbers. They have integer, fractionary part and
exponent. Examples of use:
• Create a floating point variable
In [6]: float_var = 2.1

float_var
Out[6]: 2.1
• Create variable with a number represented with exponential notation
In [7]: float_exp = 6.023e23

float_exp
Out[7]: 6.023e+23
• Determine the type
In [8]: type(float_exp)
Out[8]: float
• Divide the variables:
In [9]: float_var/float_exp
Out[9]: 3.4866345674912835e-24

1.1.3 Complex
In Python, complex numbers are native, and are used seamlessly like the other types:
• Creating a variable
In [10]: complex_var = 1.5 + 0.5j
• Requesting the real part
In [11]: complex_var.real
Out[11]: 1.5
• Requesting the imaginary part
In [12]: complex_var.imag
Out[12]: 0.5
• Determine the type:
In [13]: type(1 + 0j)
Out[13]: complex

2
Important: Notice that although 1. + 0j can be considered a real number, as it has no
imaginary part, it is still considered a complex by Python.

1.1.4 Booleans
In [14]: 3 > 4

Out[14]: False

In [15]: test = (3 > 4)

In [16]: test

Out[16]: False

In [17]: type(test)

Out[17]: bool

1.1.5 Numeric operators


A Python shell can therefore replace your pocket calculator, with the basic arithmetic operations +, -, *,
/, % (modulo) and **(exponent) that are natively implemented. If number of the same type are used, the
results are always the same type, with the exception of the division:

In [18]: 7/3

Out[18]: 2.3333333333333335

In this case the result is an integer, to provide the better matching result.
If an integer division is required, it can be forced using the operator //:

In [19]: 7//3

Out[19]: 2

The reminder can be calculated using the modulo operator:

In [20]: 7%3

Out[20]: 1

As an example, we can check the formula: $ Dividend = Divider*quotient + reminder $

In [21]: dividend = 7
divider = 3

quotient = dividend//divider

quotient

Out[21]: 2

In [22]: reminder = dividend%divider


reminder

Out[22]: 1

3
In [23]: divider*quotient+reminder

Out[23]: 7

The result is ok
It is possible to operate with different types:

• Integer and Float: results a float

In [24]: 2 * 3e4

Out[24]: 60000.0

• Integer and Complex: results a complex

In [25]: integer_var * complex_var

Out[25]: (6+2j)

• Float and Complex: results a complex

In [26]: 8 * 3j

Out[26]: 24j

It is possible to force the type using casting:

In [27]: int(3.14)

Out[27]: 3

In [28]: float(43)

Out[28]: 43.0

In [29]: complex(3)

Out[29]: (3+0j)

In [30]: complex(4.23)

Out[30]: (4.23+0j)

But it is not possible to force type from a complex to another numeric type:

In [31]: float(4 + 0j)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)

<ipython-input-31-567fbb0947cd> in <module>()
----> 1 float(4 + 0j)

TypeError: can’t convert complex to float

In [32]: int(2 + 0j)

4
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)

<ipython-input-32-f5d8093ffa9e> in <module>()
----> 1 int(2 + 0j)

TypeError: can’t convert complex to int

If a complex has to be converted to its absolute square value, and afterwards read the real part:

In [33]: complex_var

Out[33]: (1.5+0.5j)

First the complex conjugate of the complex var is calculated:

In [34]: complex_var_conj = complex_var.conjugate()

complex_var_conj

Out[34]: (1.5-0.5j)

In this case, the conjugate has parentheses () which means that it is a function associated with the
complex type.  
2
Then the absolute square of the complex variable is calculated |Complex| = Complex · Complex∗ :

In [35]: absolute_square_var = complex_var*complex_var.conjugate()

absolute_square_var

Out[35]: (2.5+0j)

Then, the real part is retrieved:

In [36]: absolute_square_var.real

Out[36]: 2.5

The result is already a floating point value.

1.2 Strings
Strings are used to represent text. The different letters are encoded in what is known as “Characters”.

1.2.1 Creating a string


Different syntaxes can be used to create a string:

• Single quote:

In [37]: s = ’Hello, how are you?’

Out[37]: ’Hello, how are you?’

5
• Double quote:

In [38]: s = "Hi, what’s up?"

Out[38]: "Hi, what’s up?"

• Triple quote:

It allows to span the text in different lines, but special care must be taken with the formatting:

In [39]: s = ’’’Hello,
how are you?’’’

Out[39]: ’Hello,\n how are you?’

In this case, we have implicitly included formating characters, like the newline \n. The result can be seen
using the print function:

In [40]: print(s)

Hello,
how are you?

The spaces before how have been included automatically, and most probably this is something unwanted.
Another option is to take out the spaces:

In [41]: s = """Hi,
what’s up?"""

print(s)

Hi,
what’s up?

But in this case, the python code is not so easy to read. In general, the triple quote shall be omited. It
shall be used only for comments.
It is also possible to explicitly include formatting characters:

In [42]: s = "Hi guys\nHow are you?\n\tWe are fine!!! Thanks!!!"

Out[42]: ’Hi guys\nHow are you?\n\tWe are fine!!! Thanks!!!’

In this case, we have used he newline character \n, and the tabulate character \t. The resulting text is:

In [43]: print(s)

Hi guys
How are you?
We are fine!!! Thanks!!!

6
1.2.2 Indexing a string
The different characters inside a string can be accessed using what is called indexing:

In [44]: a = "hello"

The index is introduced inside the brackets []:

In [45]: a[0]

Out[45]: ’h’

7
Important: The first character is the one at the index 0. In python, the indexes always
start with the 0 value.

In [46]: a[1]

Out[46]: ’e’

The last character is the 4th index:

In [47]: a[4]

Out[47]: ’o’

If we try to access the fith index, the result would be an error:

In [48]: a[5]

---------------------------------------------------------------------------
IndexError Traceback (most recent call last)

<ipython-input-48-b6a934feab86> in <module>()
----> 1 a[5]

IndexError: string index out of range

This indicates that we have tried to access and incorrect index.


It is possible to access the last character directly, just using the -1 index.

In [49]: a[-1]

Out[49]: ’o’

This notation can be used until we reach the index 0, that in this case would be the -5:

In [50]: a[-5]

Out[50]: ’h’

Question: What will happen if we try to access the -6 index?

In brief, the negative index correspond to counting from the right end.

1.2.3 Slicing
Sometimes we want to read parts of a text. This is known as slicing:

In [51]: a = "hello, world!"

For example, we want to access the elements 3, 4, 5. Then we have to write it as:

In [52]: a[3:6]

8
Out[52]: ’lo,’

Important: The last index is always the previous to the one requested.

It is possible to ask the length of the sub-string:

In [53]: len(a[3:6])

Out[53]: 3

The first index and the last can be implicitly, if they are not included:

In [54]: a[:4]

Out[54]: ’hell’

In [55]: a[4:]

Out[55]: ’o, world!’

We can also ask the characters in the odd positions, this is done adding a second colon and a number
afterwards, in this case 2:

In [56]: a[::2]

Out[56]: ’hlo ol!’

Or from the 4th character, every three:

In [57]: a[4::3]

Out[57]: ’owl’

Accents and special characters can also be handled in Unicode strings (see
[Link]

1.2.4 Inmutability
A string is an immutable object and it is not possible to modify its contents.

In [58]: a = "hello, world!"

Out[58]: ’hello, world!’

In [59]: a[2] = ’z’

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)

<ipython-input-59-d57c4312feba> in <module>()
----> 1 a[2] = ’z’

TypeError: ’str’ object does not support item assignment

9
One may however create new strings from the original one. We can substitute the first ocurrence of a
character:

In [60]: b = [Link](’l’, ’z’, 1)

Out[60]: ’hezlo, world!’

In [61]: a

Out[61]: ’hello, world!’

Or all the ocurrences:

In [62]: [Link](’l’, ’z’)

Out[62]: ’hezzo, worzd!’

Strings have many useful methods, such as [Link] as seen above. Remember the a. object-oriented
notation and use tab completion or help(str) to search for new methods.
Python offers advanced possibilities for manipulating strings, looking for patterns or formatting. The
interested reader is referred to [Link]
and [Link]

1.2.5 String conversion


Strings can be converted to other types, the same way as the numerical types:

In [63]: int(’1’)

Out[63]: 1

But they have to follow the correct format:

In [64]: int(’1.’)

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)

<ipython-input-64-f18b6136395b> in <module>()
----> 1 int(’1.’)

ValueError: invalid literal for int() with base 10: ’1.’

Other examples:

In [65]: complex(’3.+4j’)

Out[65]: (3+4j)

In [66]: complex(’3. + 4j’)

10
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)

<ipython-input-66-84986758f0fb> in <module>()
----> 1 complex(’3. + 4j’)

ValueError: complex() arg is a malformed string

This can be solved using the replace function:

In [67]: complex(’3. + 4j’.replace(’ ’, ’’))

Out[67]: (3+4j)

Note: In this case, we have applied the function replace to the string directly, but we can
also have asigned the string to a variable and operate afterwards. The latest method is the
preferred one.

1.2.6 String substitution


It is possible to convert from a variable to a string directly:

In [68]: str(4j)

Out[68]: ’4j’

But the preferred method is using string substitution and formatting. This we have a better control of
the resulting string. Basic examples are:

In [69]: ’An integer: {}; a float: {}; another string: {}’.format(1, 0.1, ’string’)

Out[69]: ’An integer: 1; a float: 0.1; another string: string’

In [70]: i = 102

In [71]: filename = ’processing_of_dataset_{}.txt’.format(i)

In [72]: filename

Out[72]: ’processing of dataset [Link]’

More complex formatting can be applied, but this will be presented when we talk about Input and
Output.

1.3 Binary data


The computers work always with boolean data (‘1’ and ‘0’), also called bits, and boolean operations (‘and’,
‘or’ and ‘not’), also called logic operators. As a result, to code the numbers and strings, it is necessary to
define how to group the booleans in packets that allow to encode more information.
As an example:

1 bit (boolean) can store two values: (‘1’ and ‘0’)

11
2 bits can store four values: (‘11’, ‘10’, ‘01’ and ‘00’)

3 bits can store eight values: (‘111’, ‘110’, ‘101’, ‘100’, ‘011’, ‘010’, ‘001’ and ‘000’)

And so on. The number of values (or symbols) can be determined using the formula:

m = 2n
Where n is the number of bits and m the number of symbols that can be represented.

1.3.1 Integers
Now, we have the problem how to code an integer as a binary number. This can be easily done using the
following procedure with a number like 5. First we divide the number by 2 (as we can encode two values
with a bit):
7
→3
2
so

5→3·2+1
The reminder is 1. This number becomes the less significant bit or the bit 0. The resulting 3 now has to
be also divided:
3
→1
2
so

3→1·2+1
This reminding 1 becomes the following bit or bit 1. Now we can divide another time the result (1):
1
→0
2
so

1→0·2+1
This reminding 1 becomes the following bit or bit 2. The resulting number is:

b2 b1 b0

1 1 1

Question: What will be the binary representation of 5? and 4?

Bigger numbers can be represented using a larger number of bits. Python provides means to calculate it
automatically. For example, the number 234 is represented by the number:
In [73]: bin(234)
Out[73]: ’0b11101010’
The result is a Python string which includes the prefix ‘0b’ to indicate that it is in binary.
The value in this case has to be represented by a group of, at least, 8 bits:

12
b7 b6 b5 b4 b3 b2 b1 b2

1 1 1 0 1 0 1 0

A group of 8 bits is called byte, and it can represent:

28 → 256


The range goes from number 0 to number 255. The major difficulty is that this numbers are only positive.
If the number is negative, Python adds a sign before the number to represent it. For examples:

In [74]: bin(-234)

Out[74]: ’-0b11101010’

Question: What will be the binary representation of -9? and -15?

The representation of this coding inside the computer is based on two’s complement. But this is outside
the scope of the subject.
To simplify the representation it is possible to use the hexadecimal format. In this case the bits are
grouped every 4. As 4 bits can represent 16 symbols, the 10 digits are not enough, for this reason, letters
are added:

dec bin hex

0 0000 0
1 0001 1
2 0010 2
3 0011 3
4 0100 4
5 0101 5
6 0110 6
7 0111 7
8 1000 8
9 1001 9
10 1010 a
11 1011 b
12 1100 c
13 1101 d
14 1110 e
15 1111 f

As a result, the number 234 is 0b11101010 and in hexadecimal is:


1110 is e
1010 is a

13
So 234 is 0xea (0x indicates that it is an hexadecimal number).
The function hex makes the conversion:

In [75]: hex(234)

Out[75]: ’0xea’

1.3.2 Real numbers


In case of real numbers or floating point numbers, Python uses the IEEE 754 representation. This standard
allows to represent numbers between:

±4.9406564584124654 · 10−324 ≤ x ≤ ±1.7976931348623157 · 10308


A number smaller than ±4.9406564584124654 · 10−324 is considered 0 with the same sign, and a bigger
one is considered an infinity:

In [76]: -1e-325

Out[76]: -0.0

In [77]: -1e309

Out[77]: -inf

The numbers can be also shown in hexadecimal format using the function [Link]():

In [78]: [Link](1.4e5)

Out[78]: ’0x1.1170000000000p+17’

Note that the exponent is written in decimal rather than hexadecimal, and that it gives the power of
2 by which to multiply the coefficient. For example, the hexadecimal string 0x1.117p+17 represents the
floating-point number:

x = 1 · 160 + 1 · 16−1 + 1 · 16−2 + 1 · 16−3 · 217 = 14000 = 1.4 · 105




Where every digit after the comma has multiplied by the corresponding power of 16. This notation is
only used when high precission representation is required. In any other case, the decimal notation is used.

14

You might also like