{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "view-in-github", "colab_type": "text" }, "source": [ "\"Open" ] }, { "cell_type": "markdown", "id": "887eb6d8", "metadata": { "id": "887eb6d8" }, "source": [ "# Bucle ```for``` \n", "\n", "Un bucle es una estructura de control que repite un bloque de código un **número conocido de veces**. \n", "\n", "El bloque de instrucciones que se repite se denomina **cuerpo del bucle**, \n", "\n", "cada repetición se denomina **iteración**." ] }, { "cell_type": "markdown", "id": "5d0df1a8", "metadata": { "id": "5d0df1a8" }, "source": [ "## Iterando los elementos de una lista" ] }, { "cell_type": "code", "execution_count": 1, "id": "ac051410", "metadata": { "id": "ac051410", "outputId": "0c209613-6a03-4638-8a40-ddd14edd37ed", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "naranja\n", "banana\n", "manzana\n" ] } ], "source": [ "frutas = [\"naranja\", \"banana\", \"manzana\"]\n", "for x in frutas:\n", " print(x)" ] }, { "cell_type": "markdown", "id": "286f882a", "metadata": { "id": "286f882a" }, "source": [ "La variable de control ```x``` es una variable auxiliar que toma el valor sucesivo de los elementos de la lista." ] }, { "cell_type": "markdown", "id": "effecdca", "metadata": { "id": "effecdca" }, "source": [ "## Iterando las letras de una palabra" ] }, { "cell_type": "code", "execution_count": 2, "id": "ff955d7d", "metadata": { "id": "ff955d7d", "outputId": "c75b11ff-59e1-4229-b1da-ac630ade8d8e", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "b\n", "a\n", "n\n", "a\n", "n\n", "a\n" ] } ], "source": [ "palabra = \"banana\"\n", "for letra in palabra:\n", " print(letra)" ] }, { "cell_type": "markdown", "id": "1fece682", "metadata": { "id": "1fece682" }, "source": [ "Ahora la variable de control es ```letra``` que irá tomando sucesivamente los diferentes caracteres del string." ] }, { "cell_type": "markdown", "id": "9cc1ab5f", "metadata": { "id": "9cc1ab5f" }, "source": [ "## Usando la función ```range()```" ] }, { "cell_type": "markdown", "id": "6bd9dd64", "metadata": { "id": "6bd9dd64" }, "source": [ "Para efectuar un cierto número de ciclos, podemos usar la función ```range()```. \n", "La función ```range()``` devuelve una secuencia de números, comenzando en 0 de forma predeterminada, se incrementa en 1 (de forma predeterminada) y termina en un número especificado." ] }, { "cell_type": "code", "execution_count": 3, "id": "29b3bbdd", "metadata": { "id": "29b3bbdd", "outputId": "94acc766-9cc0-4ae7-e318-36d7a1ef4626", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n" ] } ], "source": [ "for i in range(5): #La variable i toma los valores de 0 a 4\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 4, "id": "2c023024", "metadata": { "id": "2c023024", "outputId": "751a8ebe-6832-4f73-e49f-9bf94ffc39d4", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "1\n", "2\n", "3\n", "4\n" ] } ], "source": [ "for i in range(1,5): #La variable i toma los valores de 1 a 4\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 5, "id": "a6a92e3e", "metadata": { "id": "a6a92e3e", "outputId": "15d278ad-a811-4dc1-f847-3af4ff162cea", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "10\n", "12\n", "14\n", "16\n", "18\n" ] } ], "source": [ "for i in range(10,20,2): #La variable i toma los valores: 10, 12, 14, 16, 18.\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 6, "id": "a590ab07", "metadata": { "id": "a590ab07", "outputId": "d091dc77-1206-46f2-9dfa-ddf121528244", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "50\n", "40\n", "30\n", "20\n", "10\n" ] } ], "source": [ "for i in range(50,0,-10): #La variable i toma los valores: 50, 40, 30, 20, 10.\n", " print(i)" ] }, { "cell_type": "markdown", "id": "b74cfa38", "metadata": { "id": "b74cfa38" }, "source": [ "```range()``` es un objeto de tipo range." ] }, { "cell_type": "code", "execution_count": 7, "id": "4ede5f19", "metadata": { "id": "4ede5f19", "outputId": "d3a87606-5b20-4efa-aab1-1e7a699501f3", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "range(0, 5)" ] }, "metadata": {}, "execution_count": 7 } ], "source": [ "range(5)" ] }, { "cell_type": "code", "execution_count": 8, "id": "17cfc14a", "metadata": { "id": "17cfc14a", "outputId": "c6a79f62-4616-4095-ccd3-b9f5c1f59ed0", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "range" ] }, "metadata": {}, "execution_count": 8 } ], "source": [ "type(range(5))" ] }, { "cell_type": "markdown", "id": "3cc63e34", "metadata": { "id": "3cc63e34" }, "source": [ "Podemos convertir el objeto range en una lista. \n", "Ocupa menos memoria range(1000) que la lista correspondiente." ] }, { "cell_type": "code", "execution_count": 9, "id": "6e2bf779", "metadata": { "id": "6e2bf779", "outputId": "36514b78-c91f-4690-9d75-60bdadad931c", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "[0, 1, 2, 3, 4]" ] }, "metadata": {}, "execution_count": 9 } ], "source": [ "list(range(5))" ] }, { "cell_type": "markdown", "id": "b6702712", "metadata": { "id": "b6702712" }, "source": [ "## La instrucción ```pass```" ] }, { "cell_type": "markdown", "id": "e285d1a4", "metadata": { "id": "e285d1a4" }, "source": [ "Los bucles ```for``` no pueden estar vacíos, pero si está haciendo prueba y aún tiene el bucle ```for``` sin contenido, ingrese la instrucción ```pass``` para evitar errores." ] }, { "cell_type": "code", "execution_count": 10, "id": "037aa485", "metadata": { "id": "037aa485" }, "outputs": [], "source": [ "for i in range(10):\n", " pass" ] }, { "cell_type": "markdown", "id": "f2c687a1", "metadata": { "id": "f2c687a1" }, "source": [ "## La instrucción ```break```" ] }, { "cell_type": "markdown", "id": "7475bda0", "metadata": { "id": "7475bda0" }, "source": [ "Interrumpir con **```break```**. Con la instrucción ```break``` podemos detener el ciclo antes de que haya pasado por todos los elementos" ] }, { "cell_type": "code", "execution_count": 11, "id": "910085c9", "metadata": { "id": "910085c9", "outputId": "1ce327b2-d562-4533-a594-e63aaaafba5a", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "5\n", "7\n", "9\n", "11\n", "13\n", "15\n" ] } ], "source": [ "for i in range(5,25,2):\n", " if i == 17:\n", " break\n", "\n", " print(i)" ] }, { "cell_type": "markdown", "id": "e14f02a0", "metadata": { "id": "e14f02a0" }, "source": [ "En el ejemplo anterior, si convertimos el ```break``` en un comentario, el código nos daría error. Se soluciona poniendo ```pass``` después del comentario." ] }, { "cell_type": "markdown", "id": "3e24b2ce", "metadata": { "id": "3e24b2ce" }, "source": [ "**Ejercicio** \n", "¿Qué pasaría si en el ejemplo anterior el ```print``` va antes del ```if```?" ] }, { "cell_type": "markdown", "id": "4689208b", "metadata": { "id": "4689208b" }, "source": [ "## La instrucción ```continue```" ] }, { "cell_type": "markdown", "id": "3596d38a", "metadata": { "id": "3596d38a" }, "source": [ "Con la instrucción **```continue```** podemos detener la iteración actual del ciclo y continuar con la siguiente." ] }, { "cell_type": "code", "execution_count": 12, "id": "85db8dc1", "metadata": { "id": "85db8dc1", "outputId": "b87c4a96-5ed2-4614-ba5d-61c69f68893c", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "primavera\n", "otoño\n", "invierno\n" ] } ], "source": [ "for i in ['primavera', 'verano', 'otoño', 'invierno']:\n", " if i == 'verano':\n", " continue\n", " print(i)" ] }, { "cell_type": "markdown", "id": "78eb271d", "metadata": { "id": "78eb271d" }, "source": [ "## La instrucción ```else``` en un bucle ```for```" ] }, { "cell_type": "markdown", "id": "b88978f5", "metadata": { "id": "b88978f5" }, "source": [ "```Else``` se ejecutará cuando el bucle haya finalizado." ] }, { "cell_type": "code", "execution_count": 13, "id": "5d0d49e1", "metadata": { "id": "5d0d49e1", "outputId": "078556c7-bbea-4c22-b440-ac5d893fd3c9", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "El bucle ha finalizado.\n" ] } ], "source": [ "for i in range(6):\n", " print(i)\n", "else:\n", " print(\"El bucle ha finalizado.\")" ] }, { "cell_type": "markdown", "id": "7ba92c6d", "metadata": { "id": "7ba92c6d" }, "source": [ "La utilidad de ```else``` reside en que si se utiliza en un bucle ```for``` con un ```break```, si se interrumpe la ejecución del bucle, y en ese caso, no se llegará a ejecutar el bloque de código del ```else```." ] }, { "cell_type": "code", "execution_count": 14, "id": "582b3521", "metadata": { "id": "582b3521", "outputId": "b424c7d7-5094-463a-d2cf-738652c95276", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "0\n", "1\n", "2\n", "3\n" ] } ], "source": [ "for i in range(6):\n", " print(i)\n", " if i == 3:\n", " break\n", "else:\n", " print(\"El bucle ha finalizado.\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.11" }, "colab": { "name": "0350_bucle_for.ipynb", "provenance": [], "include_colab_link": true } }, "nbformat": 4, "nbformat_minor": 5 }