[go: up one dir, main page]

0% encontró este documento útil (0 votos)
150 vistas8 páginas

Cuadernos Python y Jupyter

Este documento explica los cuadernos Jupyter y Python. Indica que Python es un lenguaje de programación fácil de usar y que los cuadernos Jupyter permiten combinar código, texto e imágenes. Describe variables, listas, tuplas y diccionarios en Python, así como bucles, condicionales e importación de paquetes.

Cargado por

Carlos Mora
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
150 vistas8 páginas

Cuadernos Python y Jupyter

Este documento explica los cuadernos Jupyter y Python. Indica que Python es un lenguaje de programación fácil de usar y que los cuadernos Jupyter permiten combinar código, texto e imágenes. Describe variables, listas, tuplas y diccionarios en Python, así como bucles, condicionales e importación de paquetes.

Cargado por

Carlos Mora
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
Está en la página 1/ 8

14/4/2020 Made with Jupyter Book

Cuadernos Python y Jupyter


Python es un lenguaje de programación donde no necesitas compilar. Simplemente puede
ejecutarlo línea por línea (que es cómo podemos usarlo en un cuaderno). Entonces, si usted es
bastante nuevo en programación, Python es un excelente lugar para comenzar. La versión actual
es Python 3, que es lo que usaremos aquí.

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.

Variables in Python come in many forms. Below are some examples.

an_integer = 42 # Just an integer


a_float = 0.1 # A non-integer number, up to a fixed precision
a_boolean = True # A value that can be True or False
a_string = '''just enclose text between two 's, or two "s, or do what we did for this
none_of_the_above = None # The absence of any actual value or variable type

https://qiskit.org/textbook/ch-prerequisites/python-and-jupyter-notebooks.html 1/8
14/4/2020 Made with Jupyter Book

As well as numbers, another data structure we can use is the list.

a_list = [0,1,2,3]

Lists in Python can contain any mixture of variable types.

a_list = [ 42, 0.5, True, [0,1], None, 'Banana' ]

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

A similar data structure is the tuple.

a_tuple = ( 42, 0.5, True, [0,1], None, 'Banana' )


a_tuple[0]

42

A major difference between the list and the tuple is that list elements can be changed

a_list[5] = 'apple'

print(a_list)

[42, 0.5, True, [0, 1], None, 'apple']

whereas tuple elements cannot

a_tuple[5] = 'apple'

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-42d08f1e5606> in <module>
----> 1 a_tuple[5] = 'apple'

TypeError: 'tuple' object does not support item assignment

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)

[42, 0.5, True, [0, 1], None, 'apple', 3.14]

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

The values are accessed using the keys

a_dict['This is the key for a value 1']

New key/value pairs can be added by just supplying the new value for the new key

a_dict['new key'] = 'new_value'

To loop over a range of numbers, the syntax is

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

for key in a_dict:


value = a_dict[key]
print('key =',key)
print('value =',value)
print()

key = 1
value = This is the value, for the key 1

key = This is the key for a value 1


value = 1

key = False
value = :)

key = (0, 1)
value = 256

key = new key


value = new_value

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!

Importing packages is done with a line such as

import numpy

The numpy package is important for doing maths

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.

You can also pull everything straight out of numpy with

from numpy import *

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.

A good thing to know about in any language is how to make a function.


https://qiskit.org/textbook/ch-prerequisites/python-and-jupyter-notebooks.html 5/8
14/4/2020 Made with Jupyter Book

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 .

def do_some_maths ( Input1, Input2 ):


the_answer = Input1 + Input2
return the_answer

It's used as follows

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.

def add_sausages ( input_list ):


if 'sausages' not in input_list:
input_list.append('sausages')

print('List before the function')


print(a_list)

add_sausages(a_list) # function called without an output

print('\nList after the function')


print(a_list)

List before the function


[42, 0.5, True, [0, 1], None, 'apple', 3.14]

List after the function


[42, 0.5, True, [0, 1], None, 'apple', 3.14, 'sausages']

Randomness can be generated using the random package.

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

print('\n Random number from 0 to 1:', random.random() )


print("\n Random choice from our list:", random.choice( a_list ) )
print('\n')

* Results from sample 1

Random number from 0 to 1: 0.8871532828770763

Random choice from our list: True

* Resultados de la muestra 2

Número aleatorio de 0 a 1: 0.23546620034206256

Elección aleatoria de nuestra lista: [0, 1]

* Resultados de la muestra 3

Número aleatorio de 0 a 1: 0.6239018436429378

Elección aleatoria de nuestra lista: manzana

* Resultados de la muestra 4

Número aleatorio de 0 a 1: 0.41196221426918567

Elección aleatoria de nuestra lista: salchichas

* Resultados de la muestra 5

Número aleatorio de 0 a 1: 0.2790934642986329

Elección aleatoria de nuestra lista: manzana

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

También podría gustarte