








Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity
Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium
Prepara tus exámenes
Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity
Prepara tus exámenes con los documentos que comparten otros estudiantes como tú en Docsity
Encuentra los documentos específicos para los exámenes de tu universidad
Estudia con lecciones y exámenes resueltos basados en los programas académicos de las mejores universidades
Responde a preguntas de exámenes reales y pon a prueba tu preparación
Consigue puntos base para descargar
Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium
Comunidad
Pide ayuda a la comunidad y resuelve tus dudas de estudio
Ebooks gratuitos
Descarga nuestras guías gratuitas sobre técnicas de estudio, métodos para controlar la ansiedad y consejos para la tesis preparadas por los tutores de Docsity
Una introducción a los tipos numéricos y cadenas en python, incluyendo ejemplos de uso, operadores y métodos. Se abordan tipos como enteros, flotantes, complejos y cadenas, así como operaciones básicas como sumas, restas, multiplicaciones, divisiones y módulos.
Tipo: Ejercicios
1 / 14
Esta página no es visible en la vista previa
¡No te pierdas las partes importantes!









Figure 1: BY-SA
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.
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:
In [1]: 1 + 1
Out[1]: 2
In [2]: 3 * 5
Out[2]: 15
In [3]: # Creating an integer variable for my test of integer numbers. integer_var = 4
integer_var
Out[3]: 4
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:
In [6]: float_var = 2.
float_var
Out[6]: 2.
In [7]: float_exp = 6.023e
float_exp
Out[7]: 6.023e+
In [8]: type(float_exp)
Out[8]: float
In [9]: float_var/float_exp
Out[9]: 3.4866345674912835e-
1.1.3 Complex
In Python, complex numbers are native, and are used seamlessly like the other types:
In [10]: complex_var = 1.5 + 0.5j
In [11]: complex_var.real
Out[11]: 1.
In [12]: complex_var.imag
Out[12]: 0.
In [13]: type(1 + 0j)
Out[13]: complex
In [23]: divider*quotient+reminder
Out[23]: 7
The result is ok It is possible to operate with different types:
In [24]: 2 * 3e
Out[24]: 60000.
In [25]: integer_var * complex_var
Out[25]: (6+2j)
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.
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
TypeError: can’t convert complex to float
In [32]: int(2 + 0j)
TypeError Traceback (most recent call last)
<ipython-input-32-f5d8093ffa9e> in
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.
Then the absolute square of the complex variable is calculated
|Complex|^2 = 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.
The result is already a floating point value.
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:
In [37]: s = ’Hello, how are you?’
s
Out[37]: ’Hello, how are you?’
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’
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
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]
One may however create new strings from the original one. We can substitute the first ocurrence of a character:
In [60]: b = a.replace(’l’, ’z’, 1)
b
Out[60]: ’hezlo, world!’
In [61]: a
Out[61]: ’hello, world!’
Or all the ocurrences:
In [62]: a.replace(’l’, ’z’)
Out[62]: ’hezzo, worzd!’
Strings have many useful methods, such as a.replace 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 https://docs.python.org/3.4/library/stdtypes.html#text-sequence-type-str and https://docs.python.org/3.4/library/string.html#formatstrings
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
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’)
ValueError Traceback (most recent call last)
<ipython-input-66-84986758f0fb> in
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 102.txt’
More complex formatting can be applied, but this will be presented when we talk about Input and Output.
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 ’)
b 7 b 6 b 5 b 4 b 3 b 2 b 1 b 2
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
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-
Out[76]: -0.
In [77]: -1e
Out[77]: -inf
The numbers can be also shown in hexadecimal format using the function float.hex():
In [78]: float.hex(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 =
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.