Cuadernos Python y Jupyter
Cuadernos Python y Jupyter
Una forma de codificar en Python es usar un cuaderno Jupyter. Esta es probablemente la mejor
manera de combinar programación, texto e imágenes. En un cuaderno, todo se presenta en
celdas. Las celdas de texto y las celdas de código son las más comunes. Si está viendo esta
sección como un cuaderno Jupyter, el texto que está leyendo ahora está en una celda de texto.
Una celda de código se puede encontrar justo debajo.
Para ejecutar el contenido de una celda de código, puede hacer clic en ella y presionar Shift +
Enter. O si hay una pequeña flecha a la izquierda, puede hacer clic en eso.
1 + 1
Si está viendo esta sección como un cuaderno Jupyter, ejecute cada una de las celdas de código
a medida que lee.
a = 1
b = 0.5
a + b
1,5
Above we created two variables, which we called a and b , and gave them values. Then we
added them. Simple arithmetic like this is pretty straightforward in Python.
https://qiskit.org/textbook/ch-prerequisites/python-and-jupyter-notebooks.html 1/8
14/4/2020 Made with Jupyter Book
a_list = [0,1,2,3]
Lists are indexed from 0 in Python (unlike languages such as Fortran). So here's how you access
the 42 at the beginning of the above list.
a_list[0]
42
42
A major difference between the list and the tuple is that list elements can be changed
a_list[5] = 'apple'
print(a_list)
a_tuple[5] = 'apple'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-42d08f1e5606> in <module>
----> 1 a_tuple[5] = 'apple'
https://qiskit.org/textbook/ch-prerequisites/python-and-jupyter-notebooks.html 2/8
14/4/2020 Made with Jupyter Book
Also we can add an element to the end of a list, which we cannot do with tuples.
a_list.append( 3.14 )
print(a_list)
Another useful data structure is the dictionary. This stores a set of values, each labeled by a
unique key.
Values can be any data type. Keys can be anything sufficiently simple (integer, float, Boolean,
string). It cannot be a list, but it can be a tuple.
a_dict = { 1:'This is the value, for the key 1', 'This is the key for a value 1':1, F
New key/value pairs can be added by just supplying the new value for the new key
for j in range(5):
print(j)
0
1
2
3
4
Note that it starts at 0 (by default), and ends at n-1 for range(n) .
You can also loop over any 'iterable' object, such as lists
https://qiskit.org/textbook/ch-prerequisites/python-and-jupyter-notebooks.html 3/8
14/4/2020 Made with Jupyter Book
for j in a_list:
print(j)
42
0.5
True
[0, 1]
None
apple
3.14
or dictionaries
key = 1
value = This is the value, for the key 1
key = False
value = :)
key = (0, 1)
value = 256
Conditional statements are done with if , elif and else with the following syntax.
if 'strawberry' in a_list:
print('We have a strawberry!')
elif a_list[5]=='apple':
print('We have an apple!')
else:
print('Not much fruit here!')
https://qiskit.org/textbook/ch-prerequisites/python-and-jupyter-notebooks.html 4/8
14/4/2020 Made with Jupyter Book
We have an apple!
import numpy
numpy.sin( numpy.pi/2 )
1.0
We have to write numpy. in front of every numpy command so that it knows to find that
command defined in numpy . To save writing, it is common to use
import numpy as np
np.sin( np.pi/2 )
1.0
Then you only need the shortened name. Most people use np , but you can choose what you
like.
Then you can use the commands directly. But this can cause packages to mess with each other,
so use with caution.
sin( pi/2 )
1.0
If you want to do trigonometry, linear algebra, etc, you can use numpy . For plotting, use
matplotlib . For graph theory, use networkx . For quantum computing, use qiskit . For
whatever you want, there will probably be a package to help you do it.
Here's a function, whose name was chosen to be do_some_maths , whose inputs are named
Input1 and Input2 and whose output is named the_answer .
x = do_some_maths(1,72)
print(x)
73
If you give a function an object, and the function calls a method of that object to alter its state,
the effect will persist. So if that's all you want to do, you don't need to return anything. For
example, let's do it with the append method of a list.
import random
for j in range(5):
print('* Results from sample',j+1)
https://qiskit.org/textbook/ch-prerequisites/python-and-jupyter-notebooks.html 6/8
14/4/2020 Made with Jupyter Book
* Resultados de la muestra 2
* Resultados de la muestra 3
* Resultados de la muestra 4
* Resultados de la muestra 5
Estos son los conceptos básicos. Ahora todo lo que necesita es un motor de búsqueda y la
intuición de saber a quién vale la pena escuchar en Stack Exchange. Entonces puedes hacer
https://qiskit.org/textbook/ch-prerequisites/python-and-jupyter-notebooks.html 7/8
14/4/2020 Made with Jupyter Book
cualquier cosa con Python. Es posible que su código no sea el más 'Pitónico', pero solo los
Pythonistas realmente se preocupan por eso.
https://qiskit.org/textbook/ch-prerequisites/python-and-jupyter-notebooks.html 8/8