{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "< [Tuplas, Listas, y Diccionarios](PythonIntroCh5.ipynb) | [Contenido](PythonIntro.ipynb) | [Clases](PythonIntroCh7.ipynb) >" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 6. El Ciclo For\n", "## 6.1 Introducción\n", "\n", "Bien, en la primer lección acerca de los bucles. Mencione que pospondría la enseñanza del Ciclo `For`, hasta que revisaramos las listas. ¡El momento ha llegado!\n", "\n", "## 6.2 El ciclo `for`\n", "Basicamente, el ciclo `for` hace algo para cada valor en una lista. La forma en que se realiza es un poco confusa, por lo demás es básica. El siguiente ejemplo de código:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "45\n", "eat me\n", "90210.07\n", "The day has come, the walrus said, to speak of many things\n", "-67\n" ] }, { "data": { "text/plain": [ "str" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Ejemplo del ciclo 'for'\n", "# Primero, crea una lista para que itere a tráves de ella: \n", "\n", "newList = [45, 'eat me', 90210.07, \"The day has come, the walrus said, \\\n", "to speak of many things\", -67]\n", "\n", "# Crea el ciclo:\n", "# Va a tráves de la lista newList, y secuencialmente coloca cada información\n", "# dentro de una variable, y corre el ciclo\n", "for value in newList:\n", " print(value)\n", "\n", "type(newList[1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Como puedes ver, cuando el ciclo se ejecuta, este corre a tráves de todos los valores en la lista mencionada después de `in`. Después coloca los calores dentro de `value` y se ejecuta a través del ciclo, cada ocasión con el valor cambia a algo distinto. Veamos otra vez, en un programa clásico cheerleading que todos conocemos:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gimme a p!\n", "p!\n", "Gimme a e!\n", "e!\n", "Gimme a r!\n", "r!\n", "Gimme a r!\n", "r!\n", "Gimme a o!\n", "o!\n", "What does that spell?\n", "perro!\n" ] } ], "source": [ "# cheerleading program\n", "word = input(\"Who do you go for? \")\n", "\n", "for letter in word:\n", " call = \"Gimme a \" + letter + \"!\"\n", " print(call)\n", " print(letter + \"!\")\n", "\n", "print(\"What does that spell?\")\n", "print(word + \"!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Acabas de aprender dos cosas:\n", "* Como puedes observar, las cadenas (recuerda - las cadenas son líneas de texto) son sólo listas con muchos carácteres.\n", "* El programa recorrio cada uno de los carácteres (valores) en una palabra, y la despliega sobre la pantalla.
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Y eso es todo lo que hay para el Ciclo For." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6.3 Como crear una función de menú\n", "Ahora pasemos a la parte práctica de la lección. Iniciemos la escritura de programas. Hasta ahora hemos aprendido de variables, listas, bucles y funciones. Con ello es suficiente para programar un poco. Así que dejaremos una tarea." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```Python\n", "# THE MENU FUNCTION\n", "# El programa pregunta por una cadena con todas las opciones del menú\n", "# y la cadena de texto pregunta por una pregunta.\n", "# asegurate que cada entrada es unica.\n", "\n", "def menu(list, question):\n", " for entry in list:\n", " print(1 + list.index(entry),end=\"\"))\n", " print (\") \" + entry)\n", "\n", " return eval(input(question)) - 1\n", "\n", "# def menu(list, question): le indica a la función a\n", "# solicitar dos datos:\n", "# Una lista de todas las entradas del menú,\n", "# y la pregunta que se realizará cuando se hayan desplegado todas las opciones\n", "\n", "# para las entradas en la lista: es más o menos decir;\n", "#'para cada entrada de la lista, haz lo siguiente:'\n", "\n", "# print list.index(entry) + 1 usa la función .index() para encontrar\n", "# donde se encuentra la entrada de lista. la función print despliega este\n", "# añade 1 para hacer que los números sean más inteligibles.\n", "\n", "# print \") \" + imprime un corchete y el nombre de las entradas\n", "\n", "# después del ciclo for termina, eval(input(question) - 1) pregunta,\n", "# y regresa el valor al programa principal (menos 1, y regresa el\n", "# número que la computadora entenderá).\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "No ha sido muy díficl , verdad? El programa actual abarca cinco líneas - esto es una maravilla de lo mucho que hemos aprendido hasta el momento! Todos mis comentarios tienen 16 líneas - mayor de tres veces el tamaño del programa. Es una buena idea ampliar tus programas. Recuerda que si deseas publicar tu código abierto, habrá muchas personas revisando tu código que hayas escrito. Revisemos la función que acabamos de escribir en el primer programa de ejemplo." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6.4 Nuestro primer 'Game'\n", "¿Cuál será nuestro primer programa de ejemplo? ¿Qué tal un (muy) sencillo juego de aventura de texto? Suena divertido! Sólo abarcará un habitación de la casa, y será extremadamente simple. Habrá cinco cosas y una puerta. En una de esas cinco cosas, es una llave de la puerta. Requieres encontrar la llave, que abre la puerta. Primero una versión en inglés-plano, después en Python:
\n", "```\n", "#Versión plana de nuestro juego 'game'\n", "\n", "Informar a la computadora acerca de nuestro menú\n", "\n", "Imprime un mensaje de bienvenida, mostrando la descripción de una habitación\n", "\n", "Vamos a dar al jugador, seis cosas para que las mire: una maceta, un cuadro\\\n", "un jarrón, una lampara, un zapato y la puerta.\n", "\n", "Dile a la computadora que la puerta esta cerrada\n", "Dile a la computadora donde se encuentra la llave\n", "\n", "Presenta un menu, diciendo que cosas pueden 'operate':\n", " El menú te proporcionará seis opciones\n", " El menú te preguntará \"Qué deseas buscar?\n", " \n", "\n", "Si el usuario desea buscar:\n", " pot plant:\n", " Si la llave se encuentra aquí , proporciona al jugador la llave\n", " de forma indicarle que no esta aquí\n", " painting:\n", " Lo mismo de arriba\n", " etc.\n", " door:\n", " Si el jugador tiene la llave, permitelé abrir la puerta\n", " De otra forma, indiquenle que busque más\n", "\n", "Mencionen al jugador un mensaje de que lo hizo bien, para completar el juego.\n", "\n", "```\n", "
\n", "A partir de esto, podemos escribir un programa real. Listo? Aquí está:" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Last night you went to sleep in the comfort of your own home.\n", "Now, you find yourself locked in a room. You don't know how\n", "you got there, or what time it is. In the room you can see\n", "6 things:\n", "pot plant\n", "painting\n", "vase\n", "lampshade\n", "shoe\n", "door\n", "\n", "The door is locked. Could there be a key somewhere?\n", "1) pot plant\n", "2) painting\n", "3) vase\n", "4) lampshade\n", "5) shoe\n", "6) door\n", "You found nothing in the shoe.\n", "\n", "1) pot plant\n", "2) painting\n", "3) vase\n", "4) lampshade\n", "5) shoe\n", "6) door\n", "The door is locked, you need to find a key.\n", "\n", "1) pot plant\n", "2) painting\n", "3) vase\n", "4) lampshade\n", "5) shoe\n", "6) door\n" ] }, { "ename": "SyntaxError", "evalue": "unexpected EOF while parsing (, line 0)", "output_type": "error", "traceback": [ "Traceback \u001b[0;36m(most recent call last)\u001b[0m:\n", " File \u001b[1;32m\"/usr/lib/python3/dist-packages/IPython/core/interactiveshell.py\"\u001b[0m, line \u001b[1;32m3331\u001b[0m, in \u001b[1;35mrun_code\u001b[0m\n exec(code_obj, self.user_global_ns, self.user_ns)\n", " File \u001b[1;32m\"\"\u001b[0m, line \u001b[1;32m34\u001b[0m, in \u001b[1;35m\u001b[0m\n choice = menu(items,\"What do you want to inspect? \")\n", "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m9\u001b[0;36m, in \u001b[0;35mmenu\u001b[0;36m\u001b[0m\n\u001b[0;31m return eval(input(question)) - 1\u001b[0m\n", "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32munknown\u001b[0m\n\u001b[0;31m \u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m unexpected EOF while parsing\n" ] } ], "source": [ "# TEXT ADVENTURE GAME\n", "\n", "#the menu function:\n", "def menu(list, question):\n", " for entry in list:\n", " print(1 + list.index(entry),end=\"\")\n", " print (\") \" + entry)\n", "\n", " return eval(input(question)) - 1\n", "\n", "#Give the computer some basic information about the room:\n", "items = [\"pot plant\",\"painting\",\"vase\",\"lampshade\",\"shoe\",\"door\"]\n", "\n", "#The key is in the vase (or entry number 2 in the list above):\n", "keylocation = 2\n", "\n", "#You haven't found the key:\n", "keyfound = 0\n", "\n", "loop = 1\n", "\n", "#Give some introductary text:\n", "print(\"Last night you went to sleep in the comfort of your own home.\")\n", "\n", "print(\"Now, you find yourself locked in a room. You don't know how\")\n", "print(\"you got there, or what time it is. In the room you can see\")\n", "print(len(items), \"things:\")\n", "for x in items:\n", " print(x)\n", "print(\"\")\n", "print(\"The door is locked. Could there be a key somewhere?\")\n", "#Get your menu working, and the program running until you find the key:\n", "while loop == 1:\n", " choice = menu(items,\"What do you want to inspect? \")\n", " if choice == 0:\n", " if choice == keylocation:\n", " print(\"You found a small key in the pot plant.\")\n", "\n", " print(\"\")\n", " keyfound = 1\n", " else:\n", " print(\"You found nothing in the pot plant.\")\n", " print(\"\")\n", " elif choice == 1:\n", " if choice == keylocation:\n", " print(\"You found a small key behind the painting.\")\n", " print(\"\")\n", "\n", " keyfound = 1\n", " else:\n", " print(\"You found nothing behind the painting.\")\n", " print(\"\")\n", " elif choice == 2:\n", " if choice == keylocation:\n", " print(\"You found a small key in the vase.\")\n", " print(\"\")\n", " keyfound = 1\n", " else:\n", " print(\"You found nothing in the vase.\")\n", "\n", " print(\"\")\n", " elif choice == 3:\n", " if choice == keylocation:\n", " print(\"You found a small key in the lampshade.\")\n", " print(\"\")\n", " keyfound = 1\n", " else:\n", " print(\"You found nothing in the lampshade.\")\n", " print(\"\")\n", "\n", " elif choice == 4:\n", " if choice == keylocation:\n", " print(\"You found a small key in the shoe.\")\n", " print(\"\")\n", " keyfound = 1\n", " else:\n", " print(\"You found nothing in the shoe.\")\n", " print(\"\")\n", " elif choice == 5:\n", " if keyfound == 1:\n", " loop = 0\n", " print(\"You put in the key, turn it, and hear a click\")\n", "\n", " print(\"\")\n", " else:\n", " print(\"The door is locked, you need to find a key.\")\n", " print(\"\")\n", "\n", "# Remember that a backslash continues\n", "# the code on the next line\n", "print(\"Light floods into the room as \\\n", "you open the door to your freedom.\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Bueno, un juego simple, pero divertido. No te asustes por la cantidad de códgio, 53 de las líneas son sólo sentencias condicionales `if`, que es lo más fácil de leer (Una vez que hayas comprendido toda la sangría o indentación. Pronto, realizarás tu propio juego, y puedes hacerlo más simple (o más compleja) como gustes. Lo publicaré un poco después." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6.5 Realizando un juego mejor\n", "La primera pregunta que debería hacerse es \"¿Este programa funciona?\". La respuesta es sí. Luego la siguiente pregunta es \"¿Este programa trabaja bien?\" - no del todo. La función del `menu()` es genial - reduce un poco del tecleo. El ciclo `while` que tenemos, sin embargo es un poco más desordenado - cuatro niveles de indentación, para un programa simple. Podemos hacerlo mejor!\n", "\n", "Ahora, será más sencillo cuando introduzcamos las clases. Pero eso tendrá que esperar. Hagamos una función que reduzca nuestro desorden. Le pasaremos dos cosas - el menú de las opciones, y la ubicación de las llaves. Y devolverá una cosa, si la llave ha sido encontrada o no, veasmoslo:\n", "\n", "```Python\n", "def inspect(choice,location):\n", " if choice == location:\n", " print(\"\")\n", " print(\"You found a key!\")\n", " print(\"\")\n", " return 1\n", " else:\n", " print(\"\")\n", " print(\"Nothing of interest here.\")\n", " print(\"\")\n", " return 0\n", "```\n", "\n", "\n", "Now the main program can be a little simpler.\n", "\n", "In the field below:\n", "\n", "1. Insert the `inspect` function\n", "2. Replace the `while` loop with:\n", "\n", "```Python\n", "while loop == 1:\n", " keyfound = inspect(menu(items,\"What do you want to inspect? \"),keylocation)\n", " if keyfound == 1:\n", " print(\"You put the key in the lock of the door, and turn it. It opens!\")\n", " loop = 0\n", "```" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Last night you went to sleep in the comfort of your own home.\n", "Now, you find yourself locked in a room. You don't know how\n", "you got there, or what time it is. In the room you can see\n", "6 things:\n", "pot plant\n", "painting\n", "vase\n", "lampshade\n", "shoe\n", "door\n", "\n", "The door is locked. Could there be a key somewhere?\n", "1) pot plant\n", "2) painting\n", "3) vase\n", "4) lampshade\n", "5) shoe\n", "6) door\n", "You found nothing in the shoe.\n", "\n", "1) pot plant\n", "2) painting\n", "3) vase\n", "4) lampshade\n", "5) shoe\n", "6) door\n", "You found nothing behind the painting.\n", "\n", "1) pot plant\n", "2) painting\n", "3) vase\n", "4) lampshade\n", "5) shoe\n", "6) door\n" ] }, { "ename": "NameError", "evalue": "name 'vase' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 32\u001b[0m \u001b[0;31m#Get your menu working, and the program running until you find the key:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 33\u001b[0m \u001b[0;32mwhile\u001b[0m \u001b[0mloop\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 34\u001b[0;31m \u001b[0mchoice\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mmenu\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mitems\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\"What do you want to inspect? \"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 35\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mchoice\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 36\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mchoice\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0mkeylocation\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;32m\u001b[0m in \u001b[0;36mmenu\u001b[0;34m(list, question)\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0mprint\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;34m\") \"\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mentry\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 9\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0meval\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mquestion\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 10\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0;31m#Give the computer some basic information about the room:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n", "\u001b[0;31mNameError\u001b[0m: name 'vase' is not defined" ] } ], "source": [ "# TEXT ADVENTURE GAME\n", "\n", "#the menu function:\n", "def menu(list, question):\n", " for entry in list:\n", " print(1 + list.index(entry),end=\"\")\n", " print (\") \" + entry)\n", "\n", " return eval(input(question)) - 1\n", "\n", "#Give the computer some basic information about the room:\n", "items = [\"pot plant\",\"painting\",\"vase\",\"lampshade\",\"shoe\",\"door\"]\n", "\n", "#The key is in the vase (or entry number 2 in the list above):\n", "keylocation = 2\n", "\n", "#You haven't found the key:\n", "keyfound = 0\n", "\n", "loop = 1\n", "\n", "#Give some introductary text:\n", "print(\"Last night you went to sleep in the comfort of your own home.\")\n", "\n", "print(\"Now, you find yourself locked in a room. You don't know how\")\n", "print(\"you got there, or what time it is. In the room you can see\")\n", "print(len(items), \"things:\")\n", "for x in items:\n", " print(x)\n", "print(\"\")\n", "print(\"The door is locked. Could there be a key somewhere?\")\n", "#Get your menu working, and the program running until you find the key:\n", "while loop == 1:\n", " choice = menu(items,\"What do you want to inspect? \")\n", " if choice == 0:\n", " if choice == keylocation:\n", " print(\"You found a small key in the pot plant.\")\n", "\n", " print(\"\")\n", " keyfound = 1\n", " else:\n", " print(\"You found nothing in the pot plant.\")\n", " print(\"\")\n", " elif choice == 1:\n", " if choice == keylocation:\n", " print(\"You found a small key behind the painting.\")\n", " print(\"\")\n", "\n", " keyfound = 1\n", " else:\n", " print(\"You found nothing behind the painting.\")\n", " print(\"\")\n", " elif choice == 2:\n", " if choice == keylocation:\n", " print(\"You found a small key in the vase.\")\n", " print(\"\")\n", " keyfound = 1\n", " else:\n", " print(\"You found nothing in the vase.\")\n", "\n", " print(\"\")\n", " elif choice == 3:\n", " if choice == keylocation:\n", " print(\"You found a small key in the lampshade.\")\n", " print(\"\")\n", " keyfound = 1\n", " else:\n", " print(\"You found nothing in the lampshade.\")\n", " print(\"\")\n", "\n", " elif choice == 4:\n", " if choice == keylocation:\n", " print(\"You found a small key in the shoe.\")\n", " print(\"\")\n", " keyfound = 1\n", " else:\n", " print(\"You found nothing in the shoe.\")\n", " print(\"\")\n", " elif choice == 5:\n", " if keyfound == 1:\n", " loop = 0\n", " print(\"You put in the key, turn it, and hear a click\")\n", "\n", " print(\"\")\n", " else:\n", " print(\"The door is locked, you need to find a key.\")\n", " print(\"\")\n", "\n", "# Remember that a backslash continues\n", "# the code on the next line\n", "print(\"Light floods into the room as \\\n", "you open the door to your freedom.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Ahora el programa se reduce masivamente - de 83 líneas engorrosas- a unas muy bien formadas 50 líneas! Por supuesto, se pierde bastante versatilidad: todos los elementos de la habitación hacen lo mismo. La puerta se abre automáticamente cuando encuentra la llave. El juego se vuelve un poco menos interesante. Y se vuelve más díficil de cambiar." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6.6 Conclusiones\n", "Ahora dije que escribirías unos programas. Esta es tu oportunidad! Tu tarea, si aceptas esta, es postear un mejor juego de aventuras con texto, puedes utilizar cualquier sección de código que he utilizado aquí. Recuerda repasar las lecciones previas - son herramientas invaluables. Haz una búsqueda para algunos textos simples de juegos de aventuras - si encuentras alguno juegos de aventura divertidos y agradables, échales un vistazo." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "< [Tuplas, Listas y Dictionarios](PythonIntroCh5.ipynb) | [Contenido](PythonIntro.ipynb) | [Clases](PythonIntroCh7.ipynb) >" ] }, { "cell_type": "markdown", "metadata": {}, "source": [] } ], "metadata": { "interpreter": { "hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6" }, "kernelspec": { "display_name": "Python 3.8.10 64-bit", "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.10" } }, "nbformat": 4, "nbformat_minor": 2 }