diff --git a/README.es.md b/README.es.md index 3172b5e7..3aab995b 100644 --- a/README.es.md +++ b/README.es.md @@ -1,77 +1,194 @@ -# 🐍 Tutorial y Ejercicios para Principiantes de Python +
-Por @alesanchezr y otros colaboradores en 4Geeks Academy +# Aprende Python Interactivamente (Principiante) + +![Portada del curso con el texto "Learn Python Beginner interactive" junto al logo azul y amarillo de Python](https://raw.githubusercontent.com/4GeeksAcademy/python-beginner-programming-exercises/HEAD/.learn/assets/preview.png) + +[![Tutorial interactivo](https://img.shields.io/badge/4Geeks_Academy-Tutorial_interactivo-2563eb?style=flat-square)](https://4geeks.com/es/interactive-exercise/python-beginner-programming-exercises) +[![Autocorregido con LearnPack](https://img.shields.io/badge/LearnPack-21_ejercicios_autocorregidos-2563eb?style=flat-square)](https://learnpack.co) +[![Abrir en GitHub Codespaces](https://img.shields.io/badge/Abrir_en-GitHub_Codespaces-fb5a1f?style=flat-square&logo=github&logoColor=white)](https://codespaces.new/?repo=4GeeksAcademy/python-beginner-programming-exercises) + +
-Esta serie en particular es para principiantes de Python. Aprenderás los siguientes conceptos: +Aprende Python Interactivamente es un curso para principiantes con 21 retos autocorregidos que se resuelven dentro del editor de código. Empiezas imprimiendo `Hello World!` y terminas escribiendo FizzBuzz, una función de ruleta rusa y la canción completa de las 99 botellas. Dura unas 10 horas, no exige experiencia previa programando y 19 de los ejercicios traen un vídeo explicativo paso a paso. -1. La función `print`. + +## 📋 Sobre este tutorial + +- **Dificultad**: fácil (`difficulty: "easy"` en `learn.json`) +- **Duración**: unas 10 horas +- **Ejercicios**: 22 carpetas — 1 página de bienvenida y 21 retos de código +- **Tecnologías**: Python 3, variables, cadenas, condicionales, funciones, bucles +- **Corrección**: automática, 21 ficheros `test.py` que se ejecutan con pytest +- **Vídeos**: 19 explicaciones de ejercicio más 1 vídeo de introducción +- **Idiomas**: [English](https://github.com/4GeeksAcademy/python-beginner-programming-exercises/blob/HEAD/README.md) · [Español](https://github.com/4GeeksAcademy/python-beginner-programming-exercises/blob/HEAD/README.es.md) + -2. Tipos de datos. +## 🎯 ¿Qué vas a aprender? -3. Listas y tuplas. +Los 21 retos presentan una idea cada vez, y ninguna idea se queda suelta: todas vuelven a aparecer en un ejercicio posterior. -4. Funciones y diccionarios. +- **La consola**: `print()` como la vía por la que un programa te responde y como tu principal herramienta para depurar. +- **Variables**: declararlas, asignarles cadenas y números, e imprimir varias en una sola llamada a `print()` separándolas con comas. +- **Aritmética**: multiplicar con `*` y guardar el resultado en una variable. +- **Entrada del usuario**: leer un valor con `input()` y trabajar con una variable cuyo contenido no conoces de antemano. +- **Concatenación de cadenas**: unir textos con el operador `+`, hasta construir un documento HTML entero a partir de 8 variables sueltas. +- **Condicionales**: cadenas de `if...else`, operadores relacionales (`>`, `<`, `==`, `!=`, `>=`, `<=`) y tramos de precios con varias ramas. +- **El módulo `random`**: `randint(min, max)` y `randrange(inicio, fin)`, y la diferencia entre un límite superior inclusivo y uno exclusivo. +- **Funciones**: llamar a una función escrita por otra persona, definir la tuya, pasar parámetros y distinguir `return` de `print`. +- **Bucles**: `for` con `range()`, repetir una acción cientos de veces y combinar bucles con condicionales. +- **Listas**: construir una lista elemento a elemento dentro de un bucle. -Todo el tutorial es 👆 interactivo, ✅ calificado automáticamente, y con 📹 video tutoriales. +## 👀 ¿Qué vas a construir? +Cada ejercicio es un programa de Python real y ejecutable. Estos son los 21 retos evaluados, en orden: -¡Te necesitamos! Estos ejercicios se crean y mantienen con colaboradores como tú. Si encuentras algún error o falta de ortografía, contribuye y/o infórmanos. +- **`01` Console** — imprimir `Hello World!` en la terminal. +- **`02` Declare Variables** — declarar una variable con el valor `"Yellow"` e imprimirla. +- **`03` Print more Variables** — declarar `color = "red"` e `item = "marker"` e imprimir ambas en una sola llamada. +- **`04` Multiply Two Values** — guardar `2345 * 7323` en una variable e imprimir el resultado. +- **`05` User Inputed Values** — pedir la edad al usuario e imprimirla sumándole 10 años. +- **`06` String Concatenation** — dar valor a dos variables para que `my_var1 + my_var2` imprima `Hello World`. +- **`07` Create a Basic HTML** — concatenar 8 variables dadas hasta formar ``. +- **`08.1` Your First If** — responder distinto según si el usuario tiene más de $100, más de $50 o $50 o menos. +- **`08.2` How Much The Wedding Costs** — calcular el precio de un catering de boda en cuatro tramos de invitados, desde $4.000 para un máximo de 50 hasta $20.000 para más de 200. +- **`09` Random Numbers** — devolver un número entero aleatorio entre 1 y 10 en lugar de un decimal. +- **`10` Calling Your First Function** — llamar a la función `is_odd` que ya viene escrita pasándole `45345` e imprimir lo que devuelve. +- **`10.1` Creating Your First Function** — rellenar el cuerpo de `add_numbers(a, b)` para que el programa imprima `7`. +- **`11` Create A New Function** — escribir `generate_random()`, que devuelve un número aleatorio entre 0 y 9. +- **`12` Rand From One to Twelve** — usar `randrange()` para generar enteros del 1 al 12, ambos incluidos. +- **`13` Your First Loop** — coger un bucle que cuenta hasta 9 y hacer que cuente hasta 11. +- **`14` Create A For Loop** — imprimir "I will ask questions if I am stuck" exactamente 300 veces. +- **`15` Looping With FizzBuzz** — el clásico de las entrevistas: imprimir del 1 al 100 con `Fizz`, `Buzz` y `FizzBuzz`. +- **`16` Random Colors (Loop)** — asignar a cada uno de 10 alumnos un color aleatorio de entre cuatro y devolver la lista resultante. +- **`17` Russian Roulette** — completar `fire_gun` para que compare la posición de la bala con la del tambor de un revólver de 6 recámaras. +- **`18` The Beatles** — escribir `sing()` para que imprima línea a línea el estribillo final de "Let It Be". +- **`19` Bottles Of Milk** — escribir `number_of_bottles()`, que imprime las 100 estrofas de la canción de las 99 botellas, singular incluido. - +El ejercicio `00` es una página de bienvenida sin código: enumera los conceptos que vienen y enlaza a lecturas introductorias. -## Instalación en un clic (recomendado) +## 🎓 ¿Qué necesitas antes de empezar? -Puedes empezar estos ejercicios en pocos segundos haciendo clic en: [Abrir en Codespaces](https://codespaces.new/?repo=4GeeksAcademy/python-beginner-programming-exercises) (recomendado) o [Abrir en Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/python-beginner-programming-exercises). +- **Experiencia programando**: ninguna. El primer reto es una sola llamada a `print()`, y el tutorial explica qué es una consola antes de pedirte que la uses. +- **Conocimientos de Python**: ninguno. Cada función que se usa (`print`, `input`, `int`, `str`, `range`, `randint`, `randrange`) se presenta en el ejercicio que la necesita. +- **Software, opción en la nube**: basta una cuenta de GitHub. Codespaces monta el entorno a partir del `.devcontainer` del repositorio, que instala por ti Python 3.10, Node 22, LearnPack y pytest. +- **Software, opción local**: Python 3 y Node.js 14 o superior, además de los paquetes `pytest`, `pytest-testdox` y `mock`. +- **Tiempo**: unas 10 horas en total, es decir, alrededor de 30 minutos por reto si ves los vídeos. +- **Idioma**: cada ejercicio incluye `README.md` en inglés y `README.es.md` en español. -> Una vez ya tengas abierto VSCode, los ejercicios de LearnPack deberían empezar automáticamente, si esto no sucede puedes intentar empezar los ejercicios escribiendo este comando en tu terminal: `$ learnpack start` +## ✅ ¿Cómo funciona la corrección automática? -## Instalación local: +La corrección es real, no decorativa: 21 de las 22 carpetas de ejercicio contienen un fichero `test.py`, y se ejecutan con pytest. -1. Asegúrate de instalar [LearnPack](https://learnpack.co), node.js version 14+ y Python version 3+. Este es el comando para instalar LearnPack: +- **Escribes tu respuesta en `app.py`**, el único fichero que debes tocar. Marcas como `# ✅↓ Write your code here ↓✅` y `# ❌ ↓ DON'T CHANGE THE CODE BELOW ↓ ❌` te señalan la zona editable. +- **Pulsas Run** para ejecutar el programa y ver su salida, y el botón de feedback para lanzar los tests. +- **Cada test lleva una etiqueta legible** escrita con `@pytest.mark.it(...)`, así que un fallo se lee como "The function `fizz_buzz` should exist" o "Your function needs to print the correct output" en vez de como una traza de error. +- **Se usan dos tipos de comprobación**: las de salida, que capturan lo que imprime tu programa y lo comparan con el texto esperado, y las de código fuente, que con expresiones regulares verifican que de verdad usaste la técnica que se enseña, por ejemplo que aparezca la palabra `for` en tu solución de FizzBuzz. +- **Junto a cada ejercicio evaluado hay un `solution.hide.py`**, así que siempre tienes una solución resuelta disponible cuando ya lo hayas intentado por tu cuenta. -```bash -$ npm i @learnpack/learnpack@2.1.20 -g && learnpack plugins:install @learnpack/python@1.0.0 -``` +![Captura del panel de instrucciones de LearnPack dentro de VS Code mostrando el ejercicio 01 Console, con una flecha roja señalando el botón Run junto a los botones Get feedback y Reset](https://raw.githubusercontent.com/4GeeksAcademy/python-beginner-programming-exercises/HEAD/.learn/assets/run-exercise.png) -2. Clona o descarga este repositorio en tu ambiente local. +## 💡 ¿Qué errores conviene evitar? -```bash -$ git clone https://github.com/4GeeksAcademy/python-beginner-programming-exercises.git -$ cd python-beginner-programming-exercises -``` +Casi todos los tests que fallan en este tutorial se explican por un puñado de causas: + +- **Llegar al resultado correcto por el camino equivocado.** El ejercicio `12` solo acepta `random.randrange(1, 13)`; `randint(1, 12)` imprime exactamente los mismos números y aun así falla. El `15` exige que aparezca la palabra `for` en tu fichero, así que un `while` que imprime un FizzBuzz impecable queda rechazado. +- **Confundir `return` con `print`.** El ejercicio `19` pide explícitamente imprimir la letra, mientras que el `17` espera que `fire_gun` devuelva las cadenas `You are dead!` y `Keep playing!`. Intercambiarlos rompe el test aunque en pantalla parezca que todo funciona. +- **Equivocarte en el texto exacto.** Las comparaciones incluyen mayúsculas, puntuación y espacios: `"Yellow"` no es `"yellow"`, y la última estrofa de la canción cambia a "no more bottles" y "Go to the store and buy some more". +- **Olvidar el singular.** La canción de las botellas pasa de "bottles" a "bottle" al llegar a 1, y esa es la razón más habitual de que falle su último test. +- **Errores de uno en los rangos.** `randint(a, b)` incluye ambos extremos, `randrange(a, b)` excluye el último, y el bucle del ejercicio `13` tiene que llegar a 11, no quedarse en 10. +- **No llamar a tu propia función.** Varios tests comprueban que la función esté definida y además invocada; por ejemplo, que `print(get_randomInt())` aparezca de verdad en `app.py`. + +## ❓ Preguntas frecuentes + +### ¿Cuánto se tarda en aprender lo básico de Python con estos ejercicios? + +El paquete está estimado en 10 horas repartidas entre 21 retos. La mayoría son unas pocas líneas de código; los que más cuestan son FizzBuzz, la lista de colores aleatorios y la canción de las 99 botellas, porque su salida esperada se compara carácter a carácter. + +### ¿Hace falta saber programar antes de empezar? + +No. El tutorial está marcado con dificultad `easy` y arranca imprimiendo una sola línea de texto. Los conceptos llegan en orden — consola, variables, entrada, condicionales, aleatoriedad, funciones, bucles, listas — y cada uno se reutiliza en un ejercicio posterior. + +### ¿Tengo que instalar Python en mi ordenador? + +No si usas Codespaces: el `.devcontainer` de este repositorio provisiona automáticamente Python 3.10, Node 22, LearnPack y pytest, y los ejercicios se abren en el navegador. La instalación local también está soportada y necesita Python 3, Node.js 14 o superior y los paquetes `pytest`, `pytest-testdox` y `mock`. + +### Mi código funciona pero el test falla igual. ¿Es normal? -> Nota: Una vez que termine de descargar, encontrarás la carpeta "exercises" que contiene todos los ejercicios. +Sí, y conviene entender por qué. Algunos tests inspeccionan tu código fuente con expresiones regulares para verificar que usaste la construcción concreta que se está enseñando, así que una respuesta correcta escrita de otra manera puede ser rechazada. Los propios autores describen la corrección como rígida y recomiendan tomarla como sugerencia, no como veredicto. Ante la duda, compara tu fichero con el `solution.hide.py` que hay junto al ejercicio. -3. Inicializa el tutorial ejecutando el siguiente comando al mismo nivel en el que se encuentra tu archivo learn.json: +### ¿Es gratis y puedo reutilizar el código? + +Acceder no cuesta nada y el código que escribes es tuyo. El contenido, en cambio, no es open source: la [LICENSE](https://github.com/4GeeksAcademy/python-beginner-programming-exercises/blob/HEAD/LICENSE.md) reserva todos los derechos de propiedad intelectual y prohíbe republicar, vender, reproducir o redistribuir el material. Puedes usarlo para aprender y estudiar por tu cuenta, que es justo para lo que lo publica 4Geeks Academy. + +### ¿Qué hago cuando termine? + +Sigue por los paquetes a los que apunta el propio tutorial: una serie dedicada a [listas y bucles](https://4geeks.com/es/interactive-exercise/python-lists-loops-programming-exercises) y más de 20 [ejercicios de funciones](https://4geeks.com/es/interactive-exercise/python-functions-programming-exercises) con dificultad creciente. Los ejercicios `10.1`, `13` y `15` enlazan a ellos directamente. + + +## 📚 Tutoriales relacionados + +- [Ejercicios de listas y bucles en Python](https://4geeks.com/es/interactive-exercise/python-lists-loops-programming-exercises) — el paso natural después del ejercicio `13`. +- [Ejercicios de funciones en Python](https://4geeks.com/es/interactive-exercise/python-functions-programming-exercises) — más de 20 retos, referenciados desde los ejercicios `10` y `10.1`. +- [Vídeo de introducción del curso](https://www.youtube.com/watch?v=IXNSwnN-YqM) — el que enlaza `learn.json` para español. + +## 🚀 Cómo empezar + +Instalación en un clic, la opción recomendada: + +[Abrir en GitHub Codespaces](https://codespaces.new/?repo=4GeeksAcademy/python-beginner-programming-exercises) + +Cuando se abra VS Code, los ejercicios de LearnPack deberían arrancar solos. Si no lo hacen, escribe esto en la terminal: ```bash -$ pip3 install pytest==6.2.5 pytest-testdox mock $ learnpack start ``` - +> 💡 También puedes seguir el mismo tutorial en la web, en [4geeks.com](https://4geeks.com/es/interactive-exercise/python-beginner-programming-exercises). +## 💻 Instalación local -## ¿Cómo están organizados los ejercicios? +1. Instala [LearnPack](https://learnpack.co), Node.js 14+ y Python 3+: -Cada ejercicio es una pequeña aplicación de Python que contiene los siguientes archivos: + ```bash + $ npm i @learnpack/learnpack -g && learnpack plugins:install @learnpack/python + ``` -1. **app.py:** representa el archivo de entrada de Python que será ejecutado por el computador. -2. **README.es.md:** Contiene las instrucciones del ejercicio. -3. **test.py:** Contiene el script del test para el ejercicio (no es necesario que abras este archivo). +2. Clona el repositorio y entra en la carpeta: -> Nota: Estos ejercicios tienen calificación automática. Los tests son muy rígidos y estrictos, mi recomendación es que no prestes demasiada atención a los tests y los uses solo como una sugerencia o podrías frustrarte. + ```bash + $ git clone https://github.com/4GeeksAcademy/python-beginner-programming-exercises.git + $ cd python-beginner-programming-exercises + ``` -## Colaboradores - -Gracias a estas personas maravillosas ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): +3. Instala las dependencias de test y arranca, desde el mismo nivel en el que está `learn.json`: + + ```bash + $ pip3 install pytest==6.2.5 pytest-testdox mock + $ learnpack start + ``` -1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribución: (programador) 💻 (idea) 🤔, (build-tests) ⚠️, (pull-request-review) 👀, (build-tutorial) ✅, (documentación) 📖 +## 📚 Cómo están organizados los ejercicios -2. [Paolo (plucodev)](https://github.com/plucodev), contribución: (bug reports) 🐛, (programador) 💻, (traducción) 🌎 +Cada ejercicio vive en su propia carpeta dentro de [`exercises/`](https://github.com/4GeeksAcademy/python-beginner-programming-exercises/tree/HEAD/exercises). Los 21 evaluados contienen: -Este proyecto sigue la especificación [all-contributors](https://github.com/kentcdodds/all-contributors). ¡Todas las contribuciones son bienvenidas! +- **`app.py`** — el fichero de entrada que editas y ejecutas. +- **`README.md`** — las instrucciones en inglés. +- **`README.es.md`** — las instrucciones en español. +- **`test.py`** — el script de corrección; no necesitas abrirlo. +- **`solution.hide.py`** — una solución resuelta, que LearnPack mantiene oculta hasta que la pides. -Este y otros ejercicios son usados para [aprender a programar](https://4geeksacademy.com/es/aprender-a-programar/aprender-a-programar-desde-cero) por parte de los alumnos de 4Geeks Academy [Coding Bootcamp](https://4geeksacademy.com/us/coding-bootcamp) realizado por [Alejandro Sánchez](https://twitter.com/alesanchezr) y muchos otros contribuyentes. Conoce más sobre nuestros [Cursos de Programación](https://4geeksacademy.com/es/curso-de-programacion-desde-cero?lang=es) para convertirte en [Full Stack Developer](https://4geeksacademy.com/es/coding-bootcamps/desarrollador-full-stack/?lang=es), o nuestro [Data Science Bootcamp](https://4geeksacademy.com/es/coding-bootcamps/curso-datascience-machine-learning). +## 🤝 Colaboradores + +Gracias a estas personas maravillosas ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): + +1. [Alejandro Sánchez (alesanchezr)](https://github.com/alesanchezr) — (programador) 💻, (idea) 🤔, (build-tests) ⚠️, (pull-request-review) 👀, (build-tutorial) ✅, (documentación) 📖 +2. [Paolo Lucano (plucodev)](https://github.com/plucodev) — (reporte de bugs) 🐛, (programador) 💻, (traducción) 🌎 +3. [Marco Gómez (marcogonzalo)](https://github.com/marcogonzalo) — (traducción) 🌎 + +Este proyecto sigue la especificación [all-contributors](https://github.com/kentcdodds/all-contributors). Toda contribución es bienvenida — consulta la [lista completa de colaboradores](https://github.com/4GeeksAcademy/python-beginner-programming-exercises/graphs/contributors). + +Este y muchos otros ejercicios los construyen los alumnos del [Coding Bootcamp de 4Geeks Academy](https://4geeks.com/es/inicio). Conoce más sobre el [programa de Desarrollo Full Stack](https://4geeks.com/es/programas-de-carrera/desarrollo-full-stack) y el [programa de Ciencia de Datos y Machine Learning](https://4geeks.com/es/programas-de-carrera/ciencia-de-datos-ml). + diff --git a/README.md b/README.md index ffbcfff7..207265b1 100644 --- a/README.md +++ b/README.md @@ -1,83 +1,194 @@ - +
+# Learn Python Interactively (beginner) -# 🐍 Python Beginner Tutorial and Exercises -By [@alesanchezr](https://twitter.com/alesanchezr) and [other contributors](https://github.com/4GeeksAcademy/python-beginner-programming-exercises/graphs/contributors) at [4Geeks Academy](http://4geeksacademy.com) - +![Course cover art reading "Learn Python Beginner interactive" next to the blue and yellow Python logo](https://raw.githubusercontent.com/4GeeksAcademy/python-beginner-programming-exercises/HEAD/.learn/assets/preview.png) +[![Interactive tutorial](https://img.shields.io/badge/4Geeks_Academy-Interactive_tutorial-2563eb?style=flat-square)](https://4geeks.com/en/interactive-exercise/python-beginner-programming-exercises) +[![Auto-graded with LearnPack](https://img.shields.io/badge/LearnPack-21_auto--graded_exercises-2563eb?style=flat-square)](https://learnpack.co) +[![Open in GitHub Codespaces](https://img.shields.io/badge/Open_in-GitHub_Codespaces-fb5a1f?style=flat-square&logo=github&logoColor=white)](https://codespaces.new/?repo=4GeeksAcademy/python-beginner-programming-exercises) -*Estas instrucciones [están disponibles en 🇪🇸 español](https://github.com/4GeeksAcademy/python-beginner-programming-exercises/blob/master/README.es.md) :es:* +
-These exercises are the ideal first step for anyone trying to learn Python. We start with the most simple challenge, like printing a message on the terminal and slowly increase step by step. +Learn Python Interactively is a beginner course of 21 auto-graded coding challenges that run inside your code editor. You start by printing `Hello World!` and finish by writing FizzBuzz, a Russian-roulette function and the full 99-bottles-of-milk song. It takes roughly 10 hours, requires no prior programming experience, and 19 of the exercises include a step-by-step video walkthrough. -This particular series is for Python beginners. You will learn: + +## 📋 About this tutorial + +- **Difficulty**: easy (`difficulty: "easy"` in `learn.json`) +- **Duration**: about 10 hours +- **Exercises**: 22 folders — 1 welcome page plus 21 coding challenges +- **Technologies**: Python 3, variables, strings, conditionals, functions, loops +- **Grading**: automatic, 21 `test.py` files executed with pytest +- **Videos**: 19 exercise walkthroughs plus 1 intro video +- **Languages**: [English](https://github.com/4GeeksAcademy/python-beginner-programming-exercises/blob/HEAD/README.md) · [Español](https://github.com/4GeeksAcademy/python-beginner-programming-exercises/blob/HEAD/README.es.md) + -1. The `print` function. +## 🎯 What will you learn? -2. Data-Types. +The 21 challenges introduce one idea at a time, and every idea is used again in a later exercise: -3. Lists and Tuples. +- **The console**: `print()` as the way a program talks back to you, and as your main debugging tool. +- **Variables**: declaring them, assigning strings and numbers, and printing several of them in a single `print()` call separated by commas. +- **Arithmetic**: multiplication with `*` and storing a result in a variable. +- **User input**: reading a value with `input()` and working with a variable whose value you don't know in advance. +- **String concatenation**: joining strings with the `+` operator, up to building a full HTML document out of 8 separate variables. +- **Conditionals**: `if...else` chains, relational operators (`>`, `<`, `==`, `!=`, `>=`, `<=`) and multi-branch price brackets. +- **The `random` module**: `randint(min, max)` and `randrange(start, stop)`, and the difference between an inclusive and an exclusive upper bound. +- **Functions**: calling a function someone else wrote, defining your own, passing parameters, and the difference between `return` and `print`. +- **Loops**: `for` with `range()`, repeating an action hundreds of times, and combining loops with conditionals. +- **Lists**: building a list item by item inside a loop. -4. Functions and dictionaries. +## 👀 What will you build? -The entire tutorial is 👆 interactive, ✅ auto-graded, and has 📹 video tutorials. +Each exercise is a real, runnable Python program. These are the 21 graded challenges, in order: -These exercises were built in collaboration, we need you! If you find any bugs or misspellings please contribute and report them. +- **`01` Console** — print `Hello World!` on the terminal. +- **`02` Declare Variables** — declare a variable with the value `"Yellow"` and print it. +- **`03` Print more Variables** — declare `color = "red"` and `item = "marker"` and print both in one call. +- **`04` Multiply Two Values** — store `2345 * 7323` in a variable and print the result. +- **`05` User Inputed Values** — ask the user for their age and print it plus 10 years. +- **`06` String Concatenation** — set two variables so that `my_var1 + my_var2` prints `Hello World`. +- **`07` Create a Basic HTML** — concatenate 8 given variables into ``. +- **`08.1` Your First If** — answer differently depending on whether the user has more than $100, more than $50, or $50 or less. +- **`08.2` How Much The Wedding Costs** — price a wedding catering job across four guest brackets, from $4,000 for up to 50 guests to $20,000 for more than 200. +- **`09` Random Numbers** — return a random whole number between 1 and 10 instead of a decimal. +- **`10` Calling Your First Function** — call the given `is_odd` function with `45345` and print what it returns. +- **`10.1` Creating Your First Function** — fill in the body of `add_numbers(a, b)` so the program prints `7`. +- **`11` Create A New Function** — write `generate_random()`, returning a random number between 0 and 9. +- **`12` Rand From One to Twelve** — use `randrange()` to produce integers from 1 to 12 inclusive. +- **`13` Your First Loop** — take a loop that counts to 9 and make it count to 11. +- **`14` Create A For Loop** — print "I will ask questions if I am stuck" exactly 300 times. +- **`15` Looping With FizzBuzz** — the classic interview exercise, printing 1 to 100 with `Fizz`, `Buzz` and `FizzBuzz`. +- **`16` Random Colors (Loop)** — assign one random color out of four to each of 10 students and return the resulting list. +- **`17` Russian Roulette** — complete `fire_gun` so it compares the bullet slot against the chamber position of a 6-slot revolver. +- **`18` The Beatles** — write `sing()` so it prints the closing chorus of "Let It Be" line by line. +- **`19` Bottles Of Milk** — write `number_of_bottles()`, printing all 100 verses of the 99-bottles song, singular included. - +Exercise `00` is a welcome page with no code: it lists the concepts ahead and links to introductory reading. -## One click installation (recommended): +## 🎓 What do you need before starting? -You can open these exercises in just a few seconds by clicking: [Open in Codespaces](https://codespaces.new/?repo=4GeeksAcademy/python-beginner-programming-exercises) (recommended) or [Open in Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/python-beginner-programming-exercises). +- **Prior programming experience**: none. The first challenge is a single `print()` call, and the tutorial explains what a console is before asking you to use one. +- **Python knowledge**: none. Every function used (`print`, `input`, `int`, `str`, `range`, `randint`, `randrange`) is introduced in the exercise that needs it. +- **Software, cloud option**: a GitHub account is enough. Codespaces builds the environment from the repository's `.devcontainer`, which installs Python 3.10, Node 22, LearnPack and pytest for you. +- **Software, local option**: Python 3 and Node.js 14 or newer, plus `pytest`, `pytest-testdox` and `mock`. +- **Time**: about 10 hours in total, so roughly 30 minutes per challenge if you watch the videos. +- **Language**: every exercise ships with `README.md` in English and `README.es.md` in Spanish. -> Once you have VSCode open, the LearnPack exercises should start automatically. If exercises don't run automatically, you can try typing on your terminal: `$ learnpack start` +## ✅ How does the automatic grading work? -## Local Installation +Grading is real, not decorative: 21 of the 22 exercise folders contain a `test.py` file, and they run with pytest. -1. Make sure you have [LearnPack](https://learnpack.co) installed, node.js version 14+, and Python version 3+. This is the command to install LearnPack: +- **You write your answer in `app.py`**, the only file you are meant to edit. Comment markers such as `# ✅↓ Write your code here ↓✅` and `# ❌ ↓ DON'T CHANGE THE CODE BELOW ↓ ❌` show you the editable region. +- **You press Run** to execute the program and see its output, and the feedback button to run the tests. +- **Each test has a human-readable label** written with `@pytest.mark.it(...)`, so a failure reads like "The function `fizz_buzz` should exist" or "Your function needs to print the correct output" instead of a raw traceback. +- **Two kinds of checks are used**: output checks that capture what your program prints and compare it to the expected text, and source checks that use regular expressions to confirm you actually used the technique being taught, for example that a `for` keyword appears in your FizzBuzz solution. +- **A `solution.hide.py` file sits next to every graded exercise**, so a worked answer is always available once you have tried it yourself. -```bash -$ npm i @learnpack/learnpack@2.1.20 -g && learnpack plugins:install @learnpack/python@1.0.0 -``` +![Screenshot of the LearnPack instructions panel inside VS Code showing exercise 01 Console, with a red arrow pointing at the Run button next to the Get feedback and Reset buttons](https://raw.githubusercontent.com/4GeeksAcademy/python-beginner-programming-exercises/HEAD/.learn/assets/run-exercise.png) -2. Clone or download this repository in your local environment. +## 💡 What mistakes should you avoid? -```bash -$ git clone https://github.com/4GeeksAcademy/python-beginner-programming-exercises.git -$ cd python-beginner-programming-exercises -``` +Most failed tests in this tutorial come from the same handful of causes: + +- **Producing the right output the wrong way.** Exercise `12` accepts only `random.randrange(1, 13)`; `randint(1, 12)` prints identical numbers and still fails. Exercise `15` requires a `for` keyword in your file, so a `while` loop that prints perfect FizzBuzz output is rejected. +- **Confusing `return` with `print`.** Exercise `19` says explicitly to print the lyrics, while exercise `17` expects `fire_gun` to return the strings `You are dead!` and `Keep playing!`. Swapping the two breaks the test even though the behaviour looks right on screen. +- **Getting the exact text wrong.** Comparisons include capitalisation, punctuation and spacing: `"Yellow"` is not `"yellow"`, and the milk song's last verse changes to "no more bottles" and "Go to the store and buy some more". +- **Forgetting the singular case.** The 99-bottles exercise flips from "bottles" to "bottle" at 1, which is the single most common reason its last test fails. +- **Off-by-one ranges.** `randint(a, b)` includes both ends, `randrange(a, b)` excludes the last one, and the loop in exercise `13` has to reach 11, not stop at 10. +- **Not calling your own function.** Several tests check that the function is both defined and invoked, for example that `print(get_randomInt())` actually appears in `app.py`. + +## ❓ Frequently asked questions + +### How long does it take to learn Python basics with these exercises? + +The package is estimated at 10 hours across 21 challenges. Most of them are a few lines of code; the ones that take longest are FizzBuzz, the random-colors list and the 99-bottles song, because their expected output is compared character by character. + +### Do I need to know how to program before starting? + +No. The tutorial is marked as `easy` difficulty and begins with printing a single line of text. Concepts arrive in order — console, variables, input, conditionals, randomness, functions, loops, lists — and each one is used again in a later exercise. + +### Do I have to install Python on my computer? + +Not if you use Codespaces: the `.devcontainer` in this repository provisions Python 3.10, Node 22, LearnPack and pytest automatically, and the exercises open in the browser. Installing locally is supported too and needs Python 3, Node.js 14 or newer, and the `pytest`, `pytest-testdox` and `mock` packages. + +### My code works but the test still fails. Is that normal? + +Yes, and it is worth knowing why. Some tests inspect your source code with regular expressions to check you used the specific construct being taught, so a correct answer written a different way can be rejected. The original authors describe the grading as rigid and suggest treating it as a suggestion rather than a verdict. When in doubt, compare your file with the `solution.hide.py` next to the exercise. -> Note: Once you finish downloading, you will find an "exercises" folder that contains all the exercises within. +### Is it free, and can I reuse the code? -3. Start the tutorial/exercises by running the following command at the same level where your learn.json file is: +Access costs nothing and the code you write is yours. The content itself is not open source: the [LICENSE](https://github.com/4GeeksAcademy/python-beginner-programming-exercises/blob/HEAD/LICENSE.md) reserves all intellectual property rights and forbids republishing, selling, reproducing or redistributing the material. You can use it for personal learning and study, which is what 4Geeks Academy publishes it for. + +### What should I do after finishing? + +Move on to the packages this tutorial itself points you to: a dedicated set of [lists and loops exercises](https://4geeks.com/en/interactive-exercise/python-lists-loops-programming-exercises) and more than 20 [functions exercises](https://4geeks.com/en/interactive-exercise/python-functions-programming-exercises) that grow in difficulty. Exercises `10.1`, `13` and `15` link to them directly. + + +## 📚 Related tutorials + +- [Python lists and loops exercises](https://4geeks.com/en/interactive-exercise/python-lists-loops-programming-exercises) — the natural next step after exercise `13`. +- [Python functions exercises](https://4geeks.com/en/interactive-exercise/python-functions-programming-exercises) — 20+ challenges, referenced from exercises `10` and `10.1`. +- [Intro video for this course](https://www.youtube.com/watch?v=amyDNhZwGJQ) — the walkthrough linked from `learn.json`. + +## 🚀 How to start + +One-click installation, recommended: + +[Open in GitHub Codespaces](https://codespaces.new/?repo=4GeeksAcademy/python-beginner-programming-exercises) + +Once VS Code opens, the LearnPack exercises should start on their own. If they don't, type this in the terminal: ```bash -$ pip3 install pytest==6.2.5 pytest-testdox mock $ learnpack start ``` - +> 💡 You can also follow the same tutorial on the web at [4geeks.com](https://4geeks.com/en/interactive-exercise/python-beginner-programming-exercises). + +## 💻 Local installation + +1. Install [LearnPack](https://learnpack.co), Node.js 14+ and Python 3+: -## How are the exercises organized? + ```bash + $ npm i @learnpack/learnpack -g && learnpack plugins:install @learnpack/python + ``` -Each exercise is a small Python application containing the following files: +2. Clone the repository and enter the folder: -1. **app.py:** represents the entry Python file that will be executed by the computer. -2. **README.md:** contains exercise instructions. -3. **test.py:** you don't have to open this file, it contains the testing script for the exercise. + ```bash + $ git clone https://github.com/4GeeksAcademy/python-beginner-programming-exercises.git + $ cd python-beginner-programming-exercises + ``` -> Note: The exercises have automatic grading, but it's very rigid and strict, my recommendation is to not take the tests too serious and use them only as a suggestion, or you may get frustrated. +3. Install the testing dependencies and start, from the same level as `learn.json`: -## Contributors + ```bash + $ pip3 install pytest==6.2.5 pytest-testdox mock + $ learnpack start + ``` -Thanks goes to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): +## 📚 How the exercises are organized -1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribution: (coder) 💻, (idea) 🤔, (build-tests) ⚠️, (pull-request-review) 👀, (build-tutorial) ✅, (documentation) 📖 +Every exercise lives in its own folder inside [`exercises/`](https://github.com/4GeeksAcademy/python-beginner-programming-exercises/tree/HEAD/exercises). The 21 graded ones contain: -2. [Paolo (plucodev)](https://github.com/plucodev), contribution: (bug reports) 🐛, (coder) 💻, (translation) 🌎 +- **`app.py`** — the entry file you edit and run. +- **`README.md`** — the instructions in English. +- **`README.es.md`** — the instructions in Spanish. +- **`test.py`** — the grading script; you don't need to open it. +- **`solution.hide.py`** — a worked solution, hidden by LearnPack until you ask for it. -This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind are welcome! +## 🤝 Contributors -This and many other exercises are built by students as part of the 4Geeks Academy [Coding Bootcamp](https://4geeksacademy.com/us/coding-bootcamp) by [Alejandro Sánchez](https://twitter.com/alesanchezr) and many other contributors. Find out more about our [Full Stack Developer Course](https://4geeksacademy.com/us/coding-bootcamps/part-time-full-stack-developer), and [Data Science Bootcamp](https://4geeksacademy.com/us/coding-bootcamps/datascience-machine-learning). +Thanks to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): + +1. [Alejandro Sánchez (alesanchezr)](https://github.com/alesanchezr) — (coder) 💻, (idea) 🤔, (build-tests) ⚠️, (pull-request-review) 👀, (build-tutorial) ✅, (documentation) 📖 +2. [Paolo Lucano (plucodev)](https://github.com/plucodev) — (bug reports) 🐛, (coder) 💻, (translation) 🌎 +3. [Marco Gómez (marcogonzalo)](https://github.com/marcogonzalo) — (translation) 🌎 + +This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind are welcome — see the [full contributor list](https://github.com/4GeeksAcademy/python-beginner-programming-exercises/graphs/contributors). + +This and many other exercises are built by students as part of the [4Geeks Academy Coding Bootcamp](https://4geeks.com/en/coding-bootcamp). Find out more about the [Full Stack Developer program](https://4geeks.com/en/career-programs/full-stack) and the [Data Science and Machine Learning program](https://4geeks.com/en/career-programs/data-science-ml). +