├── README.md ├── .gitattributes ├── .gitignore ├── 07-Listas.ipynb ├── 05-Ciclos.ipynb ├── 01-Empezando_a_Programar.ipynb ├── 04-Condicionales.ipynb ├── 02-Datos_y_Operaciones.ipynb ├── LICENSE └── 03-Variables_y_Funciones.ipynb /README.md: -------------------------------------------------------------------------------- 1 | # nbs_laboratorio 2 | 3 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 105 | __pypackages__/ 106 | 107 | # Celery stuff 108 | celerybeat-schedule 109 | celerybeat.pid 110 | 111 | # SageMath parsed files 112 | *.sage.py 113 | 114 | # Environments 115 | .env 116 | .venv 117 | env/ 118 | venv/ 119 | ENV/ 120 | env.bak/ 121 | venv.bak/ 122 | 123 | # Spyder project settings 124 | .spyderproject 125 | .spyproject 126 | 127 | # Rope project settings 128 | .ropeproject 129 | 130 | # mkdocs documentation 131 | /site 132 | 133 | # mypy 134 | .mypy_cache/ 135 | .dmypy.json 136 | dmypy.json 137 | 138 | # Pyre type checker 139 | .pyre/ 140 | 141 | # pytype static type analyzer 142 | .pytype/ 143 | 144 | # Cython debug symbols 145 | cython_debug/ 146 | 147 | # PyCharm 148 | # JetBrains specific template is maintainted in a separate JetBrains.gitignore that can 149 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 150 | # and can be added to the global gitignore or merged into this file. For a more nuclear 151 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 152 | #.idea/ 153 | -------------------------------------------------------------------------------- /07-Listas.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "07-Listas", 7 | "provenance": [], 8 | "include_colab_link": true 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "language_info": { 15 | "name": "python" 16 | } 17 | }, 18 | "cells": [ 19 | { 20 | "cell_type": "markdown", 21 | "metadata": { 22 | "id": "view-in-github", 23 | "colab_type": "text" 24 | }, 25 | "source": [ 26 | "\"Open" 27 | ] 28 | }, 29 | { 30 | "cell_type": "markdown", 31 | "source": [ 32 | "# Listas" 33 | ], 34 | "metadata": { 35 | "id": "dIaGzKynXbXb" 36 | } 37 | }, 38 | { 39 | "cell_type": "markdown", 40 | "source": [ 41 | "## Formas de declarar una variable de tipo lista" 42 | ], 43 | "metadata": { 44 | "id": "iFxnfukpnBwl" 45 | } 46 | }, 47 | { 48 | "cell_type": "code", 49 | "execution_count": null, 50 | "metadata": { 51 | "id": "y6BlP4SKXHlZ", 52 | "colab": { 53 | "base_uri": "https://localhost:8080/" 54 | }, 55 | "outputId": "63aaa31d-90d8-40af-d53c-1d1c5b0c55d3" 56 | }, 57 | "outputs": [ 58 | { 59 | "output_type": "stream", 60 | "name": "stdout", 61 | "text": [ 62 | "[]\n", 63 | "[]\n" 64 | ] 65 | } 66 | ], 67 | "source": [ 68 | "# Lista vacía\n", 69 | "a = []\n", 70 | "b = list()\n", 71 | "\n", 72 | "print(a)\n", 73 | "print(b)" 74 | ] 75 | }, 76 | { 77 | "cell_type": "code", 78 | "source": [ 79 | "# Lista homogénea: todos los elementos de la lista son del mismo tipo\n", 80 | "paises = [\"Argentina\", \"Brazil\", \"España\", \"Uruguay\"]\n", 81 | "numeros = [1, 2, 3, 4] \n", 82 | "\n", 83 | "print(paises)\n", 84 | "print(numeros)" 85 | ], 86 | "metadata": { 87 | "colab": { 88 | "base_uri": "https://localhost:8080/" 89 | }, 90 | "id": "FVYbNbsCnH8f", 91 | "outputId": "9c52f7fe-db17-466a-cc84-a66de4beebc6" 92 | }, 93 | "execution_count": null, 94 | "outputs": [ 95 | { 96 | "output_type": "stream", 97 | "name": "stdout", 98 | "text": [ 99 | "['Argentina', 'Brazil', 'España', 'Uruguay']\n", 100 | "[1, 2, 3, 4]\n" 101 | ] 102 | } 103 | ] 104 | }, 105 | { 106 | "cell_type": "code", 107 | "source": [ 108 | "# Lista heterogénea: los elementos pueden ser de cualquier tipo\n", 109 | "lista_heterogenea = [\"a\", 123, True, \"b\", ]\n", 110 | "\n", 111 | "print(lista_heterogenea)" 112 | ], 113 | "metadata": { 114 | "colab": { 115 | "base_uri": "https://localhost:8080/" 116 | }, 117 | "id": "MO3WFk61nlGs", 118 | "outputId": "381ec1a0-030c-41ba-89b0-977291befce5" 119 | }, 120 | "execution_count": null, 121 | "outputs": [ 122 | { 123 | "output_type": "stream", 124 | "name": "stdout", 125 | "text": [ 126 | "['a', 123, True, 'b']\n" 127 | ] 128 | } 129 | ] 130 | }, 131 | { 132 | "cell_type": "markdown", 133 | "source": [ 134 | "## Operaciones Básicas" 135 | ], 136 | "metadata": { 137 | "id": "8jG3hOiZpUqX" 138 | } 139 | }, 140 | { 141 | "cell_type": "code", 142 | "source": [ 143 | "# Longitud de una lista: Usamos la función len() para obtener la cantidad de elementos de la lista\n", 144 | "paises = [\"Argentina\", \"Brazil\", \"España\", \"Uruguay\"]\n", 145 | "\n", 146 | "longitud = len(paises)\n", 147 | "\n", 148 | "print(longitud)" 149 | ], 150 | "metadata": { 151 | "id": "qPEIOTtzpXlh", 152 | "colab": { 153 | "base_uri": "https://localhost:8080/" 154 | }, 155 | "outputId": "789de4ec-7699-4963-f738-835934e7c0ef" 156 | }, 157 | "execution_count": null, 158 | "outputs": [ 159 | { 160 | "output_type": "stream", 161 | "name": "stdout", 162 | "text": [ 163 | "4\n" 164 | ] 165 | } 166 | ] 167 | }, 168 | { 169 | "cell_type": "code", 170 | "source": [ 171 | "# Acceder a los elementos de la lista a través del índice\n", 172 | "# El primer valor del índice (posición) de una lista en Python comienza en 0.\n", 173 | "paises = [\"Argentina\", \"Brazil\", \"España\", \"Uruguay\"]\n", 174 | "\n", 175 | "print(paises[0])\n", 176 | "print(paises[1])\n", 177 | "print(paises[2])\n", 178 | "print(paises[3])" 179 | ], 180 | "metadata": { 181 | "colab": { 182 | "base_uri": "https://localhost:8080/" 183 | }, 184 | "id": "gLcZtPntqJ77", 185 | "outputId": "59182f21-7cc3-4842-daa0-2e9a2bbd2745" 186 | }, 187 | "execution_count": null, 188 | "outputs": [ 189 | { 190 | "output_type": "stream", 191 | "name": "stdout", 192 | "text": [ 193 | "Argentina\n", 194 | "Brazil\n", 195 | "España\n", 196 | "Uruguay\n" 197 | ] 198 | } 199 | ] 200 | }, 201 | { 202 | "cell_type": "code", 203 | "source": [ 204 | "# Obtener una sublista de una lista\n", 205 | "paises = [\"Argentina\", \"Brazil\", \"España\", \"Uruguay\"]\n", 206 | "\n", 207 | "# Indicamos la posición de incio y fin para obtener una sublista con los elementos cuyos índices están en el rango [inicio, fin)\n", 208 | "paises[1:3] " 209 | ], 210 | "metadata": { 211 | "colab": { 212 | "base_uri": "https://localhost:8080/" 213 | }, 214 | "id": "nxA8grL3reYl", 215 | "outputId": "68ac926e-6587-4c66-99be-6af321796228" 216 | }, 217 | "execution_count": null, 218 | "outputs": [ 219 | { 220 | "output_type": "execute_result", 221 | "data": { 222 | "text/plain": [ 223 | "['Brazil', 'España']" 224 | ] 225 | }, 226 | "metadata": {}, 227 | "execution_count": 1 228 | } 229 | ] 230 | }, 231 | { 232 | "cell_type": "code", 233 | "source": [ 234 | "# Otras formas de obtener sublistas\n", 235 | "\n", 236 | "print(paises[0:3]) # Es lo mismo usar [0:3] o [:3]\n", 237 | "print(paises[:3])\n", 238 | "\n", 239 | "print(paises[2:]) # Obtiene los elementos desde la posición 2 hasta el final de la lista\n", 240 | "\n", 241 | "print(paises[0:-2]) # Si usamos valores negativos el índice comienza al final de la lista con valor -1\n", 242 | "print(paises[-4:-2]) # Retorna lo mismo que la instrucción anterior" 243 | ], 244 | "metadata": { 245 | "id": "WuTS2dW6-fI-", 246 | "colab": { 247 | "base_uri": "https://localhost:8080/" 248 | }, 249 | "outputId": "5ee8d1c2-d395-4263-b0ec-89441a0ed9ae" 250 | }, 251 | "execution_count": null, 252 | "outputs": [ 253 | { 254 | "output_type": "stream", 255 | "name": "stdout", 256 | "text": [ 257 | "['Argentina', 'Brazil', 'España']\n", 258 | "['Argentina', 'Brazil', 'España']\n", 259 | "['España', 'Uruguay']\n", 260 | "['Argentina', 'Brazil']\n", 261 | "['Argentina', 'Brazil']\n" 262 | ] 263 | } 264 | ] 265 | }, 266 | { 267 | "cell_type": "markdown", 268 | "source": [ 269 | "## Recorrer los elementos de una lista" 270 | ], 271 | "metadata": { 272 | "id": "BYrJnNNPpggO" 273 | } 274 | }, 275 | { 276 | "cell_type": "code", 277 | "source": [ 278 | "# A partir de los elementos\n", 279 | "for elemento in paises:\n", 280 | " print(elemento)" 281 | ], 282 | "metadata": { 283 | "colab": { 284 | "base_uri": "https://localhost:8080/" 285 | }, 286 | "id": "2x_5YdvDpnw3", 287 | "outputId": "c23fa657-24a5-4641-f028-5ae3af01780f" 288 | }, 289 | "execution_count": null, 290 | "outputs": [ 291 | { 292 | "output_type": "stream", 293 | "name": "stdout", 294 | "text": [ 295 | "Argentina\n", 296 | "Brazil\n", 297 | "España\n", 298 | "Uruguay\n" 299 | ] 300 | } 301 | ] 302 | }, 303 | { 304 | "cell_type": "code", 305 | "source": [ 306 | "# A partir de un índice\n", 307 | "for i in range(len(paises)):\n", 308 | " print(paises[i])" 309 | ], 310 | "metadata": { 311 | "colab": { 312 | "base_uri": "https://localhost:8080/" 313 | }, 314 | "id": "Hw0lNr__p-Hg", 315 | "outputId": "b1c35279-9d52-487e-9faa-d352ea58370a" 316 | }, 317 | "execution_count": null, 318 | "outputs": [ 319 | { 320 | "output_type": "stream", 321 | "name": "stdout", 322 | "text": [ 323 | "Argentina\n", 324 | "Brazil\n", 325 | "España\n", 326 | "Uruguay\n" 327 | ] 328 | } 329 | ] 330 | }, 331 | { 332 | "cell_type": "code", 333 | "source": [ 334 | "# A partir de la función enumerate\n", 335 | "for i, e in enumerate(paises):\n", 336 | " print(f'Posición {i}: {e}.')" 337 | ], 338 | "metadata": { 339 | "colab": { 340 | "base_uri": "https://localhost:8080/" 341 | }, 342 | "id": "n9le6PA_qMMG", 343 | "outputId": "7cbcb375-a5c1-40be-d5fd-391cd2d08285" 344 | }, 345 | "execution_count": null, 346 | "outputs": [ 347 | { 348 | "output_type": "stream", 349 | "name": "stdout", 350 | "text": [ 351 | "Posición 0: Argentina.\n", 352 | "Posición 1: Brazil.\n", 353 | "Posición 2: España.\n", 354 | "Posición 3: Uruguay.\n" 355 | ] 356 | } 357 | ] 358 | }, 359 | { 360 | "cell_type": "markdown", 361 | "source": [ 362 | "## Mutación de listas" 363 | ], 364 | "metadata": { 365 | "id": "gYy6qtNaEixc" 366 | } 367 | }, 368 | { 369 | "cell_type": "code", 370 | "source": [ 371 | "# Cambiar el valor en una posición determinada\n", 372 | "paises = [\"Argentina\", \"Brazil\", \"España\", \"Uruguay\"]\n", 373 | "paises[1] = \"EEUU\"\n", 374 | "paises" 375 | ], 376 | "metadata": { 377 | "colab": { 378 | "base_uri": "https://localhost:8080/" 379 | }, 380 | "id": "9LUgIslgEkV2", 381 | "outputId": "06045038-3e40-435a-9b8f-4682370f4662" 382 | }, 383 | "execution_count": null, 384 | "outputs": [ 385 | { 386 | "output_type": "execute_result", 387 | "data": { 388 | "text/plain": [ 389 | "['Argentina', 'EEUU', 'España', 'Uruguay']" 390 | ] 391 | }, 392 | "metadata": {}, 393 | "execution_count": 8 394 | } 395 | ] 396 | }, 397 | { 398 | "cell_type": "code", 399 | "source": [ 400 | "# Agregar valores al final de la lista\n", 401 | "paises = [\"Argentina\", \"Brazil\", \"España\", \"Uruguay\"]\n", 402 | "paises.append(\"EEUU\")\n", 403 | "paises" 404 | ], 405 | "metadata": { 406 | "colab": { 407 | "base_uri": "https://localhost:8080/" 408 | }, 409 | "id": "lG_BYHuSFE_9", 410 | "outputId": "461261ed-bd65-496a-b404-441c28f7ecfc" 411 | }, 412 | "execution_count": null, 413 | "outputs": [ 414 | { 415 | "output_type": "execute_result", 416 | "data": { 417 | "text/plain": [ 418 | "['Argentina', 'Brazil', 'España', 'Uruguay', 'EEUU']" 419 | ] 420 | }, 421 | "metadata": {}, 422 | "execution_count": 9 423 | } 424 | ] 425 | }, 426 | { 427 | "cell_type": "code", 428 | "source": [ 429 | "# Insertar un valor en una posición determinada\n", 430 | "paises = [\"Argentina\", \"Brazil\", \"España\", \"Uruguay\"]\n", 431 | "paises.insert(2, \"EEUU\")\n", 432 | "paises" 433 | ], 434 | "metadata": { 435 | "colab": { 436 | "base_uri": "https://localhost:8080/" 437 | }, 438 | "id": "uWw2rrPSFk0W", 439 | "outputId": "2d92d387-7f10-4ad3-ae47-52f14236c299" 440 | }, 441 | "execution_count": null, 442 | "outputs": [ 443 | { 444 | "output_type": "execute_result", 445 | "data": { 446 | "text/plain": [ 447 | "['Argentina', 'Brazil', 'EEUU', 'España', 'Uruguay']" 448 | ] 449 | }, 450 | "metadata": {}, 451 | "execution_count": 10 452 | } 453 | ] 454 | }, 455 | { 456 | "cell_type": "code", 457 | "source": [ 458 | "# Remover un determinado valor\n", 459 | "paises = [\"Argentina\", \"Brazil\", \"España\", \"Uruguay\"]\n", 460 | "paises.remove('Brazil')\n", 461 | "paises" 462 | ], 463 | "metadata": { 464 | "colab": { 465 | "base_uri": "https://localhost:8080/" 466 | }, 467 | "id": "Kutzih2OcqVU", 468 | "outputId": "ec4ee7ba-4d98-41e4-c0ef-7611c99b243c" 469 | }, 470 | "execution_count": null, 471 | "outputs": [ 472 | { 473 | "output_type": "execute_result", 474 | "data": { 475 | "text/plain": [ 476 | "['Argentina', 'España', 'Uruguay']" 477 | ] 478 | }, 479 | "metadata": {}, 480 | "execution_count": 11 481 | } 482 | ] 483 | }, 484 | { 485 | "cell_type": "code", 486 | "source": [ 487 | "# Remover una determinada posición. \n", 488 | "paises = [\"Argentina\", \"Brazil\", \"España\", \"Uruguay\"]\n", 489 | "item_eliminado = paises.pop(1) # La función pop elimina de la lista la posición indicada y retorna el valor eliminado\n", 490 | "print(paises)\n", 491 | "print(item_eliminado)" 492 | ], 493 | "metadata": { 494 | "colab": { 495 | "base_uri": "https://localhost:8080/" 496 | }, 497 | "id": "w2jhZ7Hvd9IV", 498 | "outputId": "e142ec30-7446-4311-f49f-4bea6049d6a4" 499 | }, 500 | "execution_count": null, 501 | "outputs": [ 502 | { 503 | "output_type": "stream", 504 | "name": "stdout", 505 | "text": [ 506 | "['Argentina', 'España', 'Uruguay']\n", 507 | "Brazil\n" 508 | ] 509 | } 510 | ] 511 | }, 512 | { 513 | "cell_type": "code", 514 | "source": [ 515 | "# Si no se le pasan parámetros a pop se elimina el ultimo valor\n", 516 | "paises = [\"Argentina\", \"Brazil\", \"España\", \"Uruguay\"]\n", 517 | "item_eliminado = paises.pop() \n", 518 | "print(paises)\n", 519 | "print(item_eliminado)" 520 | ], 521 | "metadata": { 522 | "colab": { 523 | "base_uri": "https://localhost:8080/" 524 | }, 525 | "id": "j_DAeKsBff4-", 526 | "outputId": "f42d0933-34d6-4891-faa4-671364a92ceb" 527 | }, 528 | "execution_count": null, 529 | "outputs": [ 530 | { 531 | "output_type": "stream", 532 | "name": "stdout", 533 | "text": [ 534 | "['Argentina', 'Brazil', 'España']\n", 535 | "Uruguay\n" 536 | ] 537 | } 538 | ] 539 | } 540 | ] 541 | } -------------------------------------------------------------------------------- /05-Ciclos.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "language_info": { 6 | "name": "python", 7 | "codemirror_mode": { 8 | "name": "ipython", 9 | "version": 3 10 | }, 11 | "version": "3.7.5-final" 12 | }, 13 | "orig_nbformat": 2, 14 | "file_extension": ".py", 15 | "mimetype": "text/x-python", 16 | "name": "python", 17 | "npconvert_exporter": "python", 18 | "pygments_lexer": "ipython3", 19 | "version": 3, 20 | "kernelspec": { 21 | "name": "python3", 22 | "display_name": "Python 3" 23 | }, 24 | "colab": { 25 | "name": "05-Ciclos.ipynb", 26 | "provenance": [], 27 | "include_colab_link": true 28 | } 29 | }, 30 | "cells": [ 31 | { 32 | "cell_type": "markdown", 33 | "metadata": { 34 | "id": "view-in-github", 35 | "colab_type": "text" 36 | }, 37 | "source": [ 38 | "\"Open" 39 | ] 40 | }, 41 | { 42 | "cell_type": "markdown", 43 | "metadata": { 44 | "id": "RB3x9tKHzCO0" 45 | }, 46 | "source": [ 47 | "# Bucles, Ciclos, Iteraciones, Loops, etc... (Estructuras Iterativas)\n", 48 | "---\n", 49 | "\n", 50 | "**El bloque _for_ y _range_:**" 51 | ] 52 | }, 53 | { 54 | "cell_type": "code", 55 | "metadata": { 56 | "id": "G8n8CB7izCO7" 57 | }, 58 | "source": [ 59 | "# Una estructura repetitiva *for* repite una acción una cantidad definida de veces.\n", 60 | "# Normalmente es utilizado para procesar elementos en una lista.\n", 61 | "# Por ahora aprenderemos su uso más básico con el expresión *range*\n", 62 | "\n", 63 | "def sumarDesdeMHastaN(m, n):\n", 64 | " total = 0\n", 65 | " # Notar que range(x, y) incluye x pero excluye y\n", 66 | " for x in range(m, n+1):\n", 67 | " total += x\n", 68 | " return total\n", 69 | "\n", 70 | "print(sumarDesdeMHastaN(5, 10) == 5+6+7+8+9+10)" 71 | ], 72 | "execution_count": null, 73 | "outputs": [] 74 | }, 75 | { 76 | "cell_type": "markdown", 77 | "metadata": { 78 | "id": "0BUkagOyzCO8" 79 | }, 80 | "source": [ 81 | "**De hecho, no necesitamos un bucle aquí...**" 82 | ] 83 | }, 84 | { 85 | "cell_type": "code", 86 | "metadata": { 87 | "id": "z8HIsy3_zCO8" 88 | }, 89 | "source": [ 90 | "def sumarDesdeMHastaN(m, n):\n", 91 | " return sum(range(m, n+1))\n", 92 | "\n", 93 | "print(sumarDesdeMHastaN(5, 10) == 5+6+7+8+9+10)\n", 94 | "\n", 95 | "# Y hasta podemos hacerlo con un helper, sería la \n", 96 | "# manera más rápida, pero no nos ayuda a demostrar bucles.\n", 97 | "\n", 98 | "def sumarHastaN(n):\n", 99 | " # helper\n", 100 | " return n*(n+1)//2\n", 101 | "\n", 102 | "def sumarDesdeMHastaN_porFormula(m, n):\n", 103 | " return (sumarHastaN(n) - sumarHastaN(m-1))\n", 104 | "\n", 105 | "print(sumFromMToN_porFormula(5, 10) == 5+6+7+8+9+10)" 106 | ], 107 | "execution_count": null, 108 | "outputs": [] 109 | }, 110 | { 111 | "cell_type": "markdown", 112 | "metadata": { 113 | "id": "mQsHPL5hzCO9" 114 | }, 115 | "source": [ 116 | "**Como sería si omitimos el primer parametro?**" 117 | ] 118 | }, 119 | { 120 | "cell_type": "code", 121 | "metadata": { 122 | "id": "Vb5vElwCzCO9" 123 | }, 124 | "source": [ 125 | "def sumarHastaN(n):\n", 126 | " total = 0\n", 127 | " # por default range comienza en 0\n", 128 | " for x in range(n+1):\n", 129 | " total += x\n", 130 | " return total\n", 131 | "\n", 132 | "print(sumarHastaN(5) == 0+1+2+3+4+5)" 133 | ], 134 | "execution_count": null, 135 | "outputs": [] 136 | }, 137 | { 138 | "cell_type": "markdown", 139 | "metadata": { 140 | "id": "bx7CC8pozCO9" 141 | }, 142 | "source": [ 143 | "**Y el tercer parámetro de range?**" 144 | ] 145 | }, 146 | { 147 | "cell_type": "code", 148 | "metadata": { 149 | "id": "UfmxlEN2zCO-" 150 | }, 151 | "source": [ 152 | "def sumarCadaKDesdeMHastaN(m, n, k):\n", 153 | " total = 0\n", 154 | " # el tercer parámetro es el paso (step)\n", 155 | " for x in range(m, n+1, k):\n", 156 | " total += x\n", 157 | " return total\n", 158 | "\n", 159 | "print(sumarCadaKDesdeMHastaN(5, 20, 7) == (5 + 12 + 19))" 160 | ], 161 | "execution_count": null, 162 | "outputs": [] 163 | }, 164 | { 165 | "cell_type": "markdown", 166 | "metadata": { 167 | "id": "S9XXjTnpzCO-" 168 | }, 169 | "source": [ 170 | "**Sumar los números impares desde M hasta N**" 171 | ] 172 | }, 173 | { 174 | "cell_type": "code", 175 | "metadata": { 176 | "id": "jy9AjBRozCO-" 177 | }, 178 | "source": [ 179 | "# También podemos cambiar el paso procesando dentro del bucle\n", 180 | "def sumarImparesDesdeMHastaN(m, n):\n", 181 | " total = 0\n", 182 | " for x in range(m, n+1):\n", 183 | " if (x % 2 == 1):\n", 184 | " total += x\n", 185 | " return total\n", 186 | "\n", 187 | "print(sumarImparesDesdeMHastaN(4, 10) == sumarImparesDesdeMHastaN(5,9) == (5+7+9))" 188 | ], 189 | "execution_count": null, 190 | "outputs": [] 191 | }, 192 | { 193 | "cell_type": "markdown", 194 | "metadata": { 195 | "id": "YWn4bh8pzCO-" 196 | }, 197 | "source": [ 198 | "**Ahora de atrás para adelante**" 199 | ] 200 | }, 201 | { 202 | "cell_type": "code", 203 | "metadata": { 204 | "id": "mZKLzT8yzCO_" 205 | }, 206 | "source": [ 207 | "# range también nos permite usarlo de manera descendente\n", 208 | "# (No es util ahora, pero sirve de ejemplo)\n", 209 | "def sumarImparesDesdeMHastaN(m, n):\n", 210 | " total = 0\n", 211 | " for x in range(n, m-1, -1):\n", 212 | " if (x % 2 == 1):\n", 213 | " total += x\n", 214 | " return total\n", 215 | "\n", 216 | "print(sumarImparesDesdeMHastaN(4, 10) == sumarImparesDesdeMHastaN(5,9) == (5+7+9))" 217 | ], 218 | "execution_count": null, 219 | "outputs": [] 220 | }, 221 | { 222 | "cell_type": "markdown", 223 | "metadata": { 224 | "id": "R5hAGB4izCO_" 225 | }, 226 | "source": [ 227 | "**Bucles enlazados**" 228 | ] 229 | }, 230 | { 231 | "cell_type": "code", 232 | "metadata": { 233 | "id": "oYOWITfjzCO_" 234 | }, 235 | "source": [ 236 | "# Podemos agregar bucles un dentro de otro para repetir acciones\n", 237 | "# en múltiples niveles.\n", 238 | "# Esto imprime un sistema de coordenadas.\n", 239 | "\n", 240 | "def imprimirSistemasDeCoordenadas(xMax, yMax):\n", 241 | " for x in range(xMax+1):\n", 242 | " for y in range(yMax+1):\n", 243 | " print(\"(\", x, \",\", y, \") \", end=\"\")\n", 244 | " print()\n", 245 | "\n", 246 | "imprimirSistemasDeCoordenadas(4, 5)" 247 | ], 248 | "execution_count": null, 249 | "outputs": [] 250 | }, 251 | { 252 | "cell_type": "markdown", 253 | "metadata": { 254 | "id": "Jo0_ZlBazCO_" 255 | }, 256 | "source": [ 257 | "**Otro ejemplo**" 258 | ] 259 | }, 260 | { 261 | "cell_type": "code", 262 | "metadata": { 263 | "id": "WUlqY0tRzCPA" 264 | }, 265 | "source": [ 266 | "def imprimirRectanguloDeAsteriscos(n):\n", 267 | " # Imprime un rectángulo de nxn de asteriscos\n", 268 | " for row in range(n):\n", 269 | " for col in range(n):\n", 270 | " print(\"*\", end=\"\")\n", 271 | " print()\n", 272 | "\n", 273 | "imprimirRectanguloDeAsteriscos(5)" 274 | ], 275 | "execution_count": null, 276 | "outputs": [] 277 | }, 278 | { 279 | "cell_type": "markdown", 280 | "metadata": { 281 | "id": "P9NfZIaZzCPA" 282 | }, 283 | "source": [ 284 | "**...y otro más**" 285 | ] 286 | }, 287 | { 288 | "cell_type": "code", 289 | "metadata": { 290 | "id": "nuqBLdV0zCPA" 291 | }, 292 | "source": [ 293 | "# Qué hace esto? Con cuidado y siendo preciso!\n", 294 | "\n", 295 | "def dibujarMisteriosaFigura(n):\n", 296 | " for fila in range(n):\n", 297 | " print(fila, end=\" \")\n", 298 | " for columna in range(fila):\n", 299 | " print(\"*\", end=\" \")\n", 300 | " print()\n", 301 | "\n", 302 | "dibujarMisteriosaFigura(5)" 303 | ], 304 | "execution_count": null, 305 | "outputs": [] 306 | }, 307 | { 308 | "cell_type": "markdown", 309 | "metadata": { 310 | "id": "whgwnW6lzCPA" 311 | }, 312 | "source": [ 313 | "**El bloque _while_**" 314 | ] 315 | }, 316 | { 317 | "cell_type": "code", 318 | "metadata": { 319 | "id": "74adYaZDzCPB" 320 | }, 321 | "source": [ 322 | "# Usar bucles \"while\" cuando hay un indeterminado número de iteraciones.\n", 323 | "# Cuidado con esto! Por qué?\n", 324 | "\n", 325 | "def digitoDeLaIzquierda(n):\n", 326 | " n = abs(n)\n", 327 | " while (n >= 10):\n", 328 | " n = n//10\n", 329 | " print(n)\n", 330 | " return n\n", 331 | "\n", 332 | "print(digitoDeLaIzquierda(72658489290098) == 7)" 333 | ], 334 | "execution_count": null, 335 | "outputs": [] 336 | }, 337 | { 338 | "cell_type": "markdown", 339 | "metadata": { 340 | "id": "0-oAXwDwzCPB" 341 | }, 342 | "source": [ 343 | "**Ejemplo: el _enésimo_ entero no negativo con alguna propiedad**" 344 | ] 345 | }, 346 | { 347 | "cell_type": "code", 348 | "metadata": { 349 | "id": "Y6jC919DzCPB" 350 | }, 351 | "source": [ 352 | "# eg: Encontrar el enésimo número que es multiplo de 4 o de 7\n", 353 | "def esMultiploDe4o7(x):\n", 354 | " return ((x % 4) == 0) or ((x % 7) == 0)\n", 355 | "\n", 356 | "def enesimoMultiploDe4o7(n):\n", 357 | " encontrado = 0\n", 358 | " adivinado = -1\n", 359 | " while (encontrado <= n):\n", 360 | " adivinado += 1\n", 361 | " if (esMultiploDe4o7(adivinado)):\n", 362 | " encontrado += 1\n", 363 | " return adivinado\n", 364 | "\n", 365 | "print(\"Multiplos de 4 o 7: \", end=\"\")\n", 366 | "for n in range(15):\n", 367 | " print(enesimoMultiploDe4o7(n), end=\" \")\n", 368 | "print()" 369 | ], 370 | "execution_count": null, 371 | "outputs": [] 372 | }, 373 | { 374 | "cell_type": "markdown", 375 | "metadata": { 376 | "id": "oXUvqaS3zCPB" 377 | }, 378 | "source": [ 379 | "**Mal uso: bucle _while_ en un rango fijo**" 380 | ] 381 | }, 382 | { 383 | "cell_type": "code", 384 | "metadata": { 385 | "id": "CECHr2EVzCPB" 386 | }, 387 | "source": [ 388 | "# sumar los números del 1 al 10\n", 389 | "\n", 390 | "def sumarHastaN(n):\n", 391 | " \"\"\"\n", 392 | " TODO: más allá de que funcione, no es un buen estilo.\n", 393 | " Deberíamos usar un bucle \"for\" y no un bucle \"while\".\n", 394 | " \"\"\"\n", 395 | " total = 0\n", 396 | " contador = 1\n", 397 | " while (contador <= n):\n", 398 | " total += contador\n", 399 | " contador += 1\n", 400 | " return total\n", 401 | "\n", 402 | "print(sumarHastaN(5) == 1+2+3+4+5)" 403 | ], 404 | "execution_count": null, 405 | "outputs": [] 406 | }, 407 | { 408 | "cell_type": "markdown", 409 | "metadata": { 410 | "id": "xQFYe2vBzCPC" 411 | }, 412 | "source": [ 413 | "**Otro mal uso: (aunque el lenguaje lo permita!) _break_, _continue_ y _pass_**" 414 | ] 415 | }, 416 | { 417 | "cell_type": "code", 418 | "metadata": { 419 | "id": "OTU3e7rzzCPC" 420 | }, 421 | "source": [ 422 | "# continue, break, y pass son tres keywords (palabras reservadas) \n", 423 | "# usadas en bucles para cambiar el flujo del programa.\n", 424 | "for n in range(200):\n", 425 | " if (n % 3 == 0):\n", 426 | " continue # saltea el resto de la ejecución de esta vuelta\n", 427 | " elif (n == 8):\n", 428 | " break # saltea el resto del bucle, ya no sigue iterando.\n", 429 | " else:\n", 430 | " pass # no hace nada, suelen llamarse \"placeholders\", no es necesario aquí\n", 431 | " print(n, end=\" \")\n", 432 | "print()" 433 | ], 434 | "execution_count": null, 435 | "outputs": [] 436 | }, 437 | { 438 | "cell_type": "markdown", 439 | "metadata": { 440 | "id": "ofSgrvDizCPC" 441 | }, 442 | "source": [ 443 | "**Bucle Infinito con _break_**" 444 | ] 445 | }, 446 | { 447 | "cell_type": "code", 448 | "metadata": { 449 | "id": "B81uqyCnzCPC", 450 | "outputId": "f7490264-74eb-4996-d45d-380402aa3138" 451 | }, 452 | "source": [ 453 | "# Nota- esto es un uso avanzado.\n", 454 | "# No hace falta entender todo el contenido\n", 455 | "\n", 456 | "def leerHastaListo():\n", 457 | " lineas_ingresadas = 0\n", 458 | " while (True):\n", 459 | " texto = input(\"Ingrese un texto (o 'listo' para salir): \")\n", 460 | " if (texto == \"listo\"):\n", 461 | " break\n", 462 | " print(\"- Usted ingresó: \", texto)\n", 463 | " lineas_ingresadas += 1\n", 464 | " print(\"Chau!\")\n", 465 | " return lineas_ingresadas\n", 466 | "\n", 467 | "cant_lineas = leerHastaListo()\n", 468 | "print(\"Usted ingreso\", cant_lineas, \"lineas (sin incluir 'listo').\")" 469 | ], 470 | "execution_count": null, 471 | "outputs": [ 472 | { 473 | "output_type": "stream", 474 | "text": [ 475 | "Usted ingresó: asd\n", 476 | " Usted ingresó: asda\n", 477 | " Usted ingresó: asdasd\n", 478 | " Usted ingresó: asdasd\n", 479 | "Chau!\n", 480 | "Usted ingreso 4 lineas (sin incluir 'listo').\n" 481 | ], 482 | "name": "stdout" 483 | } 484 | ] 485 | }, 486 | { 487 | "cell_type": "markdown", 488 | "metadata": { 489 | "id": "dUCMajvhzCPD" 490 | }, 491 | "source": [ 492 | "" 493 | ] 494 | }, 495 | { 496 | "cell_type": "code", 497 | "metadata": { 498 | "id": "QpLTssX5zCPD" 499 | }, 500 | "source": [ 501 | "# Note: there are faster/better ways. We're just going for clarity and simplicity here.\n", 502 | "def isPrime(n):\n", 503 | " if (n < 2):\n", 504 | " return False\n", 505 | " for factor in range(2,n):\n", 506 | " if (n % factor == 0):\n", 507 | " return False\n", 508 | " return True\n", 509 | "\n", 510 | "# And take it for a spin\n", 511 | "for n in range(100):\n", 512 | " if isPrime(n):\n", 513 | " print(n, end=\" \")\n", 514 | "print()" 515 | ], 516 | "execution_count": null, 517 | "outputs": [] 518 | }, 519 | { 520 | "cell_type": "markdown", 521 | "metadata": { 522 | "id": "PuVIwEMOzCPE" 523 | }, 524 | "source": [ 525 | "**Otra versión, _esPrimoRapido_**" 526 | ] 527 | }, 528 | { 529 | "cell_type": "code", 530 | "metadata": { 531 | "id": "0H-dkNTizCPE" 532 | }, 533 | "source": [ 534 | "# Nota: esto no es la manera más rápida, pero es una buena mejora.\n", 535 | "\n", 536 | "def esPrimoRapido(n):\n", 537 | " if (n < 2):\n", 538 | " return False\n", 539 | " if (n == 2):\n", 540 | " return True\n", 541 | " if (n % 2 == 0):\n", 542 | " return False\n", 543 | " maxFactor = round(n**0.5)\n", 544 | " for factor in range(3,maxFactor+1,2):\n", 545 | " if (n % factor == 0):\n", 546 | " return False\n", 547 | " return True\n", 548 | "\n", 549 | "# y probamos esta versión:\n", 550 | "for n in range(100):\n", 551 | " if esPrimoRapido(n):\n", 552 | " print(n, end=\" \")\n", 553 | "print()" 554 | ], 555 | "execution_count": null, 556 | "outputs": [] 557 | }, 558 | { 559 | "cell_type": "markdown", 560 | "metadata": { 561 | "id": "h7x9krg_zCPE" 562 | }, 563 | "source": [ 564 | "**Verificando si _esPrimoRapido_ es rápido :)**" 565 | ] 566 | }, 567 | { 568 | "cell_type": "code", 569 | "metadata": { 570 | "id": "Q2nP7SURzCPE" 571 | }, 572 | "source": [ 573 | "def esPrimo(n):\n", 574 | " if (n < 2):\n", 575 | " return False\n", 576 | " for factor in range(2,n):\n", 577 | " if (n % factor == 0):\n", 578 | " return False\n", 579 | " return True\n", 580 | "\n", 581 | "def esPrimoRapido(n):\n", 582 | " if (n < 2):\n", 583 | " return False\n", 584 | " if (n == 2):\n", 585 | " return True\n", 586 | " if (n % 2 == 0):\n", 587 | " return False\n", 588 | " maxFactor = round(n**0.5)\n", 589 | " for factor in range(3,maxFactor+1,2):\n", 590 | " if (n % factor == 0):\n", 591 | " return False\n", 592 | " return True\n", 593 | "\n", 594 | "# Verificamos que hacen lo mismo\n", 595 | "for n in range(100):\n", 596 | " assert(esPrimo(n) == esPrimoRapido(n))\n", 597 | "print(\"Parece que funcionan igual!\")\n", 598 | "\n", 599 | "# Ahora veamos si realmente es más veloz\n", 600 | "import time\n", 601 | "unPrimoGrande = 499 # probar 1010809, o 10101023, o 102030407\n", 602 | "print(\"Cronometrando esPrimo(\",unPrimoGrande,\")\", end=\" \")\n", 603 | "time0 = time.time()\n", 604 | "print(\", retorna \", esPrimo(unPrimoGrande), end=\" \")\n", 605 | "time1 = time.time()\n", 606 | "print(\", tiempo = \",(time1-time0)*1000,\"ms\")\n", 607 | "\n", 608 | "print(\"Cronometrando esPrimoRapido(\",unPrimoGrande,\")\", end=\" \")\n", 609 | "time0 = time.time()\n", 610 | "print(\", retorna \", esPrimoRapido(unPrimoGrande), end=\" \")\n", 611 | "time1 = time.time()\n", 612 | "print(\", tiempo = \",(time1-time0)*1000,\"ms\")" 613 | ], 614 | "execution_count": null, 615 | "outputs": [] 616 | }, 617 | { 618 | "cell_type": "markdown", 619 | "metadata": { 620 | "id": "IUFMk7ynzCPF" 621 | }, 622 | "source": [ 623 | "**El enésimo número primo**" 624 | ] 625 | }, 626 | { 627 | "cell_type": "code", 628 | "metadata": { 629 | "id": "a_8IzCOAzCPF" 630 | }, 631 | "source": [ 632 | "def esPrimo(n):\n", 633 | " if (n < 2):\n", 634 | " return False\n", 635 | " if (n == 2):\n", 636 | " return True\n", 637 | " if (n % 2 == 0):\n", 638 | " return False\n", 639 | " maxFactor = round(n**0.5)\n", 640 | " for factor in range(3,maxFactor+1,2):\n", 641 | " if (n % factor == 0):\n", 642 | " return False\n", 643 | " return True\n", 644 | "\n", 645 | "# Adaptando al \"enésimo\" pattern we used above in nthMultipleOf4or7()\n", 646 | "\n", 647 | "def nthPrime(n):\n", 648 | " encontrado = 0\n", 649 | " adiviado = 0\n", 650 | " while (encontrado <= n):\n", 651 | " adiviado += 1\n", 652 | " if (esPrimo(adiviado)):\n", 653 | " encontrado += 1\n", 654 | " return adiviado\n", 655 | "\n", 656 | "# and let's see a list of the primes\n", 657 | "for n in range(10):\n", 658 | " print(n, nthPrime(n))\n", 659 | "print(\"Done!\")" 660 | ], 661 | "execution_count": null, 662 | "outputs": [] 663 | } 664 | ] 665 | } -------------------------------------------------------------------------------- /01-Empezando_a_Programar.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "01-Empezando_a_Programar.ipynb", 7 | "provenance": [], 8 | "include_colab_link": true 9 | }, 10 | "kernelspec": { 11 | "display_name": "Python 3", 12 | "language": "python", 13 | "name": "python3" 14 | }, 15 | "language_info": { 16 | "codemirror_mode": { 17 | "name": "ipython", 18 | "version": 3 19 | }, 20 | "file_extension": ".py", 21 | "mimetype": "text/x-python", 22 | "name": "python", 23 | "nbconvert_exporter": "python", 24 | "pygments_lexer": "ipython3", 25 | "version": "3.7.5" 26 | }, 27 | "toc": { 28 | "base_numbering": 1, 29 | "nav_menu": {}, 30 | "number_sections": true, 31 | "sideBar": true, 32 | "skip_h1_title": false, 33 | "title_cell": "Table of Contents", 34 | "title_sidebar": "Contents", 35 | "toc_cell": false, 36 | "toc_position": {}, 37 | "toc_section_display": true, 38 | "toc_window_display": true 39 | } 40 | }, 41 | "cells": [ 42 | { 43 | "cell_type": "markdown", 44 | "metadata": { 45 | "id": "view-in-github", 46 | "colab_type": "text" 47 | }, 48 | "source": [ 49 | "\"Open" 50 | ] 51 | }, 52 | { 53 | "cell_type": "markdown", 54 | "metadata": { 55 | "id": "DtqRz2JHB0XR" 56 | }, 57 | "source": [ 58 | "# Empezando a Programar\n", 59 | "---\n", 60 | "\n", 61 | "En este curso vamos a aprender los fundamentos básicos de la Programación, utilizando Python como lenguaje. \n", 62 | "\n", 63 | "**Python** es un lenguaje de programación interpretado cuya filosofía hace hincapié en la legibilidad de su código.\n", 64 | "\n", 65 | "Se trata de un lenguaje de programación multiparadigma, ya que soporta orientación a objetos, programación imperativa y, en menor medida, programación funcional.\n", 66 | "\n", 67 | "Es un lenguaje interpretado, dinámico y multiplataforma. (Fuente: [Wikipedia](https://es.wikipedia.org/wiki/Python))\n" 68 | ] 69 | }, 70 | { 71 | "cell_type": "markdown", 72 | "metadata": { 73 | "id": "p7tYuHrPRlXs" 74 | }, 75 | "source": [ 76 | "### Ejecutando Python\n", 77 | "Para ejecutar Python, previamente debemos:\n", 78 | "* Instalar la versión 3.7 de Python, descargándola de [python.org](https://python.org),\n", 79 | "* Instalar [Visual Studio Code](https://code.visualstudio.com/download) o el Editor de código que prefieras (PyCharm, Geany,Vi, etc)\n", 80 | "* Iniciar tu Editor de Código,\n", 81 | "* Editar tu archivo de texto y guardarlo con la extensión _.py_,\n", 82 | "* Ejecutar tu código.\n" 83 | ] 84 | }, 85 | { 86 | "cell_type": "markdown", 87 | "metadata": { 88 | "id": "XWvfYVDGGBrd" 89 | }, 90 | "source": [ 91 | "\n", 92 | "### \"Hola Mundo\" en Python\n", 93 | "Ahora, escribiremos nuestro primer programa en Python, un script sencillo que muestra en pantalla el texto \"Hola Mundo\":" 94 | ] 95 | }, 96 | { 97 | "cell_type": "code", 98 | "metadata": { 99 | "id": "rDBAbBnH_3Sg", 100 | "colab": { 101 | "base_uri": "https://localhost:8080/" 102 | }, 103 | "outputId": "e0459e25-c0ea-47a6-c86a-9f3ed9d66de8" 104 | }, 105 | "source": [ 106 | "print(\"Hola Mundo!\")" 107 | ], 108 | "execution_count": 1, 109 | "outputs": [ 110 | { 111 | "output_type": "stream", 112 | "text": [ 113 | "Hola Mundo!\n" 114 | ], 115 | "name": "stdout" 116 | } 117 | ] 118 | }, 119 | { 120 | "cell_type": "markdown", 121 | "metadata": { 122 | "id": "zsMKjKiCG5n0" 123 | }, 124 | "source": [ 125 | "### Comentarios en el código\n", 126 | "Podemos hacer comentarios en nuestro código. Estos comentarios no son interpretados por el lenguaje pero nos permiten recordar que hacemos en cada porción de código. Utilizar comentarios es una buena práctica de programación." 127 | ] 128 | }, 129 | { 130 | "cell_type": "code", 131 | "metadata": { 132 | "id": "Fp61JELMHmRa", 133 | "colab": { 134 | "base_uri": "https://localhost:8080/" 135 | }, 136 | "outputId": "537a6ad6-9db7-4b9b-eabf-931c022a5ffb" 137 | }, 138 | "source": [ 139 | "print(\"Hola Mundo!\") # Esto es un comentario\n", 140 | "# print(\"Qué hace esta línea de código?\")" 141 | ], 142 | "execution_count": 2, 143 | "outputs": [ 144 | { 145 | "output_type": "stream", 146 | "text": [ 147 | "Hola Mundo!\n" 148 | ], 149 | "name": "stdout" 150 | } 151 | ] 152 | }, 153 | { 154 | "cell_type": "markdown", 155 | "metadata": { 156 | "id": "3mYfjlAFJQs0" 157 | }, 158 | "source": [ 159 | "### Salidas básicas en Pantalla\n", 160 | "Como vimos en el programita anterior, podemos mostrar textos, números y resultados de operaciones, entre otras cosas, por pantalla. La instrucción básica que permtie esto es _print_.\n", 161 | "\n", 162 | "__Uso básico de _print_:__" 163 | ] 164 | }, 165 | { 166 | "cell_type": "code", 167 | "metadata": { 168 | "id": "F_6ezzzNJQD6", 169 | "colab": { 170 | "base_uri": "https://localhost:8080/" 171 | }, 172 | "outputId": "65a15db8-6dfd-42fa-eb25-232ea77bb300" 173 | }, 174 | "source": [ 175 | "print(\"Carpe\")\n", 176 | "print(\"diem\")" 177 | ], 178 | "execution_count": 3, 179 | "outputs": [ 180 | { 181 | "output_type": "stream", 182 | "text": [ 183 | "Carpe\n", 184 | "diem\n" 185 | ], 186 | "name": "stdout" 187 | } 188 | ] 189 | }, 190 | { 191 | "cell_type": "markdown", 192 | "metadata": { 193 | "id": "0udC-1NMKCKK" 194 | }, 195 | "source": [ 196 | "__Mostrar en la misma línea:__" 197 | ] 198 | }, 199 | { 200 | "cell_type": "code", 201 | "metadata": { 202 | "id": "nmpqZB31J6JG", 203 | "colab": { 204 | "base_uri": "https://localhost:8080/" 205 | }, 206 | "outputId": "796a725c-75c2-453c-f0b0-a8573c97e071" 207 | }, 208 | "source": [ 209 | "# Podemos separar múltiples valores entre comas (\",\")\n", 210 | "print(\"Carpe\", \"diem\")\n", 211 | "\n", 212 | "# También podemos usar el parámetro end=\"\" si queremos que aparezca en la misma línea\n", 213 | "print(\"Carpe \", end=\"\")\n", 214 | "print(\"diem\")" 215 | ], 216 | "execution_count": 4, 217 | "outputs": [ 218 | { 219 | "output_type": "stream", 220 | "text": [ 221 | "Carpe diem\n", 222 | "Carpe diem\n" 223 | ], 224 | "name": "stdout" 225 | } 226 | ] 227 | }, 228 | { 229 | "cell_type": "markdown", 230 | "metadata": { 231 | "id": "wechVjeNKd89" 232 | }, 233 | "source": [ 234 | "__Imprimir usando cadenas _\"f\"_:__\n", 235 | "\n", 236 | "Las cadenas f proporcionan una forma sencilla de integrar variables y expresiones dentro de una cadena de texto de forma muy sencilla." 237 | ] 238 | }, 239 | { 240 | "cell_type": "code", 241 | "metadata": { 242 | "id": "dN1iL1hCLjRg", 243 | "colab": { 244 | "base_uri": "https://localhost:8080/" 245 | }, 246 | "outputId": "d1eb20fc-df6d-4f6c-9f8e-dc68fc83eb1d" 247 | }, 248 | "source": [ 249 | "x = 44463\n", 250 | "y = 42\n", 251 | "# Podemos poner los nombres de variables entre {llaves} para imprimir valores:\n", 252 | "print(f'Sabías que {x} + {y} es {x+y}?')" 253 | ], 254 | "execution_count": 5, 255 | "outputs": [ 256 | { 257 | "output_type": "stream", 258 | "text": [ 259 | "Sabías que 44463 + 42 es 44505?\n" 260 | ], 261 | "name": "stdout" 262 | } 263 | ] 264 | }, 265 | { 266 | "cell_type": "markdown", 267 | "metadata": { 268 | "id": "Wjta-tS_M9zp" 269 | }, 270 | "source": [ 271 | "### Importación de módulos\n", 272 | "Los lenguajes de programación cuentan con módulos que permiten reutilizar código de otros programadores así como invocar funciones complejas ya existentes en el lenguaje.\n", 273 | "\n", 274 | "Por ejemplo, existe un módulo _math_ que cuenta con operaciones matemáticas ya definidas para que podamos usarlas sin necesidad de programar como se hace la operación:" 275 | ] 276 | }, 277 | { 278 | "cell_type": "code", 279 | "metadata": { 280 | "id": "PKjQIkB4OlqQ", 281 | "colab": { 282 | "base_uri": "https://localhost:8080/", 283 | "height": 180 284 | }, 285 | "outputId": "6f50b888-c78f-4f8a-d0ce-c634c7590426" 286 | }, 287 | "source": [ 288 | "# Si queremos usar la función factorial podemos hacerlo de la siguiente manera:\n", 289 | "print(math.factorial(5))" 290 | ], 291 | "execution_count": 6, 292 | "outputs": [ 293 | { 294 | "output_type": "error", 295 | "ename": "NameError", 296 | "evalue": "ignored", 297 | "traceback": [ 298 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 299 | "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", 300 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# Si queremos usar la función factorial podemos hacerlo de la siguiente manera:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmath\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mfactorial\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m5\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 301 | "\u001b[0;31mNameError\u001b[0m: name 'math' is not defined" 302 | ] 303 | } 304 | ] 305 | }, 306 | { 307 | "cell_type": "markdown", 308 | "metadata": { 309 | "id": "kZ7WyPa9PLbp" 310 | }, 311 | "source": [ 312 | "__¿Qué sucedió?__ El error anterior se debe a que primero debemos importar el módulo _math_ de la siguiente manera:" 313 | ] 314 | }, 315 | { 316 | "cell_type": "code", 317 | "metadata": { 318 | "id": "E0-qMBVVPTjP", 319 | "colab": { 320 | "base_uri": "https://localhost:8080/" 321 | }, 322 | "outputId": "d18fa38e-3dc7-4df5-a1d8-9912a6a9690b" 323 | }, 324 | "source": [ 325 | "import math\n", 326 | "\n", 327 | "print(math.factorial(5)) # Ahora si! Mucho mejor..." 328 | ], 329 | "execution_count": 8, 330 | "outputs": [ 331 | { 332 | "output_type": "stream", 333 | "text": [ 334 | "120\n" 335 | ], 336 | "name": "stdout" 337 | } 338 | ] 339 | }, 340 | { 341 | "cell_type": "markdown", 342 | "metadata": { 343 | "id": "ZJPblvkGSN_d" 344 | }, 345 | "source": [ 346 | "## Errores de sintaxis, de tiempo de ejecución y lógicos\n", 347 | "\n", 348 | "Lamentablemente, cuando programamos tendremos errores. Podríamos categorizar a los errores en tres tipos: de sintaxis, de runtime y lógicos (o semánticos):\n", 349 | "\n", 350 | "* __Errores de sintaxis:__ (en inglés **_syntax errors_**) Estos errores se dan cuando el compilador/intérprete del lenguaje de programación no entiende lo que \"le queremos decir\".\n", 351 | "* __Errores en tiempo de ejecución:__ (en inglés **_runtime errors_**) Errores que ocurren cuando el programa está en ejecución.\n", 352 | "* __Errores lógicos:__ Son los errores de los programas cuando no resuelven el problema o arrojan resultados incorrectos." 353 | ] 354 | }, 355 | { 356 | "cell_type": "code", 357 | "metadata": { 358 | "id": "UssYjP3DTh8Z", 359 | "colab": { 360 | "base_uri": "https://localhost:8080/", 361 | "height": 129 362 | }, 363 | "outputId": "a22833b8-276f-4baf-da37-76ea90860808" 364 | }, 365 | "source": [ 366 | "# En la siguiente línea de código olvidaremos voluntariamente la comilla final\n", 367 | "# en el texto \"Uh oh!\"\n", 368 | "\n", 369 | "print(\"Uh oh!) # ERROR! missing close-quote\n", 370 | "\n", 371 | "# Python output:\n", 372 | "# SyntaxError: EOL while scanning string literal" 373 | ], 374 | "execution_count": 9, 375 | "outputs": [ 376 | { 377 | "output_type": "error", 378 | "ename": "SyntaxError", 379 | "evalue": "ignored", 380 | "traceback": [ 381 | "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m4\u001b[0m\n\u001b[0;31m print(\"Uh oh!) # ERROR! missing close-quote\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m EOL while scanning string literal\n" 382 | ] 383 | } 384 | ] 385 | }, 386 | { 387 | "cell_type": "markdown", 388 | "metadata": { 389 | "id": "DgrumfGZUGnU" 390 | }, 391 | "source": [ 392 | "__Errores de runtime (tiempo de ejecución):__ estos errores se dan cuando las condiciones a las que llega el programa generan un error para un set de datos determinado." 393 | ] 394 | }, 395 | { 396 | "cell_type": "code", 397 | "metadata": { 398 | "id": "oZqb1VyoUP15", 399 | "colab": { 400 | "base_uri": "https://localhost:8080/", 401 | "height": 214 402 | }, 403 | "outputId": "cfd795b4-8a07-4e0f-9ed0-05b0ba5e88d4" 404 | }, 405 | "source": [ 406 | "print(1/0) # ERROR! Division by zero!\n", 407 | "\n", 408 | "# Python output:\n", 409 | "# ZeroDivisionError: integer division or modulo by zero" 410 | ], 411 | "execution_count": 10, 412 | "outputs": [ 413 | { 414 | "output_type": "error", 415 | "ename": "ZeroDivisionError", 416 | "evalue": "ignored", 417 | "traceback": [ 418 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 419 | "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", 420 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# ERROR! Division by zero!\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 2\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;31m# Python output:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;31m# ZeroDivisionError: integer division or modulo by zero\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 421 | "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" 422 | ] 423 | } 424 | ] 425 | }, 426 | { 427 | "cell_type": "markdown", 428 | "metadata": { 429 | "id": "xtktqhggUWxR" 430 | }, 431 | "source": [ 432 | "__Errores de lógicos (o semánticos):__ estos errores se dan cuando el lenguaje entiende lo que tiene que hacer, lo hace pero no es lo que esperamos que haga." 433 | ] 434 | }, 435 | { 436 | "cell_type": "code", 437 | "metadata": { 438 | "id": "SbQHmhXzWHB_", 439 | "colab": { 440 | "base_uri": "https://localhost:8080/" 441 | }, 442 | "outputId": "c4b91592-5518-4b4f-884b-c8ec7a3298e7" 443 | }, 444 | "source": [ 445 | "print(\"2+2=5\") # ERROR! Es incorrecto!!!\n", 446 | "\n", 447 | "# Salida de Python:\n", 448 | "# 2+2=5" 449 | ], 450 | "execution_count": 11, 451 | "outputs": [ 452 | { 453 | "output_type": "stream", 454 | "text": [ 455 | "2+2=5\n" 456 | ], 457 | "name": "stdout" 458 | } 459 | ] 460 | }, 461 | { 462 | "cell_type": "markdown", 463 | "metadata": { 464 | "id": "-4n2-Nw-XhzD" 465 | }, 466 | "source": [ 467 | "### Entrada de Datos Básica\n", 468 | "\n", 469 | "En los lenguajes de programación vamos a necesitar ingresar datos para resolver problemas. En Python, podemos solicitar la entrada de datos por teclado con la instrucción _input_.\n", 470 | "\n", 471 | "__Podemos ingresar textos (a partir de ahora _strings_):__" 472 | ] 473 | }, 474 | { 475 | "cell_type": "code", 476 | "metadata": { 477 | "id": "6nzMO1ESYVCw", 478 | "colab": { 479 | "base_uri": "https://localhost:8080/" 480 | }, 481 | "outputId": "4c296ed3-8a08-4f51-cae7-11aa60d87d07" 482 | }, 483 | "source": [ 484 | "# Ingresa un texto\n", 485 | "nombre = input(\"Ingresá tu nombre: \")\n", 486 | "\n", 487 | "# Lo muestra en pantalla\n", 488 | "print(\"Tu nombre es:\", nombre)" 489 | ], 490 | "execution_count": 12, 491 | "outputs": [ 492 | { 493 | "output_type": "stream", 494 | "text": [ 495 | "Ingresá tu nombre: Juan Manuel\n", 496 | "Tu nombre es: Juan Manuel\n" 497 | ], 498 | "name": "stdout" 499 | } 500 | ] 501 | }, 502 | { 503 | "cell_type": "markdown", 504 | "metadata": { 505 | "id": "3it7YCQLY7qv" 506 | }, 507 | "source": [ 508 | "__Si ingresamos números debemos tener cuidado:__\n", 509 | "Python por defecto lo guardará como string (texto).\n" 510 | ] 511 | }, 512 | { 513 | "cell_type": "code", 514 | "metadata": { 515 | "id": "XQ-DmG3nZHSw", 516 | "colab": { 517 | "base_uri": "https://localhost:8080/", 518 | "height": 197 519 | }, 520 | "outputId": "4551c580-ad4d-4a97-d5aa-7ff9be5b9439" 521 | }, 522 | "source": [ 523 | "x = input(\"Ingrese un número: \")\n", 524 | "print(f\"La mitad de {x} es {x/2}\") # Error!" 525 | ], 526 | "execution_count": 13, 527 | "outputs": [ 528 | { 529 | "output_type": "stream", 530 | "text": [ 531 | "Ingrese un número: 12\n" 532 | ], 533 | "name": "stdout" 534 | }, 535 | { 536 | "output_type": "error", 537 | "ename": "TypeError", 538 | "evalue": "ignored", 539 | "traceback": [ 540 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 541 | "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", 542 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mx\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0minput\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Ingrese un número: \"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34mf\"La mitad de {x} es {x/2}\"\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# Error!\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 543 | "\u001b[0;31mTypeError\u001b[0m: unsupported operand type(s) for /: 'str' and 'int'" 544 | ] 545 | } 546 | ] 547 | }, 548 | { 549 | "cell_type": "markdown", 550 | "metadata": { 551 | "id": "oZxRpIypZeOL" 552 | }, 553 | "source": [ 554 | "Resolvemos esto con la función _int_, que convertirá el dato a numérico:" 555 | ] 556 | }, 557 | { 558 | "cell_type": "code", 559 | "metadata": { 560 | "id": "GjDNjAneZmfd", 561 | "colab": { 562 | "base_uri": "https://localhost:8080/" 563 | }, 564 | "outputId": "2a99953d-b1d4-4a75-87a2-e9c10cf1331f" 565 | }, 566 | "source": [ 567 | "# Agregamos la función int()\n", 568 | "x = int(input(\"Ingrese un número: \"))\n", 569 | "\n", 570 | "# Mostramos la mitad en pantalla\n", 571 | "print(f\"La mitad de {x} es {x/2}\") # Ahora funciona!\n" 572 | ], 573 | "execution_count": 14, 574 | "outputs": [ 575 | { 576 | "output_type": "stream", 577 | "text": [ 578 | "Ingrese un número: 12\n", 579 | "La mitad de 12 es 6.0\n" 580 | ], 581 | "name": "stdout" 582 | } 583 | ] 584 | } 585 | ] 586 | } -------------------------------------------------------------------------------- /04-Condicionales.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "language_info": { 6 | "name": "python", 7 | "codemirror_mode": { 8 | "name": "ipython", 9 | "version": 3 10 | }, 11 | "version": "3.7.5-final" 12 | }, 13 | "orig_nbformat": 2, 14 | "file_extension": ".py", 15 | "mimetype": "text/x-python", 16 | "name": "python", 17 | "npconvert_exporter": "python", 18 | "pygments_lexer": "ipython3", 19 | "version": 3, 20 | "kernelspec": { 21 | "name": "python3", 22 | "display_name": "Python 3" 23 | }, 24 | "colab": { 25 | "name": "04-Condicionales.ipynb", 26 | "provenance": [], 27 | "include_colab_link": true 28 | } 29 | }, 30 | "cells": [ 31 | { 32 | "cell_type": "markdown", 33 | "metadata": { 34 | "id": "view-in-github", 35 | "colab_type": "text" 36 | }, 37 | "source": [ 38 | "\"Open" 39 | ] 40 | }, 41 | { 42 | "cell_type": "markdown", 43 | "metadata": { 44 | "id": "Fs2nCmd6BaYh" 45 | }, 46 | "source": [ 47 | "# Condicionales\n", 48 | "---\n", 49 | "\n", 50 | "**El bloque _if_:**" 51 | ] 52 | }, 53 | { 54 | "cell_type": "code", 55 | "metadata": { 56 | "id": "XsyKt1q1BaYo", 57 | "colab": { 58 | "base_uri": "https://localhost:8080/" 59 | }, 60 | "outputId": "6ec77406-3c70-45eb-8a4f-e067e1df79ba" 61 | }, 62 | "source": [ 63 | "def f(x):\n", 64 | " print(\"A\", end=\"\")\n", 65 | " if (x == 0):\n", 66 | " print(\"B\", end=\"\")\n", 67 | " print(\"C\", end=\"\")\n", 68 | " print(\"D\")\n", 69 | "\n", 70 | "f(0)\n", 71 | "f(1)" 72 | ], 73 | "execution_count": null, 74 | "outputs": [ 75 | { 76 | "output_type": "stream", 77 | "text": [ 78 | "ABCD\n", 79 | "AD\n" 80 | ], 81 | "name": "stdout" 82 | } 83 | ] 84 | }, 85 | { 86 | "cell_type": "markdown", 87 | "metadata": { 88 | "id": "I37NRl16BaYp" 89 | }, 90 | "source": [ 91 | "**Un ejemplo más interesante:**" 92 | ] 93 | }, 94 | { 95 | "cell_type": "code", 96 | "metadata": { 97 | "id": "53o1tywfBaYp", 98 | "colab": { 99 | "base_uri": "https://localhost:8080/" 100 | }, 101 | "outputId": "0678d434-9afc-4ae5-d156-932399f6a3e4" 102 | }, 103 | "source": [ 104 | "# En estos ejemplos se define una función abs(n),\n", 105 | "# Es un buen ejemplo, pero recordemos que ya tenemos el abs de Python (builtin).\n", 106 | "\n", 107 | "def abs1(n):\n", 108 | " if (n < 0):\n", 109 | " n = -n\n", 110 | " return n\n", 111 | "\n", 112 | "# otra vez, pero la misma línea indentada.\n", 113 | "\n", 114 | "def abs2(n):\n", 115 | " if (n < 0): n = -n # Solo indentamos así líneas muy cortas.\n", 116 | " return n\n", 117 | "\n", 118 | "# otra vez, pero con varios returns\n", 119 | "\n", 120 | "def abs3(n):\n", 121 | " if (n < 0):\n", 122 | " n = -n\n", 123 | " return n\n", 124 | "\n", 125 | "# además: se puede hacer con aritmética booleana, pero no!\n", 126 | "\n", 127 | "def abs4(n):\n", 128 | " return (n < 0)*(-n) + (n>=0)*(n) # esto es horrible!\n", 129 | " \n", 130 | "# ahora vemos como funciona esto:\n", 131 | "\n", 132 | "print(\"abs1(5) =\", abs1(5), \"and abs1(-5) =\", abs1(-5))\n", 133 | "print(\"abs2(5) =\", abs2(5), \"and abs2(-5) =\", abs2(-5))\n", 134 | "print(\"abs3(5) =\", abs3(5), \"and abs3(-5) =\", abs3(-5))\n", 135 | "print(\"abs4(5) =\", abs4(5), \"and abs4(-5) =\", abs4(-5))" 136 | ], 137 | "execution_count": null, 138 | "outputs": [ 139 | { 140 | "output_type": "stream", 141 | "text": [ 142 | "abs1(5) = 5 and abs1(-5) = 5\n", 143 | "abs2(5) = 5 and abs2(-5) = 5\n", 144 | "abs3(5) = 5 and abs3(-5) = 5\n", 145 | "abs4(5) = 5 and abs4(-5) = 5\n" 146 | ], 147 | "name": "stdout" 148 | } 149 | ] 150 | }, 151 | { 152 | "cell_type": "markdown", 153 | "metadata": { 154 | "id": "sTRQoh7SBaYq" 155 | }, 156 | "source": [ 157 | "**El bloque _if-else_:**\n" 158 | ] 159 | }, 160 | { 161 | "cell_type": "code", 162 | "metadata": { 163 | "id": "ld0A5pxBBaYq", 164 | "colab": { 165 | "base_uri": "https://localhost:8080/" 166 | }, 167 | "outputId": "67129bce-14dc-401c-f305-0d1294cf4dad" 168 | }, 169 | "source": [ 170 | "def f(x):\n", 171 | " print(\"A\", end=\"\")\n", 172 | " if (x == 0):\n", 173 | " print(\"B\", end=\"\")\n", 174 | " print(\"C\", end=\"\")\n", 175 | " else:\n", 176 | " print(\"D\", end=\"\")\n", 177 | " if (x == 1):\n", 178 | " print(\"E\", end=\"\")\n", 179 | " else:\n", 180 | " print(\"F\", end=\"\")\n", 181 | " print(\"G\")\n", 182 | "\n", 183 | "f(0)\n", 184 | "f(1)\n", 185 | "f(2)" 186 | ], 187 | "execution_count": null, 188 | "outputs": [ 189 | { 190 | "output_type": "stream", 191 | "text": [ 192 | "ABCG\n", 193 | "ADEG\n", 194 | "ADFG\n" 195 | ], 196 | "name": "stdout" 197 | } 198 | ] 199 | }, 200 | { 201 | "cell_type": "markdown", 202 | "metadata": { 203 | "id": "3gpGp9cgBaYq" 204 | }, 205 | "source": [ 206 | "**Volviendo a _abs(n)_:**" 207 | ] 208 | }, 209 | { 210 | "cell_type": "code", 211 | "metadata": { 212 | "id": "ogyJpWiRBaYq", 213 | "colab": { 214 | "base_uri": "https://localhost:8080/" 215 | }, 216 | "outputId": "12911647-e0b8-4694-d852-c7cc438df97b" 217 | }, 218 | "source": [ 219 | "# Prohibido en IntroProg\n", 220 | "def abs5(n):\n", 221 | " if (n >= 0):\n", 222 | " return n\n", 223 | " else:\n", 224 | " return -n\n", 225 | "\n", 226 | "# o, si prefieren...\n", 227 | "\n", 228 | "def abs6(n):\n", 229 | " if (n >= 0):\n", 230 | " sign = +1\n", 231 | " else:\n", 232 | " sign = -1\n", 233 | " return sign * n\n", 234 | "\n", 235 | "print(\"abs5(5) =\", abs5(5), \"and abs5(-5) =\", abs5(-5))\n", 236 | "print(\"abs6(5) =\", abs6(5), \"and abs6(-5) =\", abs6(-5))" 237 | ], 238 | "execution_count": null, 239 | "outputs": [ 240 | { 241 | "output_type": "stream", 242 | "text": [ 243 | "abs5(5) = 5 and abs5(-5) = 5\n", 244 | "abs6(5) = 5 and abs6(-5) = 5\n" 245 | ], 246 | "name": "stdout" 247 | } 248 | ] 249 | }, 250 | { 251 | "cell_type": "markdown", 252 | "metadata": { 253 | "id": "CENWg5FzBaYr" 254 | }, 255 | "source": [ 256 | "**El bloque _if-elif-else_:**" 257 | ] 258 | }, 259 | { 260 | "cell_type": "code", 261 | "metadata": { 262 | "id": "SBTJ4ho2BaYr", 263 | "colab": { 264 | "base_uri": "https://localhost:8080/" 265 | }, 266 | "outputId": "94b8f90e-fa10-4263-d216-556bc041593b" 267 | }, 268 | "source": [ 269 | "def f(x):\n", 270 | " print(\"A\", end=\"\")\n", 271 | " if (x == 0):\n", 272 | " print(\"B\", end=\"\")\n", 273 | " print(\"C\", end=\"\")\n", 274 | " elif (x == 1):\n", 275 | " print(\"D\", end=\"\")\n", 276 | " else:\n", 277 | " print(\"E\", end=\"\")\n", 278 | " if (x == 2):\n", 279 | " print(\"F\", end=\"\")\n", 280 | " else:\n", 281 | " print(\"G\", end=\"\")\n", 282 | " print(\"H\")\n", 283 | "\n", 284 | "f(0)\n", 285 | "f(1)\n", 286 | "f(2)\n", 287 | "f(3)" 288 | ], 289 | "execution_count": null, 290 | "outputs": [ 291 | { 292 | "output_type": "stream", 293 | "text": [ 294 | "ABCH\n", 295 | "ADH\n", 296 | "AEFH\n", 297 | "AEGH\n" 298 | ], 299 | "name": "stdout" 300 | } 301 | ] 302 | }, 303 | { 304 | "cell_type": "markdown", 305 | "metadata": { 306 | "id": "rROAMg0SBaYr" 307 | }, 308 | "source": [ 309 | "**Un ejemplo más interesante:**" 310 | ] 311 | }, 312 | { 313 | "cell_type": "code", 314 | "metadata": { 315 | "id": "LPzI-c7DBaYs", 316 | "colab": { 317 | "base_uri": "https://localhost:8080/" 318 | }, 319 | "outputId": "8b6bf62e-1c69-4253-b42d-5d003e02ca2d" 320 | }, 321 | "source": [ 322 | "def cantidadDeRaices(a, b, c):\n", 323 | " # Retorna la cantidad de raices (ceros) de un polinomio de grado 2.\n", 324 | " # y = a*x**2 + b*x + c\n", 325 | " raices = 0 \n", 326 | " d = b**2 - 4*a*c\n", 327 | " if (d > 0):\n", 328 | " raices = 2\n", 329 | " elif (d == 0):\n", 330 | " raices = 1\n", 331 | " else:\n", 332 | " raices = 0\n", 333 | " \n", 334 | " return raices\n", 335 | "\n", 336 | "print(\"y = 4*x**2 + 5*x + 1 tiene\", cantidadDeRaices(4,5,1), \"raices(s).\")\n", 337 | "print(\"y = 4*x**2 + 4*x + 1 tiene\", cantidadDeRaices(4,4,1), \"raices(s).\")\n", 338 | "print(\"y = 4*x**2 + 3*x + 1 tiene\", cantidadDeRaices(4,3,1), \"raices(s).\")" 339 | ], 340 | "execution_count": 2, 341 | "outputs": [ 342 | { 343 | "output_type": "stream", 344 | "text": [ 345 | "y = 4*x**2 + 5*x + 1 tiene 2 raices(s).\n", 346 | "y = 4*x**2 + 4*x + 1 tiene 1 raices(s).\n", 347 | "y = 4*x**2 + 3*x + 1 tiene 0 raices(s).\n" 348 | ], 349 | "name": "stdout" 350 | } 351 | ] 352 | }, 353 | { 354 | "cell_type": "markdown", 355 | "metadata": { 356 | "id": "KMycDhkNBaYs" 357 | }, 358 | "source": [ 359 | "**Otro ejemplo:**" 360 | ] 361 | }, 362 | { 363 | "cell_type": "code", 364 | "metadata": { 365 | "id": "t2FD-BiIBaYs", 366 | "colab": { 367 | "base_uri": "https://localhost:8080/" 368 | }, 369 | "outputId": "dbe87846-5b1a-4284-f555-4aba77ef66c5" 370 | }, 371 | "source": [ 372 | "def obtenerNivel(puntos):\n", 373 | " if (puntos >= 90):\n", 374 | " puntos = \"A\"\n", 375 | " elif (puntos >= 80):\n", 376 | " puntos = \"B\"\n", 377 | " elif (puntos >= 70):\n", 378 | " puntos = \"C\"\n", 379 | " elif (puntos >= 60):\n", 380 | " puntos = \"D\"\n", 381 | " else:\n", 382 | " puntos = \"F\"\n", 383 | " return puntos\n", 384 | "\n", 385 | "print(\"103 -->\", obtenerNivel(103))\n", 386 | "print(\" 88 -->\", obtenerNivel(88))\n", 387 | "print(\" 70 -->\", obtenerNivel(70))\n", 388 | "print(\" 61 -->\", obtenerNivel(61))\n", 389 | "print(\" 22 -->\", obtenerNivel(22))" 390 | ], 391 | "execution_count": null, 392 | "outputs": [ 393 | { 394 | "output_type": "stream", 395 | "text": [ 396 | "103 --> A\n", 397 | " 88 --> B\n", 398 | " 70 --> C\n", 399 | " 61 --> D\n", 400 | " 22 --> F\n" 401 | ], 402 | "name": "stdout" 403 | } 404 | ] 405 | }, 406 | { 407 | "cell_type": "markdown", 408 | "metadata": { 409 | "id": "Cg26YJPSBaYs" 410 | }, 411 | "source": [ 412 | "**Uso de _if-else_ como expresión:**" 413 | ] 414 | }, 415 | { 416 | "cell_type": "code", 417 | "metadata": { 418 | "id": "EV9ojtueBaYt", 419 | "colab": { 420 | "base_uri": "https://localhost:8080/" 421 | }, 422 | "outputId": "dc9c27e3-22a4-46db-b151-a8b51b3b05fe" 423 | }, 424 | "source": [ 425 | "# expresión if-else (no es un bloque if-else!)\n", 426 | "\n", 427 | "def abs7(n):\n", 428 | " return n if (n >= 0) else -n\n", 429 | "\n", 430 | "print(\"abs7(5) =\", abs7(5), \"and abs7(-5) =\", abs7(-5))" 431 | ], 432 | "execution_count": null, 433 | "outputs": [ 434 | { 435 | "output_type": "stream", 436 | "text": [ 437 | "abs7(5) = 5 and abs7(-5) = 5\n" 438 | ], 439 | "name": "stdout" 440 | } 441 | ] 442 | }, 443 | { 444 | "cell_type": "markdown", 445 | "metadata": { 446 | "id": "nkHGi3QjBaYt" 447 | }, 448 | "source": [ 449 | "---\n", 450 | "\n", 451 | "**Uso incorrecto**\n", 452 | "\n", 453 | "**_NOTA:_ Esta sección es sobre _estilo_ y no sobre _correctitud_. Todos lo ejemplos funcionan, pero algunos son más ingeniosos que otros.**" 454 | ] 455 | }, 456 | { 457 | "cell_type": "markdown", 458 | "metadata": { 459 | "id": "i4bz_pMhBaYt" 460 | }, 461 | "source": [ 462 | "**Negando condiciones:**" 463 | ] 464 | }, 465 | { 466 | "cell_type": "code", 467 | "metadata": { 468 | "id": "9vpvdtUZBaYt", 469 | "colab": { 470 | "base_uri": "https://localhost:8080/" 471 | }, 472 | "outputId": "464e0fd1-a26a-41a3-a2d3-fcba267d1391" 473 | }, 474 | "source": [ 475 | "# Incorrecto:\n", 476 | "b = True\n", 477 | "if (not b):\n", 478 | " print('NO')\n", 479 | "else:\n", 480 | " print('SI')" 481 | ], 482 | "execution_count": null, 483 | "outputs": [ 484 | { 485 | "output_type": "stream", 486 | "text": [ 487 | "SI\n" 488 | ], 489 | "name": "stdout" 490 | } 491 | ] 492 | }, 493 | { 494 | "cell_type": "code", 495 | "metadata": { 496 | "id": "yatwsIauBaYt", 497 | "colab": { 498 | "base_uri": "https://localhost:8080/" 499 | }, 500 | "outputId": "cd9f23f3-6748-4eff-e7c4-79124cec77ec" 501 | }, 502 | "source": [ 503 | "# Correcto:\n", 504 | "b = True\n", 505 | "if (b):\n", 506 | " print('SI')\n", 507 | "else:\n", 508 | " print('NO')" 509 | ], 510 | "execution_count": null, 511 | "outputs": [ 512 | { 513 | "output_type": "stream", 514 | "text": [ 515 | "SI\n" 516 | ], 517 | "name": "stdout" 518 | } 519 | ] 520 | }, 521 | { 522 | "cell_type": "markdown", 523 | "metadata": { 524 | "id": "3XF2ZCLtBaYu" 525 | }, 526 | "source": [ 527 | "**Clausula _if_ vacia:**" 528 | ] 529 | }, 530 | { 531 | "cell_type": "code", 532 | "metadata": { 533 | "id": "QlO4WJCKBaYu", 534 | "colab": { 535 | "base_uri": "https://localhost:8080/" 536 | }, 537 | "outputId": "5a0aef55-bf1a-474a-9e6a-95499a67191b" 538 | }, 539 | "source": [ 540 | "# Mal:\n", 541 | "b = False\n", 542 | "if (b):\n", 543 | " pass\n", 544 | "else:\n", 545 | " print('no')" 546 | ], 547 | "execution_count": null, 548 | "outputs": [ 549 | { 550 | "output_type": "stream", 551 | "text": [ 552 | "no\n" 553 | ], 554 | "name": "stdout" 555 | } 556 | ] 557 | }, 558 | { 559 | "cell_type": "code", 560 | "metadata": { 561 | "id": "ece1qgH2BaYu", 562 | "colab": { 563 | "base_uri": "https://localhost:8080/" 564 | }, 565 | "outputId": "01afaf1e-ae63-4bb7-9d3c-4fa07fcca8d7" 566 | }, 567 | "source": [ 568 | "# Bien:\n", 569 | "b = False\n", 570 | "if (not b):\n", 571 | " print('no')" 572 | ], 573 | "execution_count": null, 574 | "outputs": [ 575 | { 576 | "output_type": "stream", 577 | "text": [ 578 | "no\n" 579 | ], 580 | "name": "stdout" 581 | } 582 | ] 583 | }, 584 | { 585 | "cell_type": "markdown", 586 | "metadata": { 587 | "id": "3sUKPDi7BaYu" 588 | }, 589 | "source": [ 590 | "**Usando _if_ en vez de _and_:**" 591 | ] 592 | }, 593 | { 594 | "cell_type": "code", 595 | "metadata": { 596 | "id": "185Qj99pBaYu", 597 | "colab": { 598 | "base_uri": "https://localhost:8080/" 599 | }, 600 | "outputId": "c0d2969a-d467-4e58-b1d7-38723f05619c" 601 | }, 602 | "source": [ 603 | "# Bien:\n", 604 | "b1 = True\n", 605 | "b2 = True\n", 606 | "if (b1):\n", 607 | " if (b2):\n", 608 | " print('ambos!')" 609 | ], 610 | "execution_count": null, 611 | "outputs": [ 612 | { 613 | "output_type": "stream", 614 | "text": [ 615 | "ambos!\n" 616 | ], 617 | "name": "stdout" 618 | } 619 | ] 620 | }, 621 | { 622 | "cell_type": "code", 623 | "metadata": { 624 | "id": "ne5hwFM3BaYv", 625 | "colab": { 626 | "base_uri": "https://localhost:8080/" 627 | }, 628 | "outputId": "371f3d3b-9dfb-4e49-96e4-2602be3e5338" 629 | }, 630 | "source": [ 631 | "# Bien:\n", 632 | "b1 = True\n", 633 | "b2 = True\n", 634 | "if (b1 and b2):\n", 635 | " print('ambos!')" 636 | ], 637 | "execution_count": null, 638 | "outputs": [ 639 | { 640 | "output_type": "stream", 641 | "text": [ 642 | "ambos!\n" 643 | ], 644 | "name": "stdout" 645 | } 646 | ] 647 | }, 648 | { 649 | "cell_type": "markdown", 650 | "metadata": { 651 | "id": "HNwb2BwRBaYv" 652 | }, 653 | "source": [ 654 | "**Usando _if_ en vez de _else_:**" 655 | ] 656 | }, 657 | { 658 | "cell_type": "code", 659 | "metadata": { 660 | "id": "1UuTr2WCBaYv", 661 | "colab": { 662 | "base_uri": "https://localhost:8080/" 663 | }, 664 | "outputId": "c922f12d-4773-4f69-ec9e-52cb8157a079" 665 | }, 666 | "source": [ 667 | "# Incorrecto:\n", 668 | "b = True\n", 669 | "if (b):\n", 670 | " print('SI')\n", 671 | "if (not b):\n", 672 | " print('NO')" 673 | ], 674 | "execution_count": null, 675 | "outputs": [ 676 | { 677 | "output_type": "stream", 678 | "text": [ 679 | "SI\n" 680 | ], 681 | "name": "stdout" 682 | } 683 | ] 684 | }, 685 | { 686 | "cell_type": "code", 687 | "metadata": { 688 | "id": "rIbU6Q3HBaYv", 689 | "colab": { 690 | "base_uri": "https://localhost:8080/" 691 | }, 692 | "outputId": "c8d6517c-0d4f-4cb3-a12e-5a3eeb819246" 693 | }, 694 | "source": [ 695 | "# Correcto:\n", 696 | "b = True\n", 697 | "if (b):\n", 698 | " print('SI')\n", 699 | "else:\n", 700 | " print('NO')" 701 | ], 702 | "execution_count": null, 703 | "outputs": [ 704 | { 705 | "output_type": "stream", 706 | "text": [ 707 | "SI\n" 708 | ], 709 | "name": "stdout" 710 | } 711 | ] 712 | }, 713 | { 714 | "cell_type": "markdown", 715 | "metadata": { 716 | "id": "2vSHgUE4BaYv" 717 | }, 718 | "source": [ 719 | "**Otro ejemplo:**" 720 | ] 721 | }, 722 | { 723 | "cell_type": "code", 724 | "metadata": { 725 | "id": "TwHTEWwoBaYw", 726 | "colab": { 727 | "base_uri": "https://localhost:8080/" 728 | }, 729 | "outputId": "99c58f8c-477b-42b2-f804-9b721e984c77" 730 | }, 731 | "source": [ 732 | "# Incorrecto:\n", 733 | "x = 10\n", 734 | "if (x < 5):\n", 735 | " print('pequeño')\n", 736 | "if ((x >= 5) and (x < 10)):\n", 737 | " print('mediano')\n", 738 | "if ((x >= 10) and (x < 15)):\n", 739 | " print('grande')\n", 740 | "if (x >= 15):\n", 741 | " print('muy grande')" 742 | ], 743 | "execution_count": null, 744 | "outputs": [ 745 | { 746 | "output_type": "stream", 747 | "text": [ 748 | "grande\n" 749 | ], 750 | "name": "stdout" 751 | } 752 | ] 753 | }, 754 | { 755 | "cell_type": "code", 756 | "metadata": { 757 | "id": "n9itBNk7BaYw", 758 | "colab": { 759 | "base_uri": "https://localhost:8080/" 760 | }, 761 | "outputId": "53d588e3-3bde-4eed-c3ce-8c93dc1084bd" 762 | }, 763 | "source": [ 764 | "# Correcto:\n", 765 | "x = 10\n", 766 | "if (x < 5):\n", 767 | " print('pequeño')\n", 768 | "elif (x < 10):\n", 769 | " print('mediano')\n", 770 | "elif (x < 15):\n", 771 | " print('grande')\n", 772 | "else:\n", 773 | " print('muy grande')" 774 | ], 775 | "execution_count": null, 776 | "outputs": [ 777 | { 778 | "output_type": "stream", 779 | "text": [ 780 | "grande\n" 781 | ], 782 | "name": "stdout" 783 | } 784 | ] 785 | }, 786 | { 787 | "cell_type": "markdown", 788 | "metadata": { 789 | "id": "7zTQmE4ZBaYw" 790 | }, 791 | "source": [ 792 | "**...y otro más:**" 793 | ] 794 | }, 795 | { 796 | "cell_type": "code", 797 | "metadata": { 798 | "id": "djWqhnkrBaYw", 799 | "colab": { 800 | "base_uri": "https://localhost:8080/" 801 | }, 802 | "outputId": "dadb95a5-72ab-4b3a-d129-ff1a2c86a62d" 803 | }, 804 | "source": [ 805 | "# Incorrecto:\n", 806 | "c = 'a'\n", 807 | "if ((c >= 'A') and (c <= 'Z')):\n", 808 | " print('Mayúscula!')\n", 809 | "if ((c >= 'a') and (c <= 'z')):\n", 810 | " print('Minúscula!')\n", 811 | "if ((c < 'A') or\n", 812 | " ((c > 'Z') and (c < 'a')) or (c > 'z')):\n", 813 | " print ('no es una letra!')" 814 | ], 815 | "execution_count": null, 816 | "outputs": [ 817 | { 818 | "output_type": "stream", 819 | "text": [ 820 | "Minúscula!\n" 821 | ], 822 | "name": "stdout" 823 | } 824 | ] 825 | }, 826 | { 827 | "cell_type": "code", 828 | "metadata": { 829 | "id": "bZdNPqaNBaYw", 830 | "colab": { 831 | "base_uri": "https://localhost:8080/" 832 | }, 833 | "outputId": "9829d8a7-1bb8-4ced-854a-0dd15bacbab5" 834 | }, 835 | "source": [ 836 | "# Correcto:\n", 837 | "c = 'a'\n", 838 | "if ((c >= 'A') and (c <= 'Z')):\n", 839 | " print('Mayúscula!')\n", 840 | "elif ((c >= 'a') and (c <= 'z')):\n", 841 | " print('Minúscula!')\n", 842 | "else:\n", 843 | " print('no es una letra!')" 844 | ], 845 | "execution_count": null, 846 | "outputs": [ 847 | { 848 | "output_type": "stream", 849 | "text": [ 850 | "Minúscula!\n" 851 | ], 852 | "name": "stdout" 853 | } 854 | ] 855 | }, 856 | { 857 | "cell_type": "markdown", 858 | "metadata": { 859 | "id": "ZDxM3Sx6BaYx" 860 | }, 861 | "source": [ 862 | "**Usando _\"lógica aritmética\"_ en vez de _\"lógica booleana\"_:**" 863 | ] 864 | }, 865 | { 866 | "cell_type": "code", 867 | "metadata": { 868 | "id": "zbCmg2-6BaYx" 869 | }, 870 | "source": [ 871 | "# Incorrecto:\n", 872 | "x = 42\n", 873 | "y = ((x > 0) and 99)" 874 | ], 875 | "execution_count": null, 876 | "outputs": [] 877 | }, 878 | { 879 | "cell_type": "code", 880 | "metadata": { 881 | "id": "CxYEM6pLBaYx" 882 | }, 883 | "source": [ 884 | "# Correcto:\n", 885 | "x = 42\n", 886 | "if (x > 0):\n", 887 | " y = 99" 888 | ], 889 | "execution_count": null, 890 | "outputs": [] 891 | } 892 | ] 893 | } -------------------------------------------------------------------------------- /02-Datos_y_Operaciones.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "kernelspec": { 6 | "display_name": "Python 3", 7 | "language": "python", 8 | "name": "python3" 9 | }, 10 | "language_info": { 11 | "codemirror_mode": { 12 | "name": "ipython", 13 | "version": 3 14 | }, 15 | "file_extension": ".py", 16 | "mimetype": "text/x-python", 17 | "name": "python", 18 | "nbconvert_exporter": "python", 19 | "pygments_lexer": "ipython3", 20 | "version": "3.7.5" 21 | }, 22 | "toc": { 23 | "base_numbering": 1, 24 | "nav_menu": {}, 25 | "number_sections": true, 26 | "sideBar": true, 27 | "skip_h1_title": true, 28 | "title_cell": "Contenido", 29 | "title_sidebar": "Contenido", 30 | "toc_cell": false, 31 | "toc_position": { 32 | "height": "calc(100% - 180px)", 33 | "left": "10px", 34 | "top": "150px", 35 | "width": "384px" 36 | }, 37 | "toc_section_display": true, 38 | "toc_window_display": true 39 | }, 40 | "colab": { 41 | "name": "02-Datos_y_Operaciones.ipynb", 42 | "provenance": [], 43 | "include_colab_link": true 44 | } 45 | }, 46 | "cells": [ 47 | { 48 | "cell_type": "markdown", 49 | "metadata": { 50 | "id": "view-in-github", 51 | "colab_type": "text" 52 | }, 53 | "source": [ 54 | "\"Open" 55 | ] 56 | }, 57 | { 58 | "cell_type": "markdown", 59 | "metadata": { 60 | "id": "uyOfNxHrMiB0" 61 | }, 62 | "source": [ 63 | "# Datos y Operaciones\n", 64 | "---\n", 65 | "\n", 66 | "\n", 67 | "\n" 68 | ] 69 | }, 70 | { 71 | "cell_type": "markdown", 72 | "metadata": { 73 | "id": "Sc0-NWsNMiB7" 74 | }, 75 | "source": [ 76 | "## Algunos tipos de datos de Python (Builtin Types)\n", 77 | "\n" 78 | ] 79 | }, 80 | { 81 | "cell_type": "code", 82 | "metadata": { 83 | "id": "kHhaZ6GVMiB7", 84 | "colab": { 85 | "base_uri": "https://localhost:8080/" 86 | }, 87 | "outputId": "a57fe3e1-e407-4ce5-8229-efd04a89838b" 88 | }, 89 | "source": [ 90 | "import math\n", 91 | "\n", 92 | "\n", 93 | "def una_funcion():\n", 94 | " \"\"\"\n", 95 | " Esto es un comentario del proposito de nuestra primer\n", 96 | " definición de una función\n", 97 | " \"\"\"\n", 98 | " print(\"Hola Mundo\")\n", 99 | " return 42\n", 100 | "\n", 101 | "print(\"Algunos tipos basicos de Python:\")\n", 102 | "print(type(2)) # int - entero\n", 103 | "print(type(2.2)) # float - punto flotante o real\n", 104 | "print(type(2 < 2.2)) # bool (boolean) - booleano\n", 105 | "print(type(type(42))) # type - tipo (?)\n", 106 | "\n", 107 | "print(\"#####################################################\")\n", 108 | "\n", 109 | "print(\"Algunos otros que usaremos más adelante...\")\n", 110 | "print(type(\"2.2\")) # str (string or text) - cadena de caracteres\n", 111 | "print(type([1,2,3])) # list - lista\n", 112 | "print(type((1,2,3))) # tuple - tupla\n", 113 | "print(type({1,2})) # set - conjunto\n", 114 | "print(type({1:42})) # dict (dictionary or map) - diccionario\n", 115 | "print(type(2+3j)) # complex (complex number) - números complejos" 116 | ], 117 | "execution_count": 1, 118 | "outputs": [ 119 | { 120 | "output_type": "stream", 121 | "text": [ 122 | "Algunos tipos basicos de Python:\n", 123 | "\n", 124 | "\n", 125 | "\n", 126 | "\n", 127 | "#####################################################\n", 128 | "Algunos otros que usaremos más adelante...\n", 129 | "\n", 130 | "\n", 131 | "\n", 132 | "\n", 133 | "\n", 134 | "\n" 135 | ], 136 | "name": "stdout" 137 | } 138 | ] 139 | }, 140 | { 141 | "cell_type": "markdown", 142 | "metadata": { 143 | "id": "FH0fZ3MTMiB8" 144 | }, 145 | "source": [ 146 | "\n", 147 | "## Algunas Constantes de Python (Builtin Constants)\n" 148 | ] 149 | }, 150 | { 151 | "cell_type": "code", 152 | "metadata": { 153 | "id": "z0d1SFMwMiB9", 154 | "colab": { 155 | "base_uri": "https://localhost:8080/" 156 | }, 157 | "outputId": "dd62f75c-5762-47b4-bea0-32125a3b2080" 158 | }, 159 | "source": [ 160 | "print(\"Algunas constantes incorporadas:\")\n", 161 | "print(True)\n", 162 | "print(False)\n", 163 | "print(None)\n", 164 | "\n", 165 | "print(\"...y algunas otras constantes en el módulo math:\")\n", 166 | "import math\n", 167 | "print(math.pi)\n", 168 | "print(math.e)" 169 | ], 170 | "execution_count": 2, 171 | "outputs": [ 172 | { 173 | "output_type": "stream", 174 | "text": [ 175 | "Algunas constantes incorporadas:\n", 176 | "True\n", 177 | "False\n", 178 | "None\n", 179 | "...y algunas otras constantes en el módulo math:\n", 180 | "3.141592653589793\n", 181 | "2.718281828459045\n" 182 | ], 183 | "name": "stdout" 184 | } 185 | ] 186 | }, 187 | { 188 | "cell_type": "markdown", 189 | "metadata": { 190 | "id": "zfDGsLNrMiB9" 191 | }, 192 | "source": [ 193 | "\n", 194 | "## Algunos Operadores de Python (Builtin Operators)\n", 195 | "\n", 196 | "\n", 197 | "| **Categoria** | **Operador** |\n", 198 | "|-------------------|:-------------------------------------------------:|\n", 199 | "| **Aritmérico** | \t+, -, *, /, //, \\**, %, - (unario), + (unario) |\n", 200 | "| **Relacional** | \t<, <=, >=, >, ==, != |\n", 201 | "| **De Asignación** | \t+=, -=, *=, /=, //=, \\**=, %=, <<=, >>= |\n", 202 | "| **Lógico** | and, or, not |\n", 203 | "\n", 204 | "**_Nota: por ahora no cubriremos los operadores bit a bit (<<, >>, &, |, ^, ~, &=, |=, ^=)._**" 205 | ] 206 | }, 207 | { 208 | "cell_type": "markdown", 209 | "metadata": { 210 | "id": "Vg0X_w0NMiB9" 211 | }, 212 | "source": [ 213 | "\n", 214 | "## División Entera (Integer Division)\n", 215 | "\n", 216 | "\n" 217 | ] 218 | }, 219 | { 220 | "cell_type": "code", 221 | "metadata": { 222 | "id": "rXJd24HFMiB-", 223 | "colab": { 224 | "base_uri": "https://localhost:8080/" 225 | }, 226 | "outputId": "be36877f-7610-476f-f81b-bc0d00a79441" 227 | }, 228 | "source": [ 229 | "print(\"El operador / hace la división real, punto flotante o 'común' (float division):\")\n", 230 | "print(\" 5/3 =\", ( 5/3))\n", 231 | "print()\n", 232 | "print(\"El operador // hace la división entera (integer division):\")\n", 233 | "print(\" 5//3 =\", ( 5//3))\n", 234 | "print(\" 2//3 =\", ( 2//3))\n", 235 | "print(\"-1//3 =\", (-1//3))\n", 236 | "print(\"-4//3 =\", (-4//3))" 237 | ], 238 | "execution_count": 3, 239 | "outputs": [ 240 | { 241 | "output_type": "stream", 242 | "text": [ 243 | "El operador / hace la división real, punto flotante o 'común' (float division):\n", 244 | " 5/3 = 1.6666666666666667\n", 245 | "\n", 246 | "El operador // hace la división entera (integer division):\n", 247 | " 5//3 = 1\n", 248 | " 2//3 = 0\n", 249 | "-1//3 = -1\n", 250 | "-4//3 = -2\n" 251 | ], 252 | "name": "stdout" 253 | } 254 | ] 255 | }, 256 | { 257 | "cell_type": "markdown", 258 | "metadata": { 259 | "id": "x6l7KPXlMiB-" 260 | }, 261 | "source": [ 262 | "\n", 263 | "## Módulo o Resto - Operador (%)\n", 264 | "\n" 265 | ] 266 | }, 267 | { 268 | "cell_type": "code", 269 | "metadata": { 270 | "id": "foLPq9ltMiB-", 271 | "colab": { 272 | "base_uri": "https://localhost:8080/", 273 | "height": 282 274 | }, 275 | "outputId": "cd010741-a719-48bc-a4eb-2ea52061f82f" 276 | }, 277 | "source": [ 278 | "print(\" 6 % 3 =\", ( 6%3))\n", 279 | "print(\" 5 % 3 =\", ( 5%3))\n", 280 | "print(\" 2 % 3 =\", ( 2%3))\n", 281 | "print(\" 0 % 3 =\", ( 0%3))\n", 282 | "print(\"-4 % 3 =\", (-4%3))\n", 283 | "print(\" 3 % 0 =\", ( 3%0))" 284 | ], 285 | "execution_count": 4, 286 | "outputs": [ 287 | { 288 | "output_type": "stream", 289 | "text": [ 290 | " 6 % 3 = 0\n", 291 | " 5 % 3 = 2\n", 292 | " 2 % 3 = 2\n", 293 | " 0 % 3 = 0\n", 294 | "-4 % 3 = 2\n" 295 | ], 296 | "name": "stdout" 297 | }, 298 | { 299 | "output_type": "error", 300 | "ename": "ZeroDivisionError", 301 | "evalue": "ignored", 302 | "traceback": [ 303 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 304 | "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", 305 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\" 0 % 3 =\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m(\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m%\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"-4 % 3 =\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m4\u001b[0m\u001b[0;34m%\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 6\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\" 3 % 0 =\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m(\u001b[0m \u001b[0;36m3\u001b[0m\u001b[0;34m%\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 306 | "\u001b[0;31mZeroDivisionError\u001b[0m: integer division or modulo by zero" 307 | ] 308 | } 309 | ] 310 | }, 311 | { 312 | "cell_type": "markdown", 313 | "metadata": { 314 | "id": "Dlfvuxe-MiB-" 315 | }, 316 | "source": [ 317 | "\n", 318 | "## Más sobre el Módulo o el resto - Operador (%)\n", 319 | "\n", 320 | "**Verifique que (x % y) es equivalente a (x - (x//y) * y):**\n" 321 | ] 322 | }, 323 | { 324 | "cell_type": "code", 325 | "metadata": { 326 | "id": "2ccH1Q4gMiB_", 327 | "colab": { 328 | "base_uri": "https://localhost:8080/" 329 | }, 330 | "outputId": "ada1b753-5d99-4834-9d84-964d900d8f37" 331 | }, 332 | "source": [ 333 | "def mod(x, y):\n", 334 | " return x - (x//y)*y\n", 335 | "\n", 336 | "print(41 % 14, mod(41,14))\n", 337 | "print(14 % 41, mod(14,41))\n", 338 | "print(-32 % 9, mod(-32,9))\n", 339 | "print(32 % -9, mod(32,-9))" 340 | ], 341 | "execution_count": 5, 342 | "outputs": [ 343 | { 344 | "output_type": "stream", 345 | "text": [ 346 | "13 13\n", 347 | "14 14\n", 348 | "4 4\n", 349 | "-4 -4\n" 350 | ], 351 | "name": "stdout" 352 | } 353 | ] 354 | }, 355 | { 356 | "cell_type": "markdown", 357 | "metadata": { 358 | "id": "3qUXhHCXMiB_" 359 | }, 360 | "source": [ 361 | "\n", 362 | "## Los tipos (_types_) afectan la Semantica\n", 363 | "\n" 364 | ] 365 | }, 366 | { 367 | "cell_type": "code", 368 | "metadata": { 369 | "id": "o3ZzKjwAMiB_", 370 | "colab": { 371 | "base_uri": "https://localhost:8080/", 372 | "height": 265 373 | }, 374 | "outputId": "ebbee4d5-8cde-4b87-daab-bf7513169511" 375 | }, 376 | "source": [ 377 | "print(3 * 2)\n", 378 | "print(3 * \"abc\")\n", 379 | "print(3 + 2)\n", 380 | "print(\"abc\" + \"def\")\n", 381 | "print(3 + \"def\")" 382 | ], 383 | "execution_count": 6, 384 | "outputs": [ 385 | { 386 | "output_type": "stream", 387 | "text": [ 388 | "6\n", 389 | "abcabcabc\n", 390 | "5\n", 391 | "abcdef\n" 392 | ], 393 | "name": "stdout" 394 | }, 395 | { 396 | "output_type": "error", 397 | "ename": "TypeError", 398 | "evalue": "ignored", 399 | "traceback": [ 400 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 401 | "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", 402 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m3\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"abc\"\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;34m\"def\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m3\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;34m\"def\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 403 | "\u001b[0;31mTypeError\u001b[0m: unsupported operand type(s) for +: 'int' and 'str'" 404 | ] 405 | } 406 | ] 407 | }, 408 | { 409 | "cell_type": "markdown", 410 | "metadata": { 411 | "id": "02iLnL5xMiCA" 412 | }, 413 | "source": [ 414 | "\n", 415 | "## Orden de Operadores (Precedencia y Asociatividad)\n", 416 | "\n" 417 | ] 418 | }, 419 | { 420 | "cell_type": "code", 421 | "metadata": { 422 | "id": "RyTWkxfTMiCA", 423 | "colab": { 424 | "base_uri": "https://localhost:8080/" 425 | }, 426 | "outputId": "a7a1bc32-ee0a-45b3-ab85-80fb7b27d8a5" 427 | }, 428 | "source": [ 429 | "print(\"Precedencia:\")\n", 430 | "print(2+3*4) # imprime 14, no 20\n", 431 | "print(5+4%3) # imprime 6, no 0 (% tiene la misma precedencia que *, /, y //)\n", 432 | "print(2**3*4) # imprime 32, no 4096 (** tiene mayor precedencia que *, /, //, y %)\n", 433 | "\n", 434 | "print()\n", 435 | "\n", 436 | "print(\"Asociatividad:\")\n", 437 | "print(5-4-3) # imprime -2, no 4 (- asocia de izquierda a derecha)\n", 438 | "print(4**3**2) # imprime 262144, no 4096 (** asocia de derecha a izqueirda)" 439 | ], 440 | "execution_count": 7, 441 | "outputs": [ 442 | { 443 | "output_type": "stream", 444 | "text": [ 445 | "Precedencia:\n", 446 | "14\n", 447 | "6\n", 448 | "32\n", 449 | "\n", 450 | "Asociatividad:\n", 451 | "-2\n", 452 | "262144\n" 453 | ], 454 | "name": "stdout" 455 | } 456 | ] 457 | }, 458 | { 459 | "cell_type": "markdown", 460 | "metadata": { 461 | "id": "peGGE4uzMiCA" 462 | }, 463 | "source": [ 464 | "\n", 465 | "## Números Reales - Valores Aproximados\n", 466 | "\n" 467 | ] 468 | }, 469 | { 470 | "cell_type": "code", 471 | "metadata": { 472 | "id": "V2ln18aYMiCA", 473 | "colab": { 474 | "base_uri": "https://localhost:8080/" 475 | }, 476 | "outputId": "19dae383-c398-4b71-9aac-0d37ff783188" 477 | }, 478 | "source": [ 479 | "print(0.1 + 0.1 == 0.2) # Verdadero, pero...\n", 480 | "print(0.1 + 0.1 + 0.1 == 0.3) # Falso!\n", 481 | "print(0.1 + 0.1 + 0.1) # Imprime 0.30000000000000004 (ups!)\n", 482 | "print((0.1 + 0.1 + 0.1) - 0.3) # Imprime 5.55111512313e-17 (casi..., pero no es cero!)" 483 | ], 484 | "execution_count": 8, 485 | "outputs": [ 486 | { 487 | "output_type": "stream", 488 | "text": [ 489 | "True\n", 490 | "False\n", 491 | "0.30000000000000004\n", 492 | "5.551115123125783e-17\n" 493 | ], 494 | "name": "stdout" 495 | } 496 | ] 497 | }, 498 | { 499 | "cell_type": "markdown", 500 | "metadata": { 501 | "id": "pq-DCNe5MiCA" 502 | }, 503 | "source": [ 504 | "**Prueba de igualdad o casi igual:**" 505 | ] 506 | }, 507 | { 508 | "cell_type": "code", 509 | "metadata": { 510 | "id": "NAXXrsrCMiCB", 511 | "colab": { 512 | "base_uri": "https://localhost:8080/" 513 | }, 514 | "outputId": "d0a68444-1347-41a5-ec89-b3fff2599b25" 515 | }, 516 | "source": [ 517 | "print(\"El problema...\")\n", 518 | "d1 = 0.1 + 0.1 + 0.1\n", 519 | "d2 = 0.3\n", 520 | "print(d1 == d2) # Falso (nunca usar == con números reales!)\n", 521 | "\n", 522 | "print()\n", 523 | "print(\"La solución...\")\n", 524 | "epsilon = 10**-10\n", 525 | "print(abs(d2 - d1) < epsilon) # Verdadero!\n", 526 | "\n", 527 | "print()\n", 528 | "print(\"Otra vez, pero usando una muy útil funcion de ayuda (helper), casiIgual:\")\n", 529 | "\n", 530 | "def casiIgual(d1, d2):\n", 531 | " epsilon = 10**-10\n", 532 | " return (abs(d2 - d1) < epsilon)\n", 533 | "\n", 534 | "d1 = 0.1 + 0.1 + 0.1\n", 535 | "d2 = 0.3\n", 536 | "print(d1 == d2) # sigue siendo Falso, por supuesto!\n", 537 | "print(casiIgual(d1, d2)) # Verdadero, y ahora en una función reutilizable!" 538 | ], 539 | "execution_count": 9, 540 | "outputs": [ 541 | { 542 | "output_type": "stream", 543 | "text": [ 544 | "El problema...\n", 545 | "False\n", 546 | "\n", 547 | "La solución...\n", 548 | "True\n", 549 | "\n", 550 | "Otra vez, pero usando una muy útil funcion de ayuda (helper), casiIgual:\n", 551 | "False\n", 552 | "True\n" 553 | ], 554 | "name": "stdout" 555 | } 556 | ] 557 | }, 558 | { 559 | "cell_type": "markdown", 560 | "metadata": { 561 | "id": "surTbB8SMiCB" 562 | }, 563 | "source": [ 564 | "\n", 565 | "## Evaluación Corto Circuito" 566 | ] 567 | }, 568 | { 569 | "cell_type": "code", 570 | "metadata": { 571 | "id": "OSjyYZJ0MiCB", 572 | "colab": { 573 | "base_uri": "https://localhost:8080/", 574 | "height": 401 575 | }, 576 | "outputId": "b226b597-d439-4c0d-8197-53df13206dd8" 577 | }, 578 | "source": [ 579 | "def si():\n", 580 | " return True\n", 581 | "\n", 582 | "def no():\n", 583 | " return False\n", 584 | "\n", 585 | "def explota():\n", 586 | " return 1/0 # explota!\n", 587 | "\n", 588 | "print('Ejemplo 1')\n", 589 | "print(no() and explota()) # Funciona!\n", 590 | "\n", 591 | "print('Ejemplo 2')\n", 592 | "print(explota() and no()) # Explota!\n", 593 | "\n", 594 | "print('Ejemplo 3')\n", 595 | "print (no() and explota()) # Nunca se ejecuta, pero puede explotar si no ocurre el corto circuito." 596 | ], 597 | "execution_count": 10, 598 | "outputs": [ 599 | { 600 | "output_type": "stream", 601 | "text": [ 602 | "Ejemplo 1\n", 603 | "False\n", 604 | "Ejemplo 2\n" 605 | ], 606 | "name": "stdout" 607 | }, 608 | { 609 | "output_type": "error", 610 | "ename": "ZeroDivisionError", 611 | "evalue": "ignored", 612 | "traceback": [ 613 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 614 | "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", 615 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 12\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 13\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'Ejemplo 2'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 14\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mexplota\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mand\u001b[0m \u001b[0mno\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# Explota!\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 15\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 16\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'Ejemplo 3'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 616 | "\u001b[0;32m\u001b[0m in \u001b[0;36mexplota\u001b[0;34m()\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mexplota\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 8\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0;36m0\u001b[0m \u001b[0;31m# explota!\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 9\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 10\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'Ejemplo 1'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 617 | "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" 618 | ] 619 | } 620 | ] 621 | }, 622 | { 623 | "cell_type": "markdown", 624 | "metadata": { 625 | "id": "iOsBHVtVMiCB" 626 | }, 627 | "source": [ 628 | "**Una vez más, usando el operador \"or\"**" 629 | ] 630 | }, 631 | { 632 | "cell_type": "code", 633 | "metadata": { 634 | "id": "dH7T0fZYMiCC", 635 | "colab": { 636 | "base_uri": "https://localhost:8080/", 637 | "height": 248 638 | }, 639 | "outputId": "e3dfa6a2-35d7-4a8e-a76b-ae2afec92d6b" 640 | }, 641 | "source": [ 642 | "def si():\n", 643 | " return True\n", 644 | "\n", 645 | "def no():\n", 646 | " return False\n", 647 | "\n", 648 | "def explota():\n", 649 | " return 1/0 # explota!\n", 650 | "\n", 651 | "print('Ejemplo 1')\n", 652 | "print(yes() or crash()) # Funciona!\n", 653 | "\n", 654 | "print('Ejemplo 2')\n", 655 | "print(crash() or yes()) # Explota!\n", 656 | "\n", 657 | "print('Ejemplo 3')\n", 658 | "print(no() or crash()) # Nunca se ejecuta, pero puede explotar si no ocurre el corto circuito." 659 | ], 660 | "execution_count": 11, 661 | "outputs": [ 662 | { 663 | "output_type": "stream", 664 | "text": [ 665 | "Ejemplo 1\n" 666 | ], 667 | "name": "stdout" 668 | }, 669 | { 670 | "output_type": "error", 671 | "ename": "NameError", 672 | "evalue": "ignored", 673 | "traceback": [ 674 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 675 | "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", 676 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 9\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 10\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'Ejemplo 1'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 11\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0myes\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0mcrash\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# Funciona!\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 12\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 13\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'Ejemplo 2'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 677 | "\u001b[0;31mNameError\u001b[0m: name 'yes' is not defined" 678 | ] 679 | } 680 | ] 681 | }, 682 | { 683 | "cell_type": "markdown", 684 | "metadata": { 685 | "id": "aMCCs6R5MiCC" 686 | }, 687 | "source": [ 688 | "**Otro ejemplo más:**" 689 | ] 690 | }, 691 | { 692 | "cell_type": "code", 693 | "metadata": { 694 | "id": "XyQh5FvjMiCC", 695 | "colab": { 696 | "base_uri": "https://localhost:8080/" 697 | }, 698 | "outputId": "8d79be95-7b1c-456e-dc02-8f91d20a587e" 699 | }, 700 | "source": [ 701 | "def esPositivo(n):\n", 702 | " resultado = (n > 0)\n", 703 | " print(\"esPositivo(\",n,\") =\", resultado)\n", 704 | " return resultado\n", 705 | "\n", 706 | "def esPar(n):\n", 707 | " resultado = (n % 2 == 0)\n", 708 | " print(\"esPar(\",n,\") =\", resultado)\n", 709 | " return resultado\n", 710 | "\n", 711 | "print(\"Test 1: esPar(-4) y esPositivo(-4))\")\n", 712 | "print(esPar(-4) and esPositivo(-4)) # Llama a ambas funciones\n", 713 | "print(\"----------\")\n", 714 | "print(\"Test 2: esPar(-3) y esPositivo(-3)\")\n", 715 | "print(esPar(-3) and esPositivo(-3)) # Llama solo a una función!" 716 | ], 717 | "execution_count": 12, 718 | "outputs": [ 719 | { 720 | "output_type": "stream", 721 | "text": [ 722 | "Test 1: esPar(-4) y esPositivo(-4))\n", 723 | "esPar( -4 ) = True\n", 724 | "esPositivo( -4 ) = False\n", 725 | "False\n", 726 | "----------\n", 727 | "Test 2: esPar(-3) y esPositivo(-3)\n", 728 | "esPar( -3 ) = False\n", 729 | "False\n" 730 | ], 731 | "name": "stdout" 732 | } 733 | ] 734 | } 735 | ] 736 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /03-Variables_y_Funciones.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "language_info": { 6 | "name": "python", 7 | "codemirror_mode": { 8 | "name": "ipython", 9 | "version": 3 10 | }, 11 | "version": "3.7.5-final" 12 | }, 13 | "orig_nbformat": 2, 14 | "file_extension": ".py", 15 | "mimetype": "text/x-python", 16 | "name": "python", 17 | "npconvert_exporter": "python", 18 | "pygments_lexer": "ipython3", 19 | "version": 3, 20 | "kernelspec": { 21 | "name": "python3", 22 | "display_name": "Python 3" 23 | }, 24 | "colab": { 25 | "name": "03-Variables_y_Funciones.ipynb", 26 | "provenance": [], 27 | "include_colab_link": true 28 | } 29 | }, 30 | "cells": [ 31 | { 32 | "cell_type": "markdown", 33 | "metadata": { 34 | "id": "view-in-github", 35 | "colab_type": "text" 36 | }, 37 | "source": [ 38 | "\"Open" 39 | ] 40 | }, 41 | { 42 | "cell_type": "markdown", 43 | "metadata": { 44 | "id": "HBDZKVT6Dw7h" 45 | }, 46 | "source": [ 47 | " # Variables y Funciones\n", 48 | "---\n", 49 | "\n" 50 | ] 51 | }, 52 | { 53 | "cell_type": "markdown", 54 | "metadata": { 55 | "id": "maEQRA5RDw7o" 56 | }, 57 | "source": [ 58 | "## Variables\n", 59 | "\n", 60 | "**Una variable es un valor nombrado que referencia o guarda información.**" 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "metadata": { 66 | "colab": { 67 | "base_uri": "https://localhost:8080/" 68 | }, 69 | "id": "mVE2iO86Dw7p", 70 | "outputId": "c3ac2378-b2dc-4f95-c81d-c4dbb54b45c7" 71 | }, 72 | "source": [ 73 | "# Colocamos un valor en una variable usando el = \n", 74 | "x = 5\n", 75 | "\n", 76 | "print(x) # imprime 5\n", 77 | "print(x*2) # multiplica x por 2, imprime 10" 78 | ], 79 | "execution_count": 1, 80 | "outputs": [ 81 | { 82 | "output_type": "stream", 83 | "text": [ 84 | "5\n", 85 | "10\n" 86 | ], 87 | "name": "stdout" 88 | } 89 | ] 90 | }, 91 | { 92 | "cell_type": "markdown", 93 | "metadata": { 94 | "id": "NZMSsjkjDw7p" 95 | }, 96 | "source": [ 97 | "**A diferencia de lo visto en Matemática, las variables pueden tener valores de diferentes tipos.**" 98 | ] 99 | }, 100 | { 101 | "cell_type": "code", 102 | "metadata": { 103 | "colab": { 104 | "base_uri": "https://localhost:8080/" 105 | }, 106 | "id": "zW6F8nu4Dw7q", 107 | "outputId": "3b8b014d-9cd3-4e2c-f9fe-e0f897df5bc3" 108 | }, 109 | "source": [ 110 | "y = 10\n", 111 | "print(y - 2)\n", 112 | "\n", 113 | "y = True\n", 114 | "print(y)" 115 | ], 116 | "execution_count": 2, 117 | "outputs": [ 118 | { 119 | "output_type": "stream", 120 | "text": [ 121 | "8\n", 122 | "True\n" 123 | ], 124 | "name": "stdout" 125 | } 126 | ] 127 | }, 128 | { 129 | "cell_type": "markdown", 130 | "metadata": { 131 | "id": "Pp1wEENlDw7q" 132 | }, 133 | "source": [ 134 | "**Las variables pueden tener cualquier nombre pero deben comenzar con una letra y no contener caracteres especiales.**" 135 | ] 136 | }, 137 | { 138 | "cell_type": "code", 139 | "metadata": { 140 | "colab": { 141 | "base_uri": "https://localhost:8080/", 142 | "height": 129 143 | }, 144 | "id": "tvA-YdeADw7q", 145 | "outputId": "0a2e368e-9b7b-4731-d889-e82479d2f958" 146 | }, 147 | "source": [ 148 | "numeros_de_conejos = 40\n", 149 | "curso_habilitado = True\n", 150 | "99problemas = 0 # Explota porque comienza con un número" 151 | ], 152 | "execution_count": 3, 153 | "outputs": [ 154 | { 155 | "output_type": "error", 156 | "ename": "SyntaxError", 157 | "evalue": "ignored", 158 | "traceback": [ 159 | "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m3\u001b[0m\n\u001b[0;31m 99problemas = 0 # Explota porque comienza con un número\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" 160 | ] 161 | } 162 | ] 163 | }, 164 | { 165 | "cell_type": "markdown", 166 | "metadata": { 167 | "id": "fiUaOJMJDw7r" 168 | }, 169 | "source": [ 170 | "**Las variables pueden ser actualizadas utilizando operaciones de asignación.**\n" 171 | ] 172 | }, 173 | { 174 | "cell_type": "code", 175 | "metadata": { 176 | "colab": { 177 | "base_uri": "https://localhost:8080/" 178 | }, 179 | "id": "PuB9AOzQDw7r", 180 | "outputId": "c8c6be29-ab80-4de5-bced-c84cdfdd68cd" 181 | }, 182 | "source": [ 183 | "x = 5\n", 184 | "x += 2 # Igual que x = x + 2\n", 185 | "print(x) # Debería ser 7\n", 186 | "\n", 187 | "# Podemos utilizar cualquier operación aritmética.\n", 188 | "\n", 189 | "y = 350\n", 190 | "y //= 10\n", 191 | "print(y) # Debería ser 35" 192 | ], 193 | "execution_count": 4, 194 | "outputs": [ 195 | { 196 | "output_type": "stream", 197 | "text": [ 198 | "7\n", 199 | "35\n" 200 | ], 201 | "name": "stdout" 202 | } 203 | ] 204 | }, 205 | { 206 | "cell_type": "markdown", 207 | "metadata": { 208 | "id": "w3aeMwN0Dw7r" 209 | }, 210 | "source": [ 211 | "## Declaraciones y Expresiones \n", 212 | "**Una expresión es un valor o una operación que retorna un valor.**" 213 | ] 214 | }, 215 | { 216 | "cell_type": "code", 217 | "metadata": { 218 | "colab": { 219 | "base_uri": "https://localhost:8080/" 220 | }, 221 | "id": "NS0iNPLvDw7s", 222 | "outputId": "a09f4acf-f547-4ad4-eb51-c4ee06b45a5c" 223 | }, 224 | "source": [ 225 | "# Ejemplos de expresiones.\n", 226 | "# Note que cuando es ejecutado ninguno de ellos es mostrado.\n", 227 | "\n", 228 | "4\n", 229 | "\"Hola Mundo\"\n", 230 | "7 + 2\n", 231 | "True or False\n", 232 | "(2 < 3) and (9 > 0)" 233 | ], 234 | "execution_count": 5, 235 | "outputs": [ 236 | { 237 | "output_type": "execute_result", 238 | "data": { 239 | "text/plain": [ 240 | "True" 241 | ] 242 | }, 243 | "metadata": { 244 | "tags": [] 245 | }, 246 | "execution_count": 5 247 | } 248 | ] 249 | }, 250 | { 251 | "cell_type": "markdown", 252 | "metadata": { 253 | "id": "r0zZtmRdDw7s" 254 | }, 255 | "source": [ 256 | "**Una declaración es una línea de código que ejecuta una acción. Al contrario que las expresiones, las declaraciones no pueden ser usadas en operaciones.**" 257 | ] 258 | }, 259 | { 260 | "cell_type": "code", 261 | "metadata": { 262 | "colab": { 263 | "base_uri": "https://localhost:8080/" 264 | }, 265 | "id": "CgWlR_EuDw7s", 266 | "outputId": "7ad7217d-91af-40a0-e4ae-805e697f4a44" 267 | }, 268 | "source": [ 269 | "# Ejemplo de Declaraciones.\n", 270 | "\n", 271 | "print(4)\n", 272 | "x = True" 273 | ], 274 | "execution_count": 6, 275 | "outputs": [ 276 | { 277 | "output_type": "stream", 278 | "text": [ 279 | "4\n" 280 | ], 281 | "name": "stdout" 282 | } 283 | ] 284 | }, 285 | { 286 | "cell_type": "markdown", 287 | "metadata": { 288 | "id": "IxCxH0QiDw7s" 289 | }, 290 | "source": [ 291 | "## Funciones\n", 292 | "\n", 293 | "**Una función es un procedimiento (una secuencia de _declaraciones_) guardada bajo un nombre que puede ser usada una y otra vez llamandola por el mismo.**\n" 294 | ] 295 | }, 296 | { 297 | "cell_type": "code", 298 | "metadata": { 299 | "colab": { 300 | "base_uri": "https://localhost:8080/" 301 | }, 302 | "id": "QZj_yPVzDw7t", 303 | "outputId": "b2569f0f-3cd4-41cc-d943-297df9fdf423" 304 | }, 305 | "source": [ 306 | "# Una función está compuesta por dos partes: el encabezado y el cuerpo\n", 307 | "\n", 308 | "# El encabezado (también se lo llama firma) define el nombre y los parametros.\n", 309 | "# Un encabezado de una función es escrito como sigue:\n", 310 | "#\n", 311 | "# def nombre_de_funcion(parametros):\n", 312 | "#\n", 313 | "# Los parametros son variables que serán provistas cuando la función es llamada.\n", 314 | "# El encabezado termina con dos puntos (:) para indicar que continua el cuerpo \n", 315 | "# de la función.\n", 316 | "#\n", 317 | "# El Cuerpo contiene las acciones (declaraciones [statements]) que ejecutará la función.\n", 318 | "# El cuerpo es escrito debajo del encabezado con indentación (En Español: sangrado)\n", 319 | "# Cuando las lineas dejan de tener la indentación la función termina.\n", 320 | "#\n", 321 | "# Las funciones usualmente contiene un declaración return al final.\n", 322 | "# Esto proveerá el resultado cuando la función sea llamada.\n", 323 | "\n", 324 | "# Ejemplo:\n", 325 | "\n", 326 | "def duplica(x):\n", 327 | " print(\"Soy la función duplicadora!\")\n", 328 | " return 2 * x\n", 329 | "\n", 330 | "# Para llamar a una función usamos el nombre de la función\n", 331 | "# seguido por los parentesis con los valores que queremos usar (argumentos).\n", 332 | "\n", 333 | "print(duplica(2)) # Imprimirá 4\n", 334 | "print(duplica(5)) # Imprimirá 10\n", 335 | "print(duplica(1) + 3) # Imprimirá 5" 336 | ], 337 | "execution_count": 7, 338 | "outputs": [ 339 | { 340 | "output_type": "stream", 341 | "text": [ 342 | "Soy la función duplicadora!\n", 343 | "4\n", 344 | "Soy la función duplicadora!\n", 345 | "10\n", 346 | "Soy la función duplicadora!\n", 347 | "5\n" 348 | ], 349 | "name": "stdout" 350 | } 351 | ] 352 | }, 353 | { 354 | "cell_type": "markdown", 355 | "metadata": { 356 | "id": "3KYzlOlgDw7u" 357 | }, 358 | "source": [ 359 | "**Las funciones pueden tener los parámetros que necesitemos o ninguno.**\n" 360 | ] 361 | }, 362 | { 363 | "cell_type": "code", 364 | "metadata": { 365 | "colab": { 366 | "base_uri": "https://localhost:8080/", 367 | "height": 248 368 | }, 369 | "id": "7qtochSvDw7u", 370 | "outputId": "ffbf00b0-f28d-405d-f774-01101205e527" 371 | }, 372 | "source": [ 373 | "def f(x, y, z):\n", 374 | " return x + y + z\n", 375 | "\n", 376 | "print(f(1, 3, 2)) # retorna 6\n", 377 | "\n", 378 | "def g():\n", 379 | " return 42\n", 380 | "\n", 381 | "print(g()) # retorna 42\n", 382 | "\n", 383 | "# Nota - el número de argumentos provistos debe coincidir con el número de parámetros!\n", 384 | "print(g(2)) # No funciona.\n", 385 | "print(f(1, 2)) # Tampoco funcionará." 386 | ], 387 | "execution_count": 8, 388 | "outputs": [ 389 | { 390 | "output_type": "stream", 391 | "text": [ 392 | "6\n", 393 | "42\n" 394 | ], 395 | "name": "stdout" 396 | }, 397 | { 398 | "output_type": "error", 399 | "ename": "TypeError", 400 | "evalue": "ignored", 401 | "traceback": [ 402 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 403 | "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", 404 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 10\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0;31m# Nota - el número de argumentos provistos debe coincidir con el número de parámetros!\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 12\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mg\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# No funciona.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 13\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mf\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# Tampoco funcionará.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 405 | "\u001b[0;31mTypeError\u001b[0m: g() takes 0 positional arguments but 1 was given" 406 | ] 407 | } 408 | ] 409 | }, 410 | { 411 | "cell_type": "markdown", 412 | "metadata": { 413 | "id": "tdMnskb7Dw7u" 414 | }, 415 | "source": [ 416 | "## Funciones Incorporadas (builtins)\n" 417 | ] 418 | }, 419 | { 420 | "cell_type": "code", 421 | "metadata": { 422 | "colab": { 423 | "base_uri": "https://localhost:8080/" 424 | }, 425 | "id": "Gnnwjq6_Dw7u", 426 | "outputId": "02ab5320-35bb-471b-9b90-01ecef244465" 427 | }, 428 | "source": [ 429 | "# Algunas funciones ya son provistas por el interprete Python\n", 430 | "\n", 431 | "print(\"Funciones para conversión de Tipo:\")\n", 432 | "print(bool(0)) # convierte a boolean (True or False)\n", 433 | "print(float(42)) # convierte a real\n", 434 | "print(int(2.8)) # convierte a entero (int)\n", 435 | "\n", 436 | "print(\"Y algunas funciones matemáticas basicas:\")\n", 437 | "print(abs(-5)) # valor absoluto\n", 438 | "print(max(2,3)) # retorna el máximo valor\n", 439 | "print(min(2,3)) # retorna el mínimo valor\n", 440 | "print(pow(2,3)) # eleva a potencia dada (pow(x,y) == x**y)\n", 441 | "print(round(2.354, 1)) # redondea con el número de digitos" 442 | ], 443 | "execution_count": 9, 444 | "outputs": [ 445 | { 446 | "output_type": "stream", 447 | "text": [ 448 | "Funciones para conversión de Tipo:\n", 449 | "False\n", 450 | "42.0\n", 451 | "2\n", 452 | "Y algunas funciones matemáticas basicas:\n", 453 | "5\n", 454 | "3\n", 455 | "2\n", 456 | "8\n", 457 | "2.4\n" 458 | ], 459 | "name": "stdout" 460 | } 461 | ] 462 | }, 463 | { 464 | "cell_type": "markdown", 465 | "metadata": { 466 | "id": "ZOSEYo6TDw7v" 467 | }, 468 | "source": [ 469 | "## Funciones en otros módulos\n", 470 | "\n", 471 | "**Python tiene muchas funciones ya implementadas, pero no disponibles inmediatamente.**\n", 472 | "\n", 473 | "**Para usar estas funciones, debes importar un módulo.**\n", 474 | "\n", 475 | "**Podés encontrar estos módulos leyendo la [documentación online de Python](https://docs.python.org/3/).**\n", 476 | "\n" 477 | ] 478 | }, 479 | { 480 | "cell_type": "markdown", 481 | "metadata": { 482 | "id": "ESQ-gik9Dw7v" 483 | }, 484 | "source": [ 485 | "**Llamando a una función sin importar el módulo**" 486 | ] 487 | }, 488 | { 489 | "cell_type": "code", 490 | "metadata": { 491 | "colab": { 492 | "base_uri": "https://localhost:8080/", 493 | "height": 214 494 | }, 495 | "id": "7AtglcjjDw7v", 496 | "outputId": "406f41d2-b04f-4bae-fcce-809bad04cb51" 497 | }, 498 | "source": [ 499 | "print(math.factorial(20)) # No importamos el módulo math previamente\n", 500 | "\n", 501 | "# Python output:\n", 502 | "# NameError: name 'math' is not defined" 503 | ], 504 | "execution_count": 10, 505 | "outputs": [ 506 | { 507 | "output_type": "error", 508 | "ename": "NameError", 509 | "evalue": "ignored", 510 | "traceback": [ 511 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 512 | "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", 513 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmath\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mfactorial\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m20\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# No importamos el módulo math previamente\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 2\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;31m# Python output:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;31m# NameError: name 'math' is not defined\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 514 | "\u001b[0;31mNameError\u001b[0m: name 'math' is not defined" 515 | ] 516 | } 517 | ] 518 | }, 519 | { 520 | "cell_type": "markdown", 521 | "metadata": { 522 | "id": "v7cZ6s-mDw7v" 523 | }, 524 | "source": [ 525 | "**Llamando a la función importando el módulo**" 526 | ] 527 | }, 528 | { 529 | "cell_type": "code", 530 | "metadata": { 531 | "colab": { 532 | "base_uri": "https://localhost:8080/" 533 | }, 534 | "id": "DYUtTXshDw7w", 535 | "outputId": "869b1109-54e2-40d9-90fa-eddecc8c402c" 536 | }, 537 | "source": [ 538 | "import math\n", 539 | "print(math.factorial(20)) # mucho mejor...\n", 540 | "\n", 541 | "# Notar que el nombre del módulo es incluido antes que el nombre de la función separado por punto.\n" 542 | ], 543 | "execution_count": 11, 544 | "outputs": [ 545 | { 546 | "output_type": "stream", 547 | "text": [ 548 | "2432902008176640000\n" 549 | ], 550 | "name": "stdout" 551 | } 552 | ] 553 | }, 554 | { 555 | "cell_type": "markdown", 556 | "metadata": { 557 | "id": "xytYWDc2Dw7w" 558 | }, 559 | "source": [ 560 | "## Alcance de las variables (scope)\n", 561 | "\n", 562 | "**Las variables existene en un alcance especifico basado en donde ellas fueron definidas.**\n", 563 | "\n", 564 | "**Esto significa que no son visibles o no pueden ser usadas por fuera de ese alcance en otras partes del código.**" 565 | ] 566 | }, 567 | { 568 | "cell_type": "code", 569 | "metadata": { 570 | "colab": { 571 | "base_uri": "https://localhost:8080/", 572 | "height": 265 573 | }, 574 | "id": "-RDvV2pODw7w", 575 | "outputId": "c57df504-efec-453a-cac0-4baeda0df179" 576 | }, 577 | "source": [ 578 | "\n", 579 | "def f(x_scope_test):\n", 580 | " print(\"x_scope_test:\", x_scope_test)\n", 581 | " y_scope_test = 5\n", 582 | " print(\"y_scope_test:\", y_scope_test)\n", 583 | " return x_scope_test + y_scope_test\n", 584 | "\n", 585 | "print(f(4))\n", 586 | "print(x_scope_test) # No va a funcionar!\n", 587 | "print(y_scope_test) # tampoco funciona!" 588 | ], 589 | "execution_count": 12, 590 | "outputs": [ 591 | { 592 | "output_type": "stream", 593 | "text": [ 594 | "x_scope_test: 4\n", 595 | "y_scope_test: 5\n", 596 | "9\n" 597 | ], 598 | "name": "stdout" 599 | }, 600 | { 601 | "output_type": "error", 602 | "ename": "NameError", 603 | "evalue": "ignored", 604 | "traceback": [ 605 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 606 | "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", 607 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mf\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m4\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 9\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx_scope_test\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# No va a funcionar!\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 10\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0my_scope_test\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# tampoco funciona!\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 608 | "\u001b[0;31mNameError\u001b[0m: name 'x_scope_test' is not defined" 609 | ] 610 | } 611 | ] 612 | }, 613 | { 614 | "cell_type": "markdown", 615 | "metadata": { 616 | "id": "uwuYNgxWDw7x" 617 | }, 618 | "source": [ 619 | "**Las variables en funciones tienen un alcance local.**\n", 620 | "\n", 621 | "**Solo existen dentro de la función y no tienen relación con las variables del mismo nombre en diferentes funciones.**" 622 | ] 623 | }, 624 | { 625 | "cell_type": "code", 626 | "metadata": { 627 | "colab": { 628 | "base_uri": "https://localhost:8080/" 629 | }, 630 | "id": "2fI-BaQdDw7x", 631 | "outputId": "c3ec0d47-93d6-4664-8588-c7b50b5b3a60" 632 | }, 633 | "source": [ 634 | "def f(x):\n", 635 | " print(\"In f, x =\", x)\n", 636 | " x += 5\n", 637 | " return x\n", 638 | "\n", 639 | "def g(x):\n", 640 | " y = f(x*2)\n", 641 | " print(\"In g, x =\", x)\n", 642 | " z = f(x*3)\n", 643 | " print(\"In g, x =\", x)\n", 644 | " return y + z\n", 645 | "\n", 646 | "print(g(2))\n", 647 | "\n", 648 | "# Otro ejemplo\n", 649 | "\n", 650 | "def f(x):\n", 651 | " print(\"In f, x =\", x)\n", 652 | " x += 7\n", 653 | " return round(x / 3)\n", 654 | "\n", 655 | "def g(x):\n", 656 | " x *= 10\n", 657 | " return 2 * f(x)\n", 658 | "\n", 659 | "def h(x):\n", 660 | " x += 3\n", 661 | " return f(x+4) + g(x)\n", 662 | "\n", 663 | "print(h(f(1)))" 664 | ], 665 | "execution_count": 13, 666 | "outputs": [ 667 | { 668 | "output_type": "stream", 669 | "text": [ 670 | "In f, x = 4\n", 671 | "In g, x = 2\n", 672 | "In f, x = 6\n", 673 | "In g, x = 2\n", 674 | "20\n", 675 | "In f, x = 1\n", 676 | "In f, x = 10\n", 677 | "In f, x = 60\n", 678 | "50\n" 679 | ], 680 | "name": "stdout" 681 | } 682 | ] 683 | }, 684 | { 685 | "cell_type": "markdown", 686 | "metadata": { 687 | "id": "2LyD_pl-Dw7x" 688 | }, 689 | "source": [ 690 | "**Cuando definimos variables fuera de las funciones, estas tienen un alcance global (global scope) y pueden ser usadas en cualquier lado.**\n" 691 | ] 692 | }, 693 | { 694 | "cell_type": "code", 695 | "metadata": { 696 | "colab": { 697 | "base_uri": "https://localhost:8080/" 698 | }, 699 | "id": "JYiiRg7nDw7y", 700 | "outputId": "23f77f13-ba66-4b7a-acfa-42b7d47e8b04" 701 | }, 702 | "source": [ 703 | "# En general, deberían evitar usar variables globales.\n", 704 | "# Al usarlas nuestro código pierde calidad y estilo.\n", 705 | "# Aún así, se debe saber como funcionan, ya que se usaran en algún momento.\n", 706 | "\n", 707 | "g = 100\n", 708 | "\n", 709 | "def f(x):\n", 710 | " return x + g\n", 711 | "\n", 712 | "print(f(5)) # 105\n", 713 | "print(f(6)) # 106\n", 714 | "print(g) # 100\n", 715 | "\n", 716 | "# Otro ejemplo\n", 717 | "\n", 718 | "def f(x):\n", 719 | " # Si modificamos la variable global debemos declararla como global.\n", 720 | " # Sino, Python asumirá que es una variable local.\n", 721 | " global g\n", 722 | " g += 1\n", 723 | " return x + g\n", 724 | "\n", 725 | "print(f(5)) # 106\n", 726 | "print(f(6)) # 108\n", 727 | "print(g) # 102" 728 | ], 729 | "execution_count": 14, 730 | "outputs": [ 731 | { 732 | "output_type": "stream", 733 | "text": [ 734 | "105\n", 735 | "106\n", 736 | "100\n", 737 | "106\n", 738 | "108\n", 739 | "102\n" 740 | ], 741 | "name": "stdout" 742 | } 743 | ] 744 | }, 745 | { 746 | "cell_type": "markdown", 747 | "metadata": { 748 | "id": "XrpGBLSKDw7y" 749 | }, 750 | "source": [ 751 | "## Retornando Valores\n", 752 | "\n", 753 | "**Ejemplo básico**\n" 754 | ] 755 | }, 756 | { 757 | "cell_type": "code", 758 | "metadata": { 759 | "colab": { 760 | "base_uri": "https://localhost:8080/" 761 | }, 762 | "id": "U68WMoOxDw7y", 763 | "outputId": "7a8ee081-6069-4b56-98c2-b8d8d27fa3e0" 764 | }, 765 | "source": [ 766 | "def esPositivo(x):\n", 767 | " return (x > 0)\n", 768 | "\n", 769 | "print(esPositivo(5)) # True\n", 770 | "print(esPositivo(-5)) # False\n", 771 | "print(esPositivo(0)) # False" 772 | ], 773 | "execution_count": 15, 774 | "outputs": [ 775 | { 776 | "output_type": "stream", 777 | "text": [ 778 | "True\n", 779 | "False\n", 780 | "False\n" 781 | ], 782 | "name": "stdout" 783 | } 784 | ] 785 | }, 786 | { 787 | "cell_type": "markdown", 788 | "metadata": { 789 | "id": "yMYB0pM3Dw7y" 790 | }, 791 | "source": [ 792 | "**La función terminará al encontrar un _return_**" 793 | ] 794 | }, 795 | { 796 | "cell_type": "code", 797 | "metadata": { 798 | "colab": { 799 | "base_uri": "https://localhost:8080/" 800 | }, 801 | "id": "D4DHnDuBDw7z", 802 | "outputId": "2defae49-771a-4ec0-e8b9-3f28edbe9735" 803 | }, 804 | "source": [ 805 | "def esPositivo(x):\n", 806 | " print(\"Hola!\") # Imprime \"Hola\"\n", 807 | " return (x > 0)\n", 808 | " print(\"Chau!\") # No imprimirá nada, nunca se ejecutará (\"código muerto\"/\"dead code\")\n", 809 | "\n", 810 | "print(esPositivo(5)) # Imprime \"Hola\", luego True" 811 | ], 812 | "execution_count": 16, 813 | "outputs": [ 814 | { 815 | "output_type": "stream", 816 | "text": [ 817 | "Hola!\n", 818 | "True\n" 819 | ], 820 | "name": "stdout" 821 | } 822 | ] 823 | }, 824 | { 825 | "cell_type": "markdown", 826 | "metadata": { 827 | "id": "S9j22PMbDw7z" 828 | }, 829 | "source": [ 830 | "** Si no definimos un _return_ la función devuelve _None_**" 831 | ] 832 | }, 833 | { 834 | "cell_type": "code", 835 | "metadata": { 836 | "colab": { 837 | "base_uri": "https://localhost:8080/" 838 | }, 839 | "id": "9Csgw6vpDw7z", 840 | "outputId": "27e510f6-f994-4557-9205-0a8fc2ed4139" 841 | }, 842 | "source": [ 843 | "def f(x):\n", 844 | " x + 42\n", 845 | "\n", 846 | "print(f(5)) # None" 847 | ], 848 | "execution_count": 17, 849 | "outputs": [ 850 | { 851 | "output_type": "stream", 852 | "text": [ 853 | "None\n" 854 | ], 855 | "name": "stdout" 856 | } 857 | ] 858 | }, 859 | { 860 | "cell_type": "markdown", 861 | "metadata": { 862 | "id": "fiZkb6LDDw7z" 863 | }, 864 | "source": [ 865 | "**Otro ejemplo**" 866 | ] 867 | }, 868 | { 869 | "cell_type": "code", 870 | "metadata": { 871 | "colab": { 872 | "base_uri": "https://localhost:8080/" 873 | }, 874 | "id": "920ZMPwmDw7z", 875 | "outputId": "97e11160-58a4-4a45-d076-09bd1a11cd7a" 876 | }, 877 | "source": [ 878 | "def f(x):\n", 879 | " result = x + 42\n", 880 | "\n", 881 | "print(f(5)) # None" 882 | ], 883 | "execution_count": 18, 884 | "outputs": [ 885 | { 886 | "output_type": "stream", 887 | "text": [ 888 | "None\n" 889 | ], 890 | "name": "stdout" 891 | } 892 | ] 893 | }, 894 | { 895 | "cell_type": "markdown", 896 | "metadata": { 897 | "id": "i0WKfBkiDw70" 898 | }, 899 | "source": [ 900 | "## Imprimir vs. Retornar\n", 901 | "\n", 902 | "**Un error común es confundir _print_ y _return_ o imprimir y retornar**\n" 903 | ] 904 | }, 905 | { 906 | "cell_type": "code", 907 | "metadata": { 908 | "colab": { 909 | "base_uri": "https://localhost:8080/", 910 | "height": 265 911 | }, 912 | "id": "2_olyZGxDw70", 913 | "outputId": "77126cf9-48ca-466b-8440-4788feca8302" 914 | }, 915 | "source": [ 916 | "def cubo(x):\n", 917 | " print(x**3) # Aquí está el error!\n", 918 | "\n", 919 | "cubo(2) # parece que funciona!\n", 920 | "print(cubo(3)) # Imprime None, raro, no?\n", 921 | "print(2*cubo(4)) # Error!" 922 | ], 923 | "execution_count": 19, 924 | "outputs": [ 925 | { 926 | "output_type": "stream", 927 | "text": [ 928 | "8\n", 929 | "27\n", 930 | "None\n", 931 | "64\n" 932 | ], 933 | "name": "stdout" 934 | }, 935 | { 936 | "output_type": "error", 937 | "ename": "TypeError", 938 | "evalue": "ignored", 939 | "traceback": [ 940 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 941 | "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", 942 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mcubo\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# parece que funciona!\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcubo\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# Imprime None, raro, no?\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 6\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0mcubo\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m4\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# Error!\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 943 | "\u001b[0;31mTypeError\u001b[0m: unsupported operand type(s) for *: 'int' and 'NoneType'" 944 | ] 945 | } 946 | ] 947 | }, 948 | { 949 | "cell_type": "markdown", 950 | "metadata": { 951 | "id": "2kAEuuHpDw70" 952 | }, 953 | "source": [ 954 | "**Una vez más**" 955 | ] 956 | }, 957 | { 958 | "cell_type": "code", 959 | "metadata": { 960 | "colab": { 961 | "base_uri": "https://localhost:8080/" 962 | }, 963 | "id": "qMKanenSDw70", 964 | "outputId": "d6d38bf7-46bd-4abe-ac5f-e17a273ac117" 965 | }, 966 | "source": [ 967 | "def cubo(x):\n", 968 | " return (x**3) # Ahora está mejor!\n", 969 | "\n", 970 | "cubo(2) # parece que es ignorado, por qué?\n", 971 | "print(cubo(3)) # Funciona!\n", 972 | "print(2*cubo(4)) # Funciona!" 973 | ], 974 | "execution_count": 20, 975 | "outputs": [ 976 | { 977 | "output_type": "stream", 978 | "text": [ 979 | "27\n", 980 | "128\n" 981 | ], 982 | "name": "stdout" 983 | } 984 | ] 985 | }, 986 | { 987 | "cell_type": "markdown", 988 | "metadata": { 989 | "id": "E7y754T0Dw71" 990 | }, 991 | "source": [ 992 | "## Composición de funciones" 993 | ] 994 | }, 995 | { 996 | "cell_type": "code", 997 | "metadata": { 998 | "colab": { 999 | "base_uri": "https://localhost:8080/" 1000 | }, 1001 | "id": "3TEa1dkuDw71", 1002 | "outputId": "45db13fc-13db-459f-86c6-c07d01edaaab" 1003 | }, 1004 | "source": [ 1005 | "def f(w):\n", 1006 | " return 10*w\n", 1007 | "\n", 1008 | "def g(x, y):\n", 1009 | " return f(3*x) + y\n", 1010 | "\n", 1011 | "def h(z):\n", 1012 | " return f(g(z, f(z+1)))\n", 1013 | "\n", 1014 | "print(h(1))" 1015 | ], 1016 | "execution_count": 21, 1017 | "outputs": [ 1018 | { 1019 | "output_type": "stream", 1020 | "text": [ 1021 | "500\n" 1022 | ], 1023 | "name": "stdout" 1024 | } 1025 | ] 1026 | }, 1027 | { 1028 | "cell_type": "markdown", 1029 | "metadata": { 1030 | "id": "Uv6_mU8PDw71" 1031 | }, 1032 | "source": [ 1033 | "## Funciones Auxiliares (helpers)" 1034 | ] 1035 | }, 1036 | { 1037 | "cell_type": "code", 1038 | "metadata": { 1039 | "colab": { 1040 | "base_uri": "https://localhost:8080/" 1041 | }, 1042 | "id": "ZmWDWC5sDw71", 1043 | "outputId": "15dabfe1-5058-452a-b9b8-93ed3ce54a50" 1044 | }, 1045 | "source": [ 1046 | "# Regularmente escribimos funciones para resolver problemas.\n", 1047 | "# Podemos también escribir funciones para guardar una acción que será usada muchas veces.\n", 1048 | "# Esas funciones son llamadas \"helpers\" o funciones auxiliares.\n", 1049 | "\n", 1050 | "def ultimo_digito(n):\n", 1051 | " return n%10\n", 1052 | "\n", 1053 | "def max_ultimo_digito(x, y):\n", 1054 | " return max(ultimo_digito(x), ultimo_digito(y))\n", 1055 | "\n", 1056 | "print(max_ultimo_digito(134, 672)) # 4\n", 1057 | "print(max_ultimo_digito(132, 674)) # sigue siendo 4" 1058 | ], 1059 | "execution_count": 22, 1060 | "outputs": [ 1061 | { 1062 | "output_type": "stream", 1063 | "text": [ 1064 | "4\n", 1065 | "4\n" 1066 | ], 1067 | "name": "stdout" 1068 | } 1069 | ] 1070 | }, 1071 | { 1072 | "cell_type": "markdown", 1073 | "metadata": { 1074 | "id": "P-93KCMhDw71" 1075 | }, 1076 | "source": [ 1077 | "## Funciones recomendadas" 1078 | ] 1079 | }, 1080 | { 1081 | "cell_type": "code", 1082 | "metadata": { 1083 | "colab": { 1084 | "base_uri": "https://localhost:8080/" 1085 | }, 1086 | "id": "ylExNrZVDw72", 1087 | "outputId": "665b8daa-4a36-4d15-c359-e6d6a0688e49" 1088 | }, 1089 | "source": [ 1090 | "# Hay algunas funciones en módulo que definitivamente querrán usar\n", 1091 | "\n", 1092 | "# PRIMERO: la función builtin *round* tiene un comportamiento confuso cuando redondea 0.5\n", 1093 | "# Usar nuestra función redondearMitadParaArriba para arreglar esto.\n", 1094 | "\n", 1095 | "def redondearMitadParaArriba(d):\n", 1096 | " # Round to nearest with ties going away from zero.\n", 1097 | " # You do not need to understand how this function works.\n", 1098 | " import decimal\n", 1099 | " rounding = decimal.ROUND_HALF_UP\n", 1100 | " return int(decimal.Decimal(d).to_integral_value(rounding=rounding))\n", 1101 | "\n", 1102 | "print(round(0.5)) # devuelve 0!\n", 1103 | "print(round(1.5)) # ... y esto devuelve 2! que confuso!\n", 1104 | "print(redondearMitadParaArriba(0.5)) # Ahora nuestra función siempre redondea 0.5 hacia arriba.\n", 1105 | "print(redondearMitadParaArriba(1.5)) # Sigue redondeando para arriba.\n", 1106 | "\n", 1107 | "# SEGUNDO: cuando comparamos reales, == no funciona del todo bien.\n", 1108 | "# Usaremos almostEqual para comparar reales\n", 1109 | "\n", 1110 | "print(0.1 + 0.1 == 0.2) # True, pero...\n", 1111 | "d1 = 0.1 + 0.1 + 0.1\n", 1112 | "d2 = 0.3\n", 1113 | "print(d1 == d2) # False!\n", 1114 | "print(d1) # Imprime 0.30000000000000004 (ups!)\n", 1115 | "print(d1 - d2) # Imprime 5.55111512313e-17 (muy chico, pero no es cero!)\n", 1116 | "# MORALEJA: nunca usar == con reales!\n", 1117 | "\n", 1118 | "# Python incluye una función builtin math.isclose(), pero esa función\n", 1119 | "# tiene un comportamiento confuso cuando comparamos valores cercanos a 0. \n", 1120 | "# En su lugar, haremos nuestra propia función de isclose:\n", 1121 | "\n", 1122 | "def casiIgual(x, y):\n", 1123 | " return abs(x - y) < 10**-9\n", 1124 | "\n", 1125 | "# Esto funcionará correctamente!\n", 1126 | "print(casiIgual(0, 0.0000000000001))\n", 1127 | "print(casiIgual(d1, d2))" 1128 | ], 1129 | "execution_count": 23, 1130 | "outputs": [ 1131 | { 1132 | "output_type": "stream", 1133 | "text": [ 1134 | "0\n", 1135 | "2\n", 1136 | "1\n", 1137 | "2\n", 1138 | "True\n", 1139 | "False\n", 1140 | "0.30000000000000004\n", 1141 | "5.551115123125783e-17\n", 1142 | "True\n", 1143 | "True\n" 1144 | ], 1145 | "name": "stdout" 1146 | } 1147 | ] 1148 | }, 1149 | { 1150 | "cell_type": "markdown", 1151 | "metadata": { 1152 | "id": "Y9XocewoDw72" 1153 | }, 1154 | "source": [ 1155 | "## Funciones Test\n", 1156 | "\n", 1157 | "**Una función rota para probar**\n" 1158 | ] 1159 | }, 1160 | { 1161 | "cell_type": "code", 1162 | "metadata": { 1163 | "colab": { 1164 | "base_uri": "https://localhost:8080/" 1165 | }, 1166 | "id": "4I910Dj1Dw72", 1167 | "outputId": "a137c4f1-5177-4c4a-fc5e-4b571c62b0fc" 1168 | }, 1169 | "source": [ 1170 | "def ultimoDigito(n):\n", 1171 | " return n%10\n", 1172 | "\n", 1173 | "def testUltimoDigito():\n", 1174 | " print(\"Testing ultimoDigito()...\", end=\"\")\n", 1175 | " assert(ultimoDigito(5) == 5)\n", 1176 | " assert(ultimoDigito(123) == 3)\n", 1177 | " assert(ultimoDigito(100) == 0)\n", 1178 | " assert(ultimoDigito(999) == 9)\n", 1179 | " print(\"Passed!\")\n", 1180 | "\n", 1181 | "testUltimoDigito() # Passed! Pero por qué está mal esto?" 1182 | ], 1183 | "execution_count": 24, 1184 | "outputs": [ 1185 | { 1186 | "output_type": "stream", 1187 | "text": [ 1188 | "Testing ultimoDigito()...Passed!\n" 1189 | ], 1190 | "name": "stdout" 1191 | } 1192 | ] 1193 | }, 1194 | { 1195 | "cell_type": "markdown", 1196 | "metadata": { 1197 | "id": "6ee9ZVHPDw73" 1198 | }, 1199 | "source": [ 1200 | "**Una versión mejorada**" 1201 | ] 1202 | }, 1203 | { 1204 | "cell_type": "code", 1205 | "metadata": { 1206 | "colab": { 1207 | "base_uri": "https://localhost:8080/", 1208 | "height": 333 1209 | }, 1210 | "id": "CgB7d92PDw73", 1211 | "outputId": "0088da80-ed03-4dfb-f653-9043d9ffc66b" 1212 | }, 1213 | "source": [ 1214 | "def ultimoDigito(n):\n", 1215 | " return n%10\n", 1216 | "\n", 1217 | "def testUltimoDigito():\n", 1218 | " print(\"Testing ultimoDigito()...\", end=\"\")\n", 1219 | " assert(ultimoDigito(5) == 5)\n", 1220 | " assert(ultimoDigito(123) == 3)\n", 1221 | " assert(ultimoDigito(100) == 0)\n", 1222 | " assert(ultimoDigito(999) == 9)\n", 1223 | " assert(ultimoDigito(-123) == 3) # Agregamos este test\n", 1224 | " print(\"Passed!\")\n", 1225 | "\n", 1226 | "testUltimoDigito() # Crashed! Entonces la función de Test funcionó!" 1227 | ], 1228 | "execution_count": 25, 1229 | "outputs": [ 1230 | { 1231 | "output_type": "stream", 1232 | "text": [ 1233 | "Testing ultimoDigito()..." 1234 | ], 1235 | "name": "stdout" 1236 | }, 1237 | { 1238 | "output_type": "error", 1239 | "ename": "AssertionError", 1240 | "evalue": "ignored", 1241 | "traceback": [ 1242 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 1243 | "\u001b[0;31mAssertionError\u001b[0m Traceback (most recent call last)", 1244 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Passed!\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 12\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 13\u001b[0;31m \u001b[0mtestUltimoDigito\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# Crashed! Entonces la función de Test funcionó!\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 1245 | "\u001b[0;32m\u001b[0m in \u001b[0;36mtestUltimoDigito\u001b[0;34m()\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0;32massert\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0multimoDigito\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m100\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 9\u001b[0m \u001b[0;32massert\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0multimoDigito\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m999\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;36m9\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 10\u001b[0;31m \u001b[0;32massert\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0multimoDigito\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m123\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;36m3\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# Agregamos este test\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 11\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Passed!\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 12\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n", 1246 | "\u001b[0;31mAssertionError\u001b[0m: " 1247 | ] 1248 | } 1249 | ] 1250 | } 1251 | ] 1252 | } --------------------------------------------------------------------------------