├── .devcontainer └── devcontainer.json ├── .github └── workflows │ └── learnpack-audit.yml ├── .gitignore ├── .gitpod.Dockerfile ├── .gitpod.yml ├── .learn └── assets │ ├── badge-python-bg.png │ ├── preview.png │ ├── python-intro.gif │ └── run-exercise.png ├── .vscode └── settings.json ├── LICENSE.md ├── README.es.md ├── README.md ├── exercises ├── 00-Welcome │ ├── README.es.md │ └── README.md ├── 01-Console │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 02-Declare-Variables │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 03-Print-Variables-In-The-Console │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 04-Multiply-Two-Values │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 05-User-Inputed-Values │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 06-String-Concatenation │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 07-Create-a-Basic-HTML │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 08.1-Your-First-If │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 08.2-How-Much-The-Wedding-Costs │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 09-Random-Numbers │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 10-Calling-Your-First-Function │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 10.1-Creating-Your-First-Function │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 11-Create-A-New-Function │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 12-Rand-From-One-to-Twelve │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 13-Your-First-Loop │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 14-Create-A-For-Loop │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 15-Looping-With-FizzBuzz │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 16-Random-Colors-Loop │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 17-Russian-Roulette │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 18-The-Beatles │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py └── 19-Bottles-Of-Milk │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py └── learn.json /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | 2 | // For format details, see https://aka.ms/devcontainer.json. For config options, see the 3 | // README at: https://github.com/devcontainers/templates/tree/main/src/python 4 | { 5 | "name": "Python 3", 6 | // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile 7 | "image": "mcr.microsoft.com/devcontainers/python:0-3.10", 8 | "features": { 9 | "ghcr.io/devcontainers/features/node:1": { 10 | "nodeGypDependencies": true, 11 | "version": "16" 12 | } 13 | }, 14 | "customizations": { 15 | "vscode": { 16 | "settings": { 17 | "editor.defaultFormatter": "esbenp.prettier-vscode", 18 | "workbench.editorAssociations": { 19 | "*.md": "vscode.markdown.preview.editor" 20 | } 21 | }, 22 | "extensions": ["learn-pack.learnpack-vscode"] 23 | } 24 | }, 25 | "onCreateCommand": "sudo apt-get update -y && sudo apt-get install xdg-utils -y && pip3 install pytest==6.2.5 pytest-testdox mock && npm i @learnpack/learnpack@5.0.19 -g && learnpack plugins:install @learnpack/python@1.0.6" 26 | 27 | // Features to add to the dev container. More info: https://containers.dev/features. 28 | // "features": {}, 29 | 30 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 31 | // "forwardPorts": [], 32 | 33 | // Use 'postCreateCommand' to run commands after the container is created. 34 | // "postCreateCommand": "pip3 install --user -r requirements.txt", 35 | 36 | // Configure tool-specific properties. 37 | // "customizations": {}, 38 | 39 | // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. 40 | // "remoteUser": "root" 41 | } 42 | -------------------------------------------------------------------------------- /.github/workflows/learnpack-audit.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: Learnpack audit 5 | 6 | on: 7 | push: 8 | branches: [ main ] 9 | pull_request: 10 | branches: [ main ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | strategy: 18 | matrix: 19 | node-version: [20.x] 20 | # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ 21 | 22 | steps: 23 | - uses: actions/checkout@v2 24 | - name: Use Node.js ${{ matrix.node-version }} 25 | uses: actions/setup-node@v2 26 | with: 27 | node-version: ${{ matrix.node-version }} 28 | - run: npm install @learnpack/learnpack@latest -g 29 | - run: learnpack audit -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore everything 2 | /* 3 | 4 | !.gitignore 5 | !.devcontainer 6 | !.devcontainer/* 7 | !.gitpod.yml 8 | !.gitpod.Dockerfile 9 | !learn.json 10 | !bc.json 11 | !README.md 12 | !README.es.md 13 | !.vscode 14 | 15 | !/exercises 16 | !/exercises/* 17 | 18 | *.pyc 19 | __pycache__/ 20 | .pytest_cache/ 21 | 22 | !/.learn 23 | /.learn/** 24 | !/.learn/resets 25 | !/.learn/resets/** 26 | !/.learn/assets 27 | !/.learn/assets/** 28 | 29 | -------------------------------------------------------------------------------- /.gitpod.Dockerfile: -------------------------------------------------------------------------------- 1 | FROM gitpod/workspace-full:latest 2 | 3 | SHELL ["/bin/bash", "-c"] 4 | 5 | RUN sudo apt-get update \ 6 | && sudo apt-get update \ 7 | && sudo apt-get clean \ 8 | && sudo rm -rf /var/cache/apt/* /var/lib/apt/lists/* /tmp/* 9 | 10 | # That Gitpod install pyenv for me? no, thanks 11 | WORKDIR /home/gitpod/ 12 | RUN rm .pyenv -Rf 13 | RUN rm .gp_pyenv.d -Rf 14 | RUN curl https://pyenv.run | bash 15 | 16 | 17 | RUN pyenv update && pyenv install 3.10.7 && pyenv global 3.10.7 18 | RUN pip install pipenv 19 | 20 | # remove PIP_USER environment 21 | USER gitpod 22 | RUN if ! grep -q "export PIP_USER=no" "$HOME/.bashrc"; then printf '%s\n' "export PIP_USER=no" >> "$HOME/.bashrc"; fi 23 | RUN echo "" >> $HOME/.bashrc 24 | RUN echo "unset DATABASE_URL" >> $HOME/.bashrc 25 | RUN echo "export DATABASE_URL" >> $HOME/.bashrc 26 | 27 | RUN pip3 install pytest==6.2.5 pytest-testdox mock 28 | RUN npm i @learnpack/learnpack@2.1.56 -g && learnpack plugins:install @learnpack/python@1.0.3 29 | -------------------------------------------------------------------------------- /.gitpod.yml: -------------------------------------------------------------------------------- 1 | image: 2 | file: .gitpod.Dockerfile 3 | 4 | ports: 5 | - port: 3000 6 | onOpen: ignore 7 | 8 | vscode: 9 | extensions: 10 | - learn-pack.learnpack-vscode 11 | 12 | 13 | github: 14 | prebuilds: 15 | # enable for the master/default branch (defaults to true) 16 | master: true 17 | # enable for pull requests coming from this repo (defaults to true) 18 | pullRequests: false 19 | # add a "Review in Gitpod" button as a comment to pull requests (defaults to true) 20 | addComment: false 21 | -------------------------------------------------------------------------------- /.learn/assets/badge-python-bg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/4GeeksAcademy/python-beginner-programming-exercises/fc351e4f61c8e1082e8cc98cd9304332c8fda0ad/.learn/assets/badge-python-bg.png -------------------------------------------------------------------------------- /.learn/assets/preview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/4GeeksAcademy/python-beginner-programming-exercises/fc351e4f61c8e1082e8cc98cd9304332c8fda0ad/.learn/assets/preview.png -------------------------------------------------------------------------------- /.learn/assets/python-intro.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/4GeeksAcademy/python-beginner-programming-exercises/fc351e4f61c8e1082e8cc98cd9304332c8fda0ad/.learn/assets/python-intro.gif -------------------------------------------------------------------------------- /.learn/assets/run-exercise.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/4GeeksAcademy/python-beginner-programming-exercises/fc351e4f61c8e1082e8cc98cd9304332c8fda0ad/.learn/assets/run-exercise.png -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.autoSave": "afterDelay", 3 | "files.autoSaveDelay": 700, 4 | "editor.minimap.enabled": false, 5 | "workbench.editorAssociations": { 6 | "*.md": "vscode.markdown.preview.editor" 7 | } 8 | } -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 2 | 3 | By accessing Breathe Code we assume you accept these terms and conditions. Do not continue to use Breathe Code's content, applications or tutorials if you do not agree to take all of the terms and conditions stated on this page. 4 | 5 | Unless otherwise stated, Breathe Code and/or its licensors own the intellectual property rights for all material on Breathe Code. All intellectual property rights are reserved. You may access this from Breathe Code for your own personal use subjected to restrictions set in these terms and conditions. 6 | 7 | You must not: 8 | 9 | * Republish material from Breathe Code 10 | * Sell, rent or sub-license material from Breathe Code 11 | * Reproduce, duplicate or copy material from Breathe Code 12 | * Redistribute content from Breathe Code 13 | 14 | You can read the full version of Breathe Code's terms and conditions here: [Terms and Conditions](http://breatheco.de/terms-and-conditions) 15 | -------------------------------------------------------------------------------- /README.es.md: -------------------------------------------------------------------------------- 1 | 2 | # 🐍 Tutorial y Ejercicios para Principiantes de Python 3 | 4 | Por @alesanchezr y otros colaboradores en 4Geeks Academy 5 | 6 | 7 | Esta serie en particular es para principiantes de Python. Aprenderás los siguientes conceptos: 8 | 9 | 1. La función `print`. 10 | 11 | 2. Tipos de datos. 12 | 13 | 3. Listas y tuplas. 14 | 15 | 4. Funciones y diccionarios. 16 | 17 | Todo el tutorial es 👆 interactivo, ✅ calificado automáticamente, y con 📹 video tutoriales. 18 | 19 | 20 | ¡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. 21 | 22 | 23 | 24 | ## Instalación en un clic (recomendado) 25 | 26 | 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). 27 | 28 | > 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` 29 | 30 | ## Instalación local: 31 | 32 | 1. Asegúrate de instalar [LearnPack](https://learnpack.co), node.js version 14+ y Python version 3+. Este es el comando para instalar LearnPack: 33 | 34 | ```bash 35 | $ npm i @learnpack/learnpack@2.1.20 -g && learnpack plugins:install @learnpack/python@1.0.0 36 | ``` 37 | 38 | 2. Clona o descarga este repositorio en tu ambiente local. 39 | 40 | ```bash 41 | $ git clone https://github.com/4GeeksAcademy/python-beginner-programming-exercises.git 42 | $ cd python-beginner-programming-exercises 43 | ``` 44 | 45 | > Nota: Una vez que termine de descargar, encontrarás la carpeta "exercises" que contiene todos los ejercicios. 46 | 47 | 3. Inicializa el tutorial ejecutando el siguiente comando al mismo nivel en el que se encuentra tu archivo learn.json: 48 | 49 | ```bash 50 | $ pip3 install pytest==6.2.5 pytest-testdox mock 51 | $ learnpack start 52 | ``` 53 | 54 | 55 | 56 | 57 | ## ¿Cómo están organizados los ejercicios? 58 | 59 | Cada ejercicio es una pequeña aplicación de Python que contiene los siguientes archivos: 60 | 61 | 1. **app.py:** representa el archivo de entrada de Python que será ejecutado por el computador. 62 | 2. **README.es.md:** Contiene las instrucciones del ejercicio. 63 | 3. **test.py:** Contiene el script del test para el ejercicio (no es necesario que abras este archivo). 64 | 65 | > 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. 66 | 67 | ## Colaboradores 68 | 69 | Gracias a estas personas maravillosas ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): 70 | 71 | 1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribución: (programador) 💻 (idea) 🤔, (build-tests) ⚠️, (pull-request-review) 👀, (build-tutorial) ✅, (documentación) 📖 72 | 73 | 2. [Paolo (plucodev)](https://github.com/plucodev), contribución: (bug reports) 🐛, (programador) 💻, (traducción) 🌎 74 | 75 | Este proyecto sigue la especificación [all-contributors](https://github.com/kentcdodds/all-contributors). ¡Todas las contribuciones son bienvenidas! 76 | 77 | 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). 78 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | # 🐍 Python Beginner Tutorial and Exercises 6 | 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) 7 | 8 | 9 | 10 | *Estas instrucciones [están disponibles en 🇪🇸 español](https://github.com/4GeeksAcademy/python-beginner-programming-exercises/blob/master/README.es.md) :es:* 11 | 12 | 13 | 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. 14 | 15 | This particular series is for Python beginners. You will learn: 16 | 17 | 1. The `print` function. 18 | 19 | 2. Data-Types. 20 | 21 | 3. Lists and Tuples. 22 | 23 | 4. Functions and dictionaries. 24 | 25 | The entire tutorial is 👆 interactive, ✅ auto-graded, and has 📹 video tutorials. 26 | 27 | These exercises were built in collaboration, we need you! If you find any bugs or misspellings please contribute and report them. 28 | 29 | 30 | 31 | ## One click installation (recommended): 32 | 33 | 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). 34 | 35 | > 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` 36 | 37 | ## Local Installation 38 | 39 | 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: 40 | 41 | ```bash 42 | $ npm i @learnpack/learnpack@2.1.20 -g && learnpack plugins:install @learnpack/python@1.0.0 43 | ``` 44 | 45 | 2. Clone or download this repository in your local environment. 46 | 47 | ```bash 48 | $ git clone https://github.com/4GeeksAcademy/python-beginner-programming-exercises.git 49 | $ cd python-beginner-programming-exercises 50 | ``` 51 | 52 | > Note: Once you finish downloading, you will find an "exercises" folder that contains all the exercises within. 53 | 54 | 3. Start the tutorial/exercises by running the following command at the same level where your learn.json file is: 55 | 56 | ```bash 57 | $ pip3 install pytest==6.2.5 pytest-testdox mock 58 | $ learnpack start 59 | ``` 60 | 61 | 62 | 63 | ## How are the exercises organized? 64 | 65 | Each exercise is a small Python application containing the following files: 66 | 67 | 1. **app.py:** represents the entry Python file that will be executed by the computer. 68 | 2. **README.md:** contains exercise instructions. 69 | 3. **test.py:** you don't have to open this file, it contains the testing script for the exercise. 70 | 71 | > 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. 72 | 73 | ## Contributors 74 | 75 | Thanks goes to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): 76 | 77 | 1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribution: (coder) 💻, (idea) 🤔, (build-tests) ⚠️, (pull-request-review) 👀, (build-tutorial) ✅, (documentation) 📖 78 | 79 | 2. [Paolo (plucodev)](https://github.com/plucodev), contribution: (bug reports) 🐛, (coder) 💻, (translation) 🌎 80 | 81 | This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind are welcome! 82 | 83 | 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). 84 | -------------------------------------------------------------------------------- /exercises/00-Welcome/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | intro: "https://www.youtube.com/watch?v=IXNSwnN-YqM" 3 | --- 4 | 5 | # Bienvenid@ al curso de Python para principiantes! 6 | 7 | ¡Estamos muy entusiasmados por tenerte aquí! 🎉 😂 8 | 9 | ## 💬 Fundamentos: 10 | 11 | Durante este curso aprenderás los siguientes conceptos: 12 | 13 | 1. Cómo crear y llamar funciones. 14 | 15 | 2. Cómo crear y llamar variables. 16 | 17 | 3. Cómo concatenar strings. 18 | 19 | 4. Cómo usar bucles (loops) y declaraciones if...else. 20 | 21 | 5. Cómo combinar y usar todos estos conceptos de diferentes formas. 22 | 23 | Por favor, haz clic en el botón `Next →` arriba a la derecha para dirigirte al primer ejercicio. 24 | 25 | ## Lecturas Útiles: 26 | 27 | + [https://datademia.es/blog/que-es-python](https://datademia.es/blog/que-es-python) 28 | 29 | + [https://www.capacitarte.org/blog/nota/que-es-y-para-que-sirve-python](https://www.capacitarte.org/blog/nota/que-es-y-para-que-sirve-python) 30 | 31 | ## Video Útil: 32 | 33 | + [https://youtu.be/lc5JJTQa4r8](https://youtu.be/lc5JJTQa4r8) 34 | 35 | ## Colaboradores: 36 | 37 | Gracias a estas maravillosas personas ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): 38 | 39 | 1. [Alejandro Sánchez (alesanchezr)](https://github.com/alesanchezr), contribución: (programador) 💻, (idea) 🤔, (build-tests) ⚠️, (pull-request-review) 🤓, (build-tutorial) ✅, (documentación) 📖 40 | 41 | 2. [Paolo Lucano (plucodev)](https://github.com/plucodev), contribución: (programador) 💻, (build-tests) ⚠️ 42 | 43 | 3. [Marco Gómez (marcogonzalo)](https://github.com/marcogonzalo), contribución: (traducción) 🌎 44 | 45 | Este proyecto sigue las especificaciones: [all-contributors](https://github.com/kentcdodds/all-contributors). 46 | 47 | ¡Todas las contribuciones son bienvenidas! 48 | -------------------------------------------------------------------------------- /exercises/00-Welcome/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | intro: "https://www.youtube.com/watch?v=amyDNhZwGJQ" 3 | --- 4 | 5 | # Welcome to the Python Beginner Course! 6 | 7 | We are very excited to have you here! 🎉 😂 8 | 9 | ## 💬 Fundamentals: 10 | 11 | During this course, you will be learning the following concepts: 12 | 13 | 1. How to create and call functions. 14 | 15 | 2. How to create and call variables. 16 | 17 | 3. How to concatenate strings. 18 | 19 | 4. How to use loops and if statements. 20 | 21 | 5. How to combine and use all these concepts in different ways. 22 | 23 | Please click on the `Next →` button on the top right to proceed to the first challenge. 24 | 25 | ## Useful Readings: 26 | 27 | + [https://www.w3schools.com/python/python_intro.asp](https://www.w3schools.com/python/python_intro.asp) 28 | 29 | + [https://www.python.org/doc/essays/blurb/](https://www.python.org/doc/essays/blurb/) 30 | 31 | ## Useful Video: 32 | 33 | + [https://youtu.be/Y8Tko2YC5hA](https://youtu.be/Y8Tko2YC5hA) 34 | 35 | ## Contributors: 36 | 37 | Thanks to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): 38 | 39 | 1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribution: (coder) 💻, (idea) 🤔, (build-tests) ⚠️, (pull-request-review) 🤓, (build-tutorial) ✅, (documentation) 📖 40 | 41 | 2. [Paolo Lucano (plucodev)](https://github.com/plucodev), contribution: (coder) 💻, (build-tests) ⚠️ 42 | 43 | 3. [Marco Gómez (marcogonzalo)](https://github.com/marcogonzalo), contribution: (translator) 🌎 44 | 45 | 46 | This project follows these specifications: [all-contributors](https://github.com/kentcdodds/all-contributors) 47 | 48 | 49 | Contributions of any kind are welcome! 50 | -------------------------------------------------------------------------------- /exercises/01-Console/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=z6OnN4s__TU" 3 | --- 4 | 5 | # `01` Console 6 | 7 | En Python, usamos **print** para que el computador escriba cualquier cosa que queramos (el contenido de una variable, una string dado, etc.) en algo llamado "la consola". 8 | 9 | Cada lenguaje de programación tiene una consola, ya que al principio era la única forma de interactuar con los usuarios (antes de que llegaran Windows, Linux o macOS). 10 | 11 | Hoy en día, la impresión en la consola se utiliza, sobre todo, como herramienta de monitoreo y depuración, ideal para dejar un rastro del contenido de las variables durante la ejecución del programa. 12 | 13 | Este es un ejemplo de cómo usarla: 14 | 15 | ```py 16 | print("Un texto en la consola") 17 | ``` 18 | 19 | ## 📝 Instrucciones: 20 | 21 | 1. Usa **print** para escribir `Hello World!` en la consola. 22 | 23 | ## 💡 Pistas: 24 | 25 | + Recuerda, para ejecutar el código y ver el resultado en la consola, haz clic en el ícono de caja en la esquina superior izquierda de la pantalla: 26 | 27 | ![Botón de compilar](https://github.com/4GeeksAcademy/python-beginner-programming-exercises/blob/1d9d7f83b678411be8ff9efc3bad9dab4265d057/.learn/assets/run-exercise.png?raw=true) 28 | 29 | + Siéntete libre de intentar otras cosas también. 30 | -------------------------------------------------------------------------------- /exercises/01-Console/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=2sV-2frucUs" 3 | --- 4 | 5 | # `01` Console 6 | 7 | In Python, we use **print** to make the computer write anything we want (the content of a variable, a given string, etc.) in something called "the console". 8 | 9 | Every programming language has a console, as it was the only way to interact with the users at the beginning (before Windows, Linux or macOS arrived). 10 | 11 | Today, printing in the console is mostly used as a monitoring and debugging tool, ideal for leaving a trace of the content of variables during the program's execution. 12 | 13 | This is an example of how to use it: 14 | 15 | ```py 16 | print("How are you?") 17 | ``` 18 | 19 | ## 📝 Instructions: 20 | 21 | 1. Use `print()` to print `Hello World!` on the console. 22 | 23 | 24 | ## 💡 Hints: 25 | 26 | + Remember, to run the code and see the output on the console, click on the box icon in the top left of the screen: 27 | 28 | ![The compile button](https://github.com/4GeeksAcademy/python-beginner-programming-exercises/blob/1d9d7f83b678411be8ff9efc3bad9dab4265d057/.learn/assets/run-exercise.png?raw=true) 29 | 30 | + Feel free to try other things as well. 31 | -------------------------------------------------------------------------------- /exercises/01-Console/app.py: -------------------------------------------------------------------------------- 1 | # print "Hello World!" on the console -------------------------------------------------------------------------------- /exercises/01-Console/solution.hide.py: -------------------------------------------------------------------------------- 1 | # print "Hello World!" on the console 2 | 3 | print("Hello World!") -------------------------------------------------------------------------------- /exercises/01-Console/test.py: -------------------------------------------------------------------------------- 1 | import io 2 | import sys 3 | sys.stdout = buffer = io.StringIO() 4 | import app 5 | import re 6 | import os 7 | import pytest 8 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 9 | 10 | @pytest.mark.it('Use the function print()') 11 | def test_for_file_output(capsys): 12 | 13 | with open(path, 'r') as content_file: 14 | content = content_file.read() 15 | pattern = r"print\s*\(" 16 | regex = re.compile(pattern) 17 | assert bool(regex.search(content)) == True 18 | 19 | @pytest.mark.it('Print Hello World! on the console') 20 | def test_for_console_log(capsys): 21 | captured = buffer.getvalue() 22 | assert "Hello World!\n" in captured #add \n because the console jumps the line on every print 23 | 24 | -------------------------------------------------------------------------------- /exercises/02-Declare-Variables/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=FeSo8xlnrTI" 3 | --- 4 | 5 | # `02` Declare Variables 6 | 7 | En la programación, usamos variables como si fueran cajas (o contenedores) para guardar diferentes tipos de información. Así es cómo creamos una variable: 8 | 9 | ```py 10 | name = "Daniel" 11 | ``` 12 | 13 | En este ejemplo, `name` es la variable, actuando como una caja para almacenar el valor `"Daniel"`. Dentro de esta 'caja', estamos almacenando el valor `"Daniel"`, y podemos usar `name` para referirnos a este valor más tarde. Al nombrar tus variables, puedes elegir casi cualquier nombre, pero debe comenzar con una letra o un guion bajo (`_`). Es útil elegir un nombre que describa lo que hay dentro de la 'caja' para que puedas entender fácilmente lo que representa más adelante. 14 | 15 | ## 📝 Instrucciones: 16 | 17 | 1. Declara una variable llamada `name` con el valor `"Yellow"` y luego imprímelo en la consola. 18 | 19 | 2. Luego, imprime su valor en la consola usando `print(name)`. 20 | 21 | ## 💡 Pistas: 22 | 23 | + El nombre de la variable debe ser `name` para pasar los tests y su valor tiene que ser el texto "Yellow". 24 | 25 | + Si necesitas más explicación sobre qué son los **strings** y cómo funcionan en Python, puedes ver este clip: https://www.youtube.com/watch?v=yT0jixU3M2c&ab_channel=ProgramaResuelto (`ctrl + click` en el enlace para abrir el video) 26 | -------------------------------------------------------------------------------- /exercises/02-Declare-Variables/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=dWWvZkaPwDw" 3 | --- 4 | 5 | # `02` Declare Variables 6 | 7 | In programming, we use variables like boxes (or containers) to store different kinds of information. Here's how to create a variable: 8 | 9 | ```py 10 | name = "Daniel" 11 | ``` 12 | 13 | In this example, `name` is the variable, acting like a box to store the value `"Daniel"`. Inside this 'box', we're storing the value `"Daniel"`, and we can use `name` to refer to it later. When naming your variables, you can choose almost any name, but it must begin with a letter or an underscore (`_`). It's helpful to pick a name that describes what's inside the 'box' so you can easily understand what it represents later on. 14 | 15 | ## 📝 Instructions: 16 | 17 | 1. Declare a new variable named `name` with the string value `"Yellow"` and print the value to the console. 18 | 19 | 2. Then, print its value on the console using `print(name)`. 20 | 21 | ## 💡 Hints: 22 | 23 | + The variable's name must be `name` to pass the tests, and the value inside has to be the string "Yellow". 24 | 25 | + If you need further explanation on what **strings** are and how they work in Python, you can watch this clip: https://youtube.com/clip/UgkxyQ_JLmgSUL4l25c8Ly7cCRvk1Gm-EchU (`ctrl + click` on the link to open the video) 26 | -------------------------------------------------------------------------------- /exercises/02-Declare-Variables/app.py: -------------------------------------------------------------------------------- 1 | # ✅ ↓ your code here ↓ ✅ 2 | -------------------------------------------------------------------------------- /exercises/02-Declare-Variables/solution.hide.py: -------------------------------------------------------------------------------- 1 | # ✅ ↓ your code here ↓ ✅ 2 | 3 | color = "Yellow" 4 | print(color) -------------------------------------------------------------------------------- /exercises/02-Declare-Variables/test.py: -------------------------------------------------------------------------------- 1 | import io 2 | import sys 3 | sys.stdout = buffer = io.StringIO() 4 | import app 5 | # from app import my_function 6 | import pytest 7 | import os 8 | import re 9 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 10 | 11 | @pytest.mark.it('Use the function print()') 12 | def test_for_print(): 13 | 14 | with open(path, 'r') as content_file: 15 | content = content_file.read() 16 | regex = re.compile(r"print\s*\(['\"]?.+['\"]?\)") 17 | assert bool(regex.search(content)) == True 18 | 19 | @pytest.mark.it('Declare a variable and assign it the value "Yellow"') 20 | def test_for_variable(): 21 | 22 | with open(path, 'r') as content_file: 23 | content = content_file.read() 24 | regex = re.compile(r"\w*(\s*)=(\s*)(\"|\')Yellow(\"|\')") 25 | assert bool(regex.search(content)) == True 26 | 27 | @pytest.mark.it('Print the variable on the console') 28 | def test_for_file_output(capsys): 29 | captured = buffer.getvalue() 30 | assert "Yellow\n" in captured #add \n because the console jumps the line on every print 31 | 32 | 33 | -------------------------------------------------------------------------------- /exercises/03-Print-Variables-In-The-Console/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=SM71mzjuvfA" 3 | --- 4 | 5 | # `03` Print more Variables in The Console 6 | 7 | También puedes imprimir más de una variable en la misma función `print()` separando con una coma `,` las variables a imprimir. De esta manera: 8 | 9 | ```py 10 | my_variable = 'hello' 11 | my_second_variable = "world" 12 | print(my_variable, my_second_variable) # --> hello world 13 | ``` 14 | 15 | ## 📝 Instrucciones: 16 | 17 | 1. Declara dos nuevas variables llamadas `color` y `item` y asígnales el valor `"red"` y `marker` respectivamente. 18 | 19 | 2. Luego, imprime sus valores en la consola (puede que tengas que desplazarte en la consola para poder verlo). 20 | -------------------------------------------------------------------------------- /exercises/03-Print-Variables-In-The-Console/README.md: -------------------------------------------------------------------------------- 1 | # `03` Print more Variables in the console 2 | 3 | You can also print more than one variable in the same `print()` function by separating the variables with a comma `,`. Like this: 4 | 5 | ```py 6 | my_variable = 'hello' 7 | my_second_variable = "world" 8 | print(my_variable, my_second_variable) # --> hello world 9 | ``` 10 | 11 | ## 📝 Instructions: 12 | 13 | 1. Declare two new variables called `color` and `item`, and assign the value `"red"` and `"marker"` respectively to it. 14 | 15 | 2. Then, print their values on the console (you may have to scroll up in the terminal to see it!). 16 | -------------------------------------------------------------------------------- /exercises/03-Print-Variables-In-The-Console/app.py: -------------------------------------------------------------------------------- 1 | # ✅ ↓ your code here ↓ ✅ -------------------------------------------------------------------------------- /exercises/03-Print-Variables-In-The-Console/solution.hide.py: -------------------------------------------------------------------------------- 1 | # ✅ ↓ your code here ↓ ✅ 2 | 3 | color = "red" 4 | item = "marker" 5 | print(color, item) 6 | -------------------------------------------------------------------------------- /exercises/03-Print-Variables-In-The-Console/test.py: -------------------------------------------------------------------------------- 1 | import io 2 | import sys 3 | sys.stdout = buffer = io.StringIO() 4 | # from app import my_function 5 | import pytest 6 | import app 7 | import os 8 | 9 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 10 | 11 | @pytest.mark.it("Create a variable named 'color' with the string value 'red'") 12 | def test_declare_variable(): 13 | result = app.color 14 | assert result == "red" 15 | 16 | @pytest.mark.it("Create a variable named 'item' with the string value 'marker'") 17 | def test_declare_variable(): 18 | result = app.item 19 | assert result == "marker" 20 | 21 | @pytest.mark.it('The printed value on the console should be "red marker"') 22 | def test_for_file_output(capsys): 23 | captured = buffer.getvalue() 24 | assert "red marker\n" in captured 25 | -------------------------------------------------------------------------------- /exercises/04-Multiply-Two-Values/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=p4PY8s6asfw" 3 | --- 4 | 5 | # `04` Multiply Two Values 6 | 7 | Cualquier lenguaje de programación te permite realizar operaciones matemáticas básicas como multiplicación, división, etc. 8 | 9 | Para multiplicar dos valores en Python, tienes que usar el operador estrella o asterisco de esta forma: 10 | 11 | ```py 12 | resulting_value = 2 * 3 13 | ``` 14 | 15 | En este caso, hemos almacenado el resultado de la multiplicación en una variable llamada `resulting_value`. 16 | 17 | ## 📝 Instrucciones: 18 | 19 | 1. Por favor, almacena el resultado de multiplicar 2345 por 7323 en una variable llamada `variables_are_cool`. 20 | 21 | 2. Ahora imprime el resultado en la consola. -------------------------------------------------------------------------------- /exercises/04-Multiply-Two-Values/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=tATIrAWiLLU" 3 | --- 4 | 5 | # `04` Multiply Two Values 6 | 7 | Any programming language lets you do basic Math operations like multiplication, division, etc. 8 | 9 | To multiply 2 values in Python, you have to use the asterisk operator like this: 10 | 11 | ```py 12 | resulting_value = 2 * 3 13 | ``` 14 | 15 | In this case, we stored the resulting value of the multiplication into a variable called `resulting_value`. 16 | 17 | ## 📝 Instructions: 18 | 19 | 1. Please store the result of multiplying 2345 times 7323 in a variable called `variables_are_cool`. 20 | 21 | 2. Now print the result in the console. 22 | -------------------------------------------------------------------------------- /exercises/04-Multiply-Two-Values/app.py: -------------------------------------------------------------------------------- 1 | # ✅ ↓ your code here ↓ ✅ 2 | -------------------------------------------------------------------------------- /exercises/04-Multiply-Two-Values/solution.hide.py: -------------------------------------------------------------------------------- 1 | # ✅ ↓ your code here ↓ ✅ 2 | 3 | variables_are_cool = 2345 * 7323 4 | print(variables_are_cool) -------------------------------------------------------------------------------- /exercises/04-Multiply-Two-Values/test.py: -------------------------------------------------------------------------------- 1 | import io 2 | import sys 3 | sys.stdout = buffer = io.StringIO() 4 | # from app import my_function 5 | import pytest 6 | import os 7 | import app 8 | import re 9 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 10 | 11 | @pytest.mark.it('You should create a variable named variables_are_cool') 12 | def test_variable_exists(): 13 | try: 14 | from app import variables_are_cool 15 | except ImportError: 16 | raise ImportError("The variable 'variables_are_cool' should exist on app.py") 17 | 18 | @pytest.mark.it('The value of variables_are_cool should be 2345 * 7323') 19 | def test_use_variable_name(): 20 | result = app.variables_are_cool == 17172435 21 | assert result == True 22 | 23 | @pytest.mark.it('Print on the console the value of variables_are_cool') 24 | def test_for_file_output(capsys): 25 | captured = buffer.getvalue() 26 | assert '17172435\n' in captured 27 | 28 | @pytest.mark.it('Print on the console the variables_are_cool variable') 29 | def test_for_print(): 30 | with open(path, 'r') as content_file: 31 | content = content_file.read() 32 | # makes sure we are calling print function with a variable and not the hard coded value 33 | regex = re.compile(r"print\s*\(\s*variables_are_cool\s*\)") 34 | assert bool(regex.search(content)) == True 35 | 36 | @pytest.mark.it('You should not hardcode the result') 37 | def test_for_print(): 38 | with open(path, 'r') as content_file: 39 | content = content_file.read() 40 | # makes sure we are calling print function with a variable and not the hard coded value 41 | assert str(17172435) not in content 42 | -------------------------------------------------------------------------------- /exercises/05-User-Inputed-Values/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=pe_DEzC-528" 3 | --- 4 | 5 | # `05` User Inputed Values 6 | 7 | Otra cosa genial de las variables es que no necesitas saber su valor para poder trabajar con ellas. 8 | 9 | Por ejemplo, justo ahora la aplicación está preguntando la edad del usuario, y luego la imprime en la consola. 10 | 11 | ## 📝 Instrucciones: 12 | 13 | 1. Por favor, añade 10 años al valor de la variable `age`. 14 | 15 | ## 💡 Pistas: 16 | 17 | + Puedes buscar en Google "Como sumarle una cantidad a una variable de Python". 18 | 19 | + Recuerda que el contenido de la variable está siendo definido con lo que sea que el usuario coloque. 20 | -------------------------------------------------------------------------------- /exercises/05-User-Inputed-Values/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=zeWN4ujg6yU" 3 | --- 4 | 5 | # `05` User Inputed Values 6 | 7 | The other cool thing about variables is that you don't need to know their value to be able to work with them. 8 | 9 | For example, the application right now is prompting the user for its age, and then printing it on the console. 10 | 11 | ## 📝 Instructions: 12 | 13 | 1. Please add 10 years to the value of the age variable. 14 | 15 | ## 💡 Hints: 16 | 17 | + You can Google "how to add a number to a Python variable". 18 | 19 | + Remember that the content of the variable is being previously filled with whatever the user inputs. 20 | -------------------------------------------------------------------------------- /exercises/05-User-Inputed-Values/app.py: -------------------------------------------------------------------------------- 1 | age = int(input('What is your age?\n')) 2 | # ✅ ↓ CHANGE THE CODE BELOW TO ADD 10 TO AGE ↓ ✅ 3 | 4 | print("Your age is: "+str(age)) -------------------------------------------------------------------------------- /exercises/05-User-Inputed-Values/solution.hide.py: -------------------------------------------------------------------------------- 1 | age = int(input('What is your age?\n')) 2 | # ✅ ↓ CHANGE THE CODE BELOW TO ADD 10 TO AGE ↓ ✅ 3 | age = age + 10 4 | print("Your age is: "+str(age)) 5 | -------------------------------------------------------------------------------- /exercises/05-User-Inputed-Values/test.py: -------------------------------------------------------------------------------- 1 | import pytest,os,re,io,sys,mock,json 2 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 3 | 4 | @pytest.mark.it('Use the function print()') 5 | def test_for_file_output(capsys): 6 | with open(path, 'r') as content_file: 7 | content = content_file.read() 8 | pattern = (r"print\s*\(") 9 | regex = re.compile(pattern) 10 | assert bool(regex.search(content)) == True 11 | 12 | @pytest.mark.it("Testing with age 50 and it is supposed to return 60") 13 | @mock.patch('builtins.input', lambda x: 50) 14 | def test_plus_ten(stdin): 15 | # f = open(os.path.dirname(os.path.abspath(__file__))+'/app.py') 16 | sys.stdout = buffer = io.StringIO() 17 | import app 18 | captured = buffer.getvalue() 19 | assert "Your age is: 60\n" in captured 20 | 21 | -------------------------------------------------------------------------------- /exercises/06-String-Concatenation/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=4y8xYy273f4" 3 | --- 4 | 5 | # `06` String Concatenation 6 | 7 | La concatenación de strings es una tarea común en la programación que implica combinar o unir dos o más strings. 8 | 9 | Puedes pensar en este proceso como conectar dos o más vagones de tren. Si cada string es un vagón, la concatenación es el acoplamiento que los une para formar un tren único. 10 | 11 | En Python, puedes concatenar o unir dos o más strings usando el operador `+`. Así es como funciona: 12 | 13 | ```py 14 | one = 'a' 15 | two = 'b' 16 | print(one + two) # Esto imprimirá 'ab' en la consola. 17 | ``` 18 | 19 | Aquí, las variables `one` y `two` contienen los strings individuales `'a'` y `'b'`, respectivamente. Cuando usas el operador `+` entre ellos, actúa como un pegamento, uniendo los strings de extremo a extremo. En este caso, une `'a'` y `'b'`, dando como resultado el string concatenado `'ab'`, que se imprime en la consola. 20 | 21 | ## 📝 Instrucciones: 22 | 1. Establece los valores para `my_var1` y `my_var2` de manera que, al concatenarlos, el código imprima `Hello World` en la consola. 23 | 24 | 25 | ## 💡 Pista: 26 | + Si necesitas más explicación sobre como funciona la **concatenación** en Python, puedes ver este clip: https://www.youtube.com/watch?v=T1nyPuAhd1U&ab_channel=ProgramaResuelto (`ctrl + click` en el enlace para abrir el video) 27 | -------------------------------------------------------------------------------- /exercises/06-String-Concatenation/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=kS4qpQmHwCs" 3 | --- 4 | 5 | # `06` String Concatenation 6 | 7 | String concatenation is a common task in programming that involves combining or linking two or more strings together. 8 | 9 | You can think of this process as similar to connecting two or more train cars. If each string is a train car, concatenation is the coupling that joins them to form a single train. 10 | 11 | In Python, you can concatenate, or join together, two or more strings using the `+` operator. This is how it works: 12 | 13 | ```py 14 | one = 'a' 15 | two = 'b' 16 | print(one + two) # This will print 'ab' on the console. 17 | ``` 18 | 19 | Here, the variables `one` and `two` hold the individual strings `'a'` and `'b'`. When you use the `+` operator between them, it acts like a glue, sticking the strings together end-to-end. In this case, it joins `'a'` and `'b'`, resulting in the concatenated string `'ab'`, which gets printed to the console. 20 | 21 | ## 📝 Instructions: 22 | 1. Set the values for `my_var1` and `my_var2` so that, when concatenated, the code prints `Hello World` in the console. 23 | 24 | ## 💡 Hint: 25 | + If you need further explanation on how string **concatenation** works in Python, you can watch this clip: https://www.youtube.com/watch?v=28FUVmWU_fA&ab_channel=PortfolioCourses (`ctrl + click` on the link to open the video) 26 | -------------------------------------------------------------------------------- /exercises/06-String-Concatenation/app.py: -------------------------------------------------------------------------------- 1 | # ✅ ↓ Set the values for my_var1 and my_var2 here ↓ ✅ 2 | 3 | 4 | ## Don't change anything below this line 5 | the_new_string = my_var1 + ' ' + my_var2 6 | print(the_new_string) 7 | -------------------------------------------------------------------------------- /exercises/06-String-Concatenation/solution.hide.py: -------------------------------------------------------------------------------- 1 | # ✅ ↓ Set the values for my_var1 and my_var2 here ↓ ✅ 2 | 3 | my_var1 = "Hello" 4 | my_var2 = "World" 5 | 6 | ## Don't change anything below this line 7 | the_new_string = my_var1 + ' ' + my_var2 8 | print(the_new_string) 9 | -------------------------------------------------------------------------------- /exercises/06-String-Concatenation/test.py: -------------------------------------------------------------------------------- 1 | import io, sys, os, re, pytest 2 | sys.stdout = buffer = io.StringIO() 3 | 4 | import app 5 | 6 | @pytest.mark.it("Create a variable named my_var1") 7 | def test_my_var1_exists(): 8 | try: 9 | from app import my_var1 10 | except ImportError: 11 | raise ImportError("The variable 'my_var1' should exist on app.py") 12 | 13 | @pytest.mark.it("Create a variable named my_var2") 14 | def test_my_var2_exists(): 15 | try: 16 | from app import my_var2 17 | except ImportError: 18 | raise ImportError("The variable 'my_var2' should exist on app.py") 19 | 20 | @pytest.mark.it("Variable my_var1 value should be 'Hello'") 21 | def test_my_var1_value(): 22 | from app import my_var1 23 | assert my_var1.lower() == "hello" 24 | 25 | @pytest.mark.it("Variable my_var2 value should be 'World'") 26 | def test_my_var2_value(): 27 | from app import my_var2 28 | assert my_var2.lower() == "world" 29 | 30 | @pytest.mark.it("Don't remove the_new_string variable") 31 | def test_the_new_string_exists(): 32 | import app 33 | try: 34 | app.the_new_string 35 | except AttributeError: 36 | raise AttributeError('The variable "the_new_string" should exist on app.py') 37 | 38 | @pytest.mark.it('Print "Hello World" on the console') 39 | def test_for_file_output(): 40 | captured = buffer.getvalue() 41 | assert "hello world\n" in captured.lower() #add \n because the console jumps the line on every print 42 | -------------------------------------------------------------------------------- /exercises/07-Create-a-Basic-HTML/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=zbTM_T6an4k" 3 | --- 4 | 5 | # `07` Create a Basic HTML 6 | 7 | Continuemos concatenando strings para generar un documento HTML básico... 8 | 9 | ## 📝 Instrucciones: 10 | 11 | 1. Crea la variable `html_document`. 12 | 13 | 2. El código a la izquierda contiene 8 variables con diferentes valores de tipo *string*. Por favor, usa las variables concatenándolas entre ellas para establecer el valor de la variable `html_document` a la estructura típica de un documento HTML (con las etiquetas HTML en el orden correcto). 14 | 15 | 3. Luego, imprime el valor de `html_document` en la consola. 16 | 17 | ## 💡 Pista: 18 | 19 | + Resultado esperado: 20 | 21 | ```html 22 | 23 | ``` 24 | 25 | -------------------------------------------------------------------------------- /exercises/07-Create-a-Basic-HTML/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=j14V-eS8mRg" 3 | --- 4 | 5 | # `07` Create a Basic HTML 6 | 7 | Let's continue using string concatenation to generate HTML... 8 | 9 | ## 📝 Instructions: 10 | 11 | 1. Create the variable `html_document`. 12 | 13 | 2. The code on the left contains 8 variables with different string values, please use the variables concatenating them together to set the value of the variable `html_document` 14 | to a new string that has the content of a typical HTML document (with the HTML tags in the right order). 15 | 16 | 3. Then, print the value of `html_document` on the console. 17 | 18 | ## 💡 Hint: 19 | 20 | + Expected Result: 21 | 22 | ```html 23 | 24 | ``` 25 | 26 | -------------------------------------------------------------------------------- /exercises/07-Create-a-Basic-HTML/app.py: -------------------------------------------------------------------------------- 1 | a = '' 2 | b = '' 3 | c = '' 4 | d = '' 5 | e = '' 6 | f = '' 7 | g = '' 8 | h = '<body>' 9 | 10 | # ❌ ⬆ DON'T CHANGE THE CODE ABOVE ⬆ ❌ 11 | 12 | # ✅ ↓ start coding below here ↓ ✅ 13 | 14 | -------------------------------------------------------------------------------- /exercises/07-Create-a-Basic-HTML/solution.hide.py: -------------------------------------------------------------------------------- 1 | a = '' 2 | b = '' 3 | c = '' 4 | d = '' 5 | e = '' 6 | f = '' 7 | g = '' 8 | h = '<body>' 9 | 10 | # ❌ ⬆ DON'T CHANGE THE CODE ABOVE ⬆ ❌ 11 | 12 | # ✅ ↓ start coding below here ↓ ✅ 13 | 14 | html_document = e + c + g + a + f + h + d + b 15 | print(html_document) 16 | -------------------------------------------------------------------------------- /exercises/07-Create-a-Basic-HTML/test.py: -------------------------------------------------------------------------------- 1 | import io, sys, os, re, pytest 2 | sys.stdout = buffer = io.StringIO() 3 | import app 4 | 5 | @pytest.mark.it("Create a variable named html_document") 6 | def test_html_document_exists(): 7 | try: 8 | from app import html_document 9 | except ImportError: 10 | raise ImportError("The variable 'html_document' should exist on app.py") 11 | 12 | @pytest.mark.it("The value of html_document should be the expected") 13 | def test_html_document_exists(): 14 | try: 15 | from app import html_document 16 | assert html_document == '<html><head><title>' 17 | except ImportError: 18 | raise ImportError("The variable 'html_document' should exist on app.py") 19 | 20 | @pytest.mark.it('Concatenate all the variables together (in the right order) to set the value of html_document') 21 | def test_for_concat(): 22 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 23 | with open(path, 'r') as content_file: 24 | content = content_file.read() 25 | _regex = r"html_document(\s*)=(\s*)e(\s*)\+(\s*)c(\s*)\+(\s*)g(\s*)\+(\s*)a(\s*)\+(\s*)f(\s*)\+(\s*)h(\s*)\+(\s*)d(\s*)\+(\s*)b" 26 | regex = re.compile(_regex) 27 | assert bool(regex.search(content)) == True 28 | 29 | 30 | @pytest.mark.it('Print a basic html layout on the console like this: ') 31 | def test_for_file_output(): 32 | captured = buffer.getvalue() 33 | assert "\n" in captured #add \n because the console jumps the line on every print 34 | -------------------------------------------------------------------------------- /exercises/08.1-Your-First-If/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=n5skqOQfQ84" 3 | --- 4 | 5 | # `08.1` Your First If... 6 | 7 | La aplicación actual está preguntando cuánto dinero tiene el usuario. Una vez el usuario ingresa la cantidad, debemos 'imprimir' usando **print** una de las siguientes respuestas: 8 | 9 | ## 📝 Instrucciones: 10 | 11 | 1. Si el usuario tiene más de $100, respondemos: "Give me your money!" (¡Dame tu dinero!). 12 | 13 | 2. Si el usuario tiene más de $50, respondemos: "Buy me some coffee, you cheap!" (¡Cómprame un café!). 14 | 15 | 3. Si el usuario tiene igual o menos de $50, respondemos: "You are a poor guy, go away!" (¡Eres pobre!). 16 | 17 | ## 💡 Pistas: 18 | 19 | + Usa un condicional `if...else` para verificar el valor de la variable `total`. 20 | 21 | + Puedes leer más al respecto [aquí](https://docs.python.org/3/tutorial/controlflow.html#if-statements). 22 | 23 | + Aquí tienes un recordatorio sobre los operadores relacionales: 24 | 25 | | Operador | Descripción | Sintaxis | 26 | |----------|------------------------------------------------------------------------------|----------| 27 | | > | Mayor que: True si el operando izquierdo es mayor que el derecho | x > y | 28 | | < | Menor que: True si el operando izquierdo es menor que el derecho | x < y | 29 | | == | Igual a: True si ambos operandos son iguales | x == y | 30 | | != | No igual a: True si los operandos no son iguales | x != y | 31 | | >= | Mayor o igual que: True si el operando izquierdo es mayor o igual | x >= y | 32 | | <= | Menor o igual que: True si el operando izquierdo es menor o igual | x <= y | 33 | -------------------------------------------------------------------------------- /exercises/08.1-Your-First-If/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=x9wqa5WQZiM" 3 | --- 4 | 5 | # `08.1` Your First If... 6 | 7 | The current application is asking how much money the user has. Once the user inputs the amount, we need to **print** one of the following answers: 8 | 9 | ## 📝 Instructions: 10 | 11 | 1. If the user has more than $100, we answer: "Give me your money!". 12 | 13 | 2. If the user has more than $50, we answer: "Buy me some coffee, you cheap!". 14 | 15 | 3. If the user has less than or equal to $50, we answer: "You are a poor guy, go away!". 16 | 17 | ## 💡 Hints: 18 | 19 | + Use an `if...else` statement to check the value of the `total` variable. 20 | 21 | + Further information [here](https://docs.python.org/3/tutorial/controlflow.html#if-statements). 22 | 23 | + Here's a quick reminder on relational operators: 24 | 25 | | Operator | Description | Syntax | 26 | |----------|------------------------------------------------------------------------|-----------| 27 | | > | Greater than: True if the left operand is greater than the right | x > y | 28 | | < | Less than: True if the left operand is less than the right | x < y | 29 | | == | Equal to: True if both operands are equal | x == y | 30 | | != | Not equal to: True if operands are not equal | x != y | 31 | | >= | Greater than or equal to: True if the left operand is greater or equal | x >= y | 32 | | <= | Less than or equal to: True if the left operand is less or equal | x <= y | 33 | -------------------------------------------------------------------------------- /exercises/08.1-Your-First-If/app.py: -------------------------------------------------------------------------------- 1 | total = int(input('How much money do you have in your pocket\n')) 2 | 3 | # ✅ ↓ YOUR CODE HERE ↓ ✅ 4 | -------------------------------------------------------------------------------- /exercises/08.1-Your-First-If/solution.hide.py: -------------------------------------------------------------------------------- 1 | total = int(input('How much money do you have in your pocket\n')) 2 | 3 | # ✅ ↓ YOUR CODE HERE ↓ ✅ 4 | if total > 100: 5 | print("Give me your money!") 6 | elif total > 50: 7 | print("Buy me some coffee, you cheap!") 8 | else: 9 | print("You are a poor guy, go away!") 10 | -------------------------------------------------------------------------------- /exercises/08.1-Your-First-If/test.py: -------------------------------------------------------------------------------- 1 | # from app import my_function 2 | import pytest,os,re,io,sys, mock, json 3 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 4 | 5 | @pytest.mark.it('Use the if statement') 6 | def test_for_print(capsys): 7 | with open(path, 'r') as content_file: 8 | content = content_file.read() 9 | regex = re.compile(r"if\s*") 10 | assert bool(regex.search(content)) == True 11 | 12 | @pytest.mark.it('Use the elif statement') 13 | def test_for_print(capsys): 14 | with open(path, 'r') as content_file: 15 | content = content_file.read() 16 | regex = re.compile(r"if\s*") 17 | regex2 = re.compile(r"elif\s*") 18 | assert ((bool(regex.search(content)) == True) and (bool(regex2.search(content))==True)) 19 | 20 | @pytest.mark.it('Use the function print()') 21 | def test_for_print(capsys): 22 | with open(path, 'r') as content_file: 23 | content = content_file.read() 24 | regex = re.compile(r"print\s*\(") 25 | assert bool(regex.search(content)) == True 26 | 27 | @pytest.mark.it("When input for more than 100 it should print: Give me your money!") 28 | def test_for_output_when_101(stdin, capsys, app): 29 | with mock.patch('builtins.input', lambda x: 101): 30 | app() 31 | captured = capsys.readouterr() 32 | assert "Give me your money!\n" in captured.out 33 | 34 | @pytest.mark.it("When input exactly 100 should print: Buy me some coffee, you cheap!") 35 | def test_for_output_when_100(capsys, app): 36 | with mock.patch('builtins.input', lambda x: 100): 37 | app() 38 | captured = capsys.readouterr() 39 | assert "Buy me some coffee, you cheap!\n" in captured.out 40 | 41 | @pytest.mark.it("When input is 99 should print: Buy me some coffee, you cheap!") 42 | def test_for_output_when_99(capsys, app): 43 | with mock.patch('builtins.input', lambda x: 99): 44 | app() 45 | captured = capsys.readouterr() 46 | assert "Buy me some coffee, you cheap!\n" in captured.out 47 | 48 | @pytest.mark.it("When input is 51 should print: Buy me some coffee, you cheap!") 49 | def test_for_output_when_51(capsys, app): 50 | with mock.patch('builtins.input', lambda x: 51): 51 | app() 52 | captured = capsys.readouterr() 53 | assert "Buy me some coffee, you cheap!\n" in captured.out 54 | 55 | @pytest.mark.it("When input exactly 50 should print: You are a poor guy, go away!") 56 | def test_for_output_when_50(capsys, app): 57 | with mock.patch('builtins.input', lambda x: 50): 58 | app() 59 | captured = capsys.readouterr() 60 | assert "You are a poor guy, go away!\n" in captured.out 61 | 62 | @pytest.mark.it("When input less than 50 should print: You are a poor guy, go away!") 63 | def test_for_output_when_49(capsys, app): 64 | with mock.patch('builtins.input', lambda x: 49): 65 | app() 66 | captured = capsys.readouterr() 67 | assert "You are a poor guy, go away!\n" in captured.out 68 | -------------------------------------------------------------------------------- /exercises/08.2-How-Much-The-Wedding-Costs/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=z3_0x8MlpFs" 3 | --- 4 | 5 | 6 | # `08.2` How Much The Wedding Costs (if...else) 7 | 8 | Aquí tenemos una tabla de precios de una compañía de catering de bodas: 9 | 10 | | # de invitados | Precio | 11 | | --------------------- | --------- | 12 | | Hasta 50 personas | $4,000 | 13 | | Hasta 100 personas | $10,000 | 14 | | Hasta 200 personas | $15,000 | 15 | | Más de 200 personas | $20,000 | 16 | 17 | > Nota: Las cantidades en la tabla incluyen el número especificado. Por ejemplo, "Hasta 50 personas" incluye exactamente 50 personas. 18 | 19 | ## 📝 Instrucciones: 20 | 21 | 1. Completa el algoritmo que solicita al usuario el número de personas que asistirán a su boda e imprime el precio correspondiente en la consola. 22 | 2. Amplía el código proporcionado a la izquierda para cubrir todos los rangos posibles de invitados. 23 | 3. Asegúrate de que tu código calcule e imprima correctamente el precio en la consola según el input del usuario. 24 | 25 | Por ejemplo, si la persona dice que `20` personas van a la boda, debería costar `$4,000` dólares. 26 | 27 | ## 💡 Pista: 28 | 29 | + Usa `if...else` para dividir el código y definir el valor de la variable `price` de forma correcta. 30 | -------------------------------------------------------------------------------- /exercises/08.2-How-Much-The-Wedding-Costs/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=Wu7uK8BN4nI" 3 | --- 4 | 5 | # `08.2` How Much The Wedding Costs (if...else) 6 | 7 | Here is a table of prices for a wedding catering company: 8 | 9 | | # of guests | price | 10 | | --------------------- | --------- | 11 | | Up to 50 people | $4,000 | 12 | | Up to 100 people | $10,000 | 13 | | Up to 200 people | $15,000 | 14 | | More than 200 people | $20,000 | 15 | 16 | > Note: The quantities in the table include the specified number. For example, "Up to 50 people" is inclusive of 50. 17 | 18 | ## 📝 Instructions: 19 | 20 | 1. Complete the algorithm that prompts the user for the number of people attending their wedding and prints the corresponding price in the console. 21 | 2. Extend the given code on the left to cover all possible ranges of guests. 22 | 3. Make sure that your code correctly calculates and prints the price in the console based on the user's input. 23 | 24 | For example, if the user says that `20` people are attending to the wedding, it must cost `$4,000` dollars. 25 | 26 | ## 💡 Hint: 27 | 28 | + Use `if...else` to divide your code and set the value of the `price` variable the right way. 29 | -------------------------------------------------------------------------------- /exercises/08.2-How-Much-The-Wedding-Costs/app.py: -------------------------------------------------------------------------------- 1 | user_input = int(input('How many people are coming to your wedding?\n')) 2 | 3 | # ❌ ⬆ DON'T CHANGE THE CODE ABOVE ⬆ ❌ 4 | 5 | 6 | if user_input <= 50: 7 | price = 4000 8 | # ✅ ↓ Your code here ↓ ✅ 9 | 10 | 11 | # ❌ ↓ DON'T CHANGE THE CODE BELOW ↓ ❌ 12 | print('Your wedding will cost '+str(price)+' dollars') -------------------------------------------------------------------------------- /exercises/08.2-How-Much-The-Wedding-Costs/solution.hide.py: -------------------------------------------------------------------------------- 1 | user_input = int(input('How many people are coming to your wedding?\n')) 2 | 3 | # ❌ ⬆ DON'T CHANGE THE CODE ABOVE ⬆ ❌ 4 | 5 | if user_input <= 50: 6 | price = 4000 7 | # ✅ ↓ Your code here ↓ ✅ 8 | elif user_input <= 100: 9 | price = 10000 10 | elif user_input <= 200: 11 | price = 15000 12 | else: 13 | price = 20000 14 | 15 | # ❌ ↓ DON'T CHANGE THE CODE BELOW ↓ ❌ 16 | print('Your wedding will cost '+str(price)+' dollars') -------------------------------------------------------------------------------- /exercises/08.2-How-Much-The-Wedding-Costs/test.py: -------------------------------------------------------------------------------- 1 | # from app import my_function 2 | import pytest,os,re,io,sys, mock, json 3 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 4 | 5 | @pytest.mark.it('Use the if statement') 6 | def test_for_print(capsys): 7 | with open(path, 'r') as content_file: 8 | content = content_file.read() 9 | regex = re.compile(r"if\s*") 10 | assert bool(regex.search(content)) == True 11 | 12 | @pytest.mark.it('Use the elif statement') 13 | def test_for_print(capsys): 14 | with open(path, 'r') as content_file: 15 | content = content_file.read() 16 | regex2 = re.compile(r"elif\s*") 17 | assert bool(regex2.search(content)) == True 18 | 19 | 20 | @pytest.mark.it("Between 101 and 200 guests sould be priced 15,000") 21 | def test__between_100_and_200(capsys, app): 22 | with mock.patch('builtins.input', lambda x: 200): 23 | app() 24 | captured = capsys.readouterr() 25 | price = 15000 26 | assert "Your wedding will cost "+str(price)+" dollars\n" in captured.out 27 | 28 | 29 | @pytest.mark.it("Between 51 and 100 guests sould be priced 10,000") 30 | def test_between_101_and_51(capsys, app): 31 | with mock.patch('builtins.input', lambda x: 100): 32 | app() 33 | captured = capsys.readouterr() 34 | price = 10000 35 | assert "Your wedding will cost "+str(price)+" dollars\n" in captured.out 36 | 37 | 38 | @pytest.mark.it("Less than 50 guests, it should cost 4,000") 39 | def test_less_than_50(capsys, app): 40 | with mock.patch('builtins.input', lambda x: 50): 41 | app() 42 | captured = capsys.readouterr() 43 | price = 4000 44 | "Your wedding will cost "+str(price)+" dollars\n" in captured.out 45 | 46 | @pytest.mark.it("More than 200 guests, it should cost 20,000") 47 | def test_t(capsys, app): 48 | with mock.patch('builtins.input', lambda x: 201): 49 | app() 50 | captured = capsys.readouterr() 51 | price = 20000 52 | "Your wedding will cost "+str(price)+" dollars\n" in captured.out 53 | -------------------------------------------------------------------------------- /exercises/09-Random-Numbers/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=9IjotW64sxA" 3 | --- 4 | 5 | # `09` Random Numbers 6 | 7 | Puedes usar la función `randint()` para obtener un número entero aleatorio. `randint()` es una función interna del módulo `random` en Python3. 8 | 9 | El módulo random da acceso a varias funciones útiles y una de ellas, la función `randint()`, genera números **enteros** aleatorios entre un rango que le pasemos por parámetro, por ejemplo: `randint(num_minimo, num_maximo)`. El número mínimo y el número máximo en dicho rango son inclusivos. 10 | 11 | ## 📝 Instrucciones: 12 | 13 | 1. Actualmente, el código está devolviendo números decimales aleatorios, por favor actualiza la función en el código para hacer que devuelva un número entero (no decimal) entre 1 y 10. 14 | 15 | ## 💡 Pista: 16 | 17 | + Puedes encontrar información adicional sobre el módulo `random` aquí: https://ellibrodepython.com/numeros-aleatorios-python 18 | -------------------------------------------------------------------------------- /exercises/09-Random-Numbers/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=uYqMOZ-jFag" 3 | --- 4 | 5 | # `09` Random Numbers 6 | 7 | You can use the `randint()` function to get a random integer number. `randint()` is an inbuilt function of the `random` module in Python3. 8 | 9 | The random module offers various useful functions, including `randint()`, which generates random **whole** numbers within a given range passed as parameters. You can use it like this: `randint(min_num, max_num)`, where both the minimum and maximum numbers are included in the range. 10 | 11 | ## 📝 Instructions: 12 | 13 | 1. The code now is returning random decimal numbers, please update the function code to make it return an integer (no decimal) number between 1 and 10. 14 | 15 | ## 💡 Hint: 16 | 17 | + For additional documentation on the `random` module, visit: https://www.tutorialsteacher.com/python/random-module 18 | -------------------------------------------------------------------------------- /exercises/09-Random-Numbers/app.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def get_randomInt(): 4 | # ✅ ↓ CHANGE ONLY THIS ONE LINE BELOW ↓ ✅ 5 | random_number = random.random() 6 | return random_number 7 | 8 | print(get_randomInt()) -------------------------------------------------------------------------------- /exercises/09-Random-Numbers/solution.hide.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def get_randomInt(): 4 | # ✅ ↓ CHANGE ONLY THIS ONE LINE BELOW ↓ ✅ 5 | random_number = random.randint(1,10) 6 | return random_number 7 | 8 | print(get_randomInt()) -------------------------------------------------------------------------------- /exercises/09-Random-Numbers/test.py: -------------------------------------------------------------------------------- 1 | import io 2 | import sys 3 | sys.stdout = buffer = io.StringIO() 4 | 5 | # from app import my_function 6 | import pytest 7 | import os 8 | import re 9 | import app 10 | 11 | 12 | @pytest.mark.it("You should be printing the get_randomInt function") 13 | def test_only_change_line_5(): 14 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 15 | with open(path, 'r') as content_file: 16 | content = content_file.read() 17 | line = r"print\s*\(\s*get_randomInt\s*\(\s*\)\s*\)" 18 | regex = re.compile(line) 19 | assert bool(regex.search(content)) == True 20 | 21 | @pytest.mark.it("get_randomInt function should exist") 22 | def test_function_exists(): 23 | try: 24 | assert app.get_randomInt() 25 | except AttributeError: 26 | raise AttributeError('The function "get_randomInt" should exist') 27 | 28 | @pytest.mark.it("get_randomInt function should return a random integer between 1 and 10") 29 | def test_function_returns_random_integer(): 30 | try: 31 | for i in range(10): 32 | # only asserting if value is outside the range, else it will pass 33 | result = app.get_randomInt() 34 | assert result >= 1 and result <= 10 35 | except AttributeError: 36 | raise AttributeError('The function "get_randomInt" is returning values outside the specified range') 37 | 38 | @pytest.mark.it("get_randomInt function should NOT be returning a static integer value") 39 | # in case user returns single value between [1 and 10] 40 | def test_function_return_no_static(): 41 | try: 42 | tries = 0 43 | output = app.get_randomInt() 44 | for i in range(10): 45 | if output == app.get_randomInt(): 46 | tries+=1 47 | # only asserting if value is outside the range, else it will pass 48 | assert tries < 10 49 | except AttributeError: 50 | raise AttributeError('The function "get_randomInt" is returning a static value, not a random one') 51 | -------------------------------------------------------------------------------- /exercises/10-Calling-Your-First-Function/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=0Jxyc4eClNA" 3 | --- 4 | 5 | # `10` Calling Your First Function 6 | 7 | Las funciones son increíbles por muchas cosas, pero principalmente porque puedes encapsular tu código en piezas y reusar esas piezas muchas veces sin tener que escribir todo el código cada vez. 8 | 9 | ## 📝 Instrucciones: 10 | 11 | 1. Por favor, escribe todo tu código dentro de la función `my_main_code`. 12 | 13 | 2. La función `is_odd` está definida al inicio del código, por favor llama a esa función dentro de `my_main_code` pasándole el número `45345` e imprime el resultado en la consola. 14 | 15 | ## 🔎 Importante: 16 | 17 | + Hay una serie de ejercicios dedicados a las funciones [aquí](https://github.com/4GeeksAcademy/python-functions-programming-exercises), te recomendamos realizarlos después de hacer **tu primera función** en este ejercicio. (luego... ¡Regresa! 😃). 18 | 19 | 20 | ## 💡 Pista: 21 | 22 | + Puedes consultar esta página para obtener información adicional sobre funciones y llamadas a funciones: https://www.freecodecamp.org/espanol/news/guia-de-funciones-de-python-con-ejemplos/ 23 | -------------------------------------------------------------------------------- /exercises/10-Calling-Your-First-Function/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=6IsSSc-ne9I" 3 | --- 4 | 5 | # `10` Calling Your First Function 6 | 7 | Functions are amazing because of many things, but mainly because you can encapsulate your code in pieces and re-use those pieces several times without having to type all that code again. 8 | 9 | ## 📝 Instructions: 10 | 11 | 1. Please, write all of your code inside the `my_main_code` function. 12 | 13 | 2. The function `is_odd` is defined at the beginning of the code, please call that function inside `my_main_code` passing it the number `45345` and print the result on the console. 14 | 15 | 16 | ## 🔎 Important: 17 | 18 | There's a series of exercises dedicated to functions [here](https://github.com/4GeeksAcademy/python-functions-programming-exercises), we encourage you to go and finish those after your **first function exercise** (And then... come back! 😃). 19 | 20 | 21 | ## 💡 Hint: 22 | 23 | + Check this out for additional information on functions and function calls: https://www.w3schools.com/python/python_functions.asp 24 | -------------------------------------------------------------------------------- /exercises/10-Calling-Your-First-Function/app.py: -------------------------------------------------------------------------------- 1 | def is_odd(my_number): 2 | return (my_number % 2 != 0) 3 | 4 | 5 | def my_main_code(): 6 | # ✅ ↓ Your code here ↓ ✅ -------------------------------------------------------------------------------- /exercises/10-Calling-Your-First-Function/solution.hide.py: -------------------------------------------------------------------------------- 1 | def is_odd(my_number): 2 | return (my_number % 2 != 0) 3 | 4 | 5 | def my_main_code(): 6 | # ✅ ↓ Your code here ↓ ✅ 7 | print(is_odd(45345)) -------------------------------------------------------------------------------- /exercises/10-Calling-Your-First-Function/test.py: -------------------------------------------------------------------------------- 1 | import io, mock, pytest, os, re, sys 2 | 3 | @pytest.mark.it('The function is_odd should exist') 4 | def test_functions_existence(app): 5 | try: 6 | app.is_odd 7 | except AttributeError: 8 | raise AttributeError("The function is_odd should exist") 9 | 10 | @pytest.mark.it('The function my_main_code should exist') 11 | def test_functions_existence_main(app): 12 | try: 13 | app.my_main_code 14 | except AttributeError: 15 | raise AttributeError("The function my_main_code should exist") 16 | 17 | @pytest.mark.it('Use the function print()') 18 | def test_for_print(): 19 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 20 | with open(path, 'r') as content_file: 21 | content = content_file.read() 22 | regex = re.compile(r"print\s*\(.+\)") 23 | assert bool(regex.search(content)) == True 24 | 25 | @pytest.mark.it("Call the is_odd function and pass the value 45345") 26 | def test_call_is_odd(): 27 | with mock.patch('app.is_odd') as mocked_is_odd: 28 | from app import my_main_code 29 | my_main_code() 30 | mocked_is_odd.assert_called_with(45345) 31 | 32 | @pytest.mark.it('The console should output "True" inside the function my_main_code') 33 | def test_for_file_output(capsys): 34 | from app import my_main_code 35 | my_main_code() 36 | captured = capsys.readouterr() 37 | assert "True\n" in captured.out 38 | 39 | -------------------------------------------------------------------------------- /exercises/10.1-Creating-Your-First-Function/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=ePn8AzCG57Y" 3 | --- 4 | 5 | # `10.1` Creating Your First Function 6 | 7 | ## 📝 Instrucciones: 8 | 9 | 1. La función `add_numbers` debería devolver la suma de 2 números dados. Por favor, completa el código necesario dentro de la función para hacer que se comporte como se espera. 10 | 11 | 2. Resultado esperado: el ejercicio debería escribir el número 7 en la consola. 12 | 13 | ## 💡 Pista: 14 | 15 | + Hay una función `add_numbers` ya declarada, que está recibiendo dos parámetros (las variables `a` y `b`). Tú debes completar el contenido de la función con el código requerido para sumar la variable `a` con la variable `b` y devolver el resultado de la operación. 16 | 17 | ## 🔎 Importante: 18 | 19 | + Para practicar con más funciones, 4Geeks Academy tiene más de 20 ejercicios que se incrementan en dificultad: [https://github.com/4GeeksAcademy/python-functions-programming-exercises](https://github.com/4GeeksAcademy/python-functions-programming-exercises). 20 | 21 | ¡Inténtalos, y luego regresa! 😃 22 | 23 | -------------------------------------------------------------------------------- /exercises/10.1-Creating-Your-First-Function/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=K0aDrl41SnQ" 3 | --- 4 | 5 | # `10.1` Creating Your First Function 6 | 7 | ## 📝 Instructions: 8 | 9 | 1. The function `add_numbers` is supposed to return the sum of 2 given numbers, please complete the needed code inside the function to make it behave as expected. 10 | 11 | 2. The exercise should print the number 7 in the console. 12 | 13 | ## 💡 Hint: 14 | 15 | + There is a function `add_numbers` already declared, it receives 2 parameters (variables `a` and `b`). As a developer, you were given the task to fill the function's body with the code needed to sum variable `a` with variable `b` and return the result of that operation. 16 | 17 | ## 🔎 Important: 18 | 19 | For more practice with functions, 4Geeks Academy has more than 20 exercises that increase in difficulty: [https://github.com/4GeeksAcademy/python-functions-programming-exercises](https://github.com/4GeeksAcademy/python-functions-programming-exercises). 20 | 21 | Try them, and then come back! 😃 22 | -------------------------------------------------------------------------------- /exercises/10.1-Creating-Your-First-Function/app.py: -------------------------------------------------------------------------------- 1 | def add_numbers(a,b): 2 | # This is the function's body ✅↓ Write your code here ↓✅ 3 | 4 | 5 | # ❌ ↓ DON'T CHANGE THE CODE BELOW ↓ ❌ 6 | print(add_numbers(3,4)) 7 | -------------------------------------------------------------------------------- /exercises/10.1-Creating-Your-First-Function/solution.hide.py: -------------------------------------------------------------------------------- 1 | def add_numbers(a,b): 2 | # This is the function's body ✅↓ Write your code here ↓✅ 3 | return a + b 4 | 5 | # ❌ ↓ DON'T CHANGE THE CODE BELOW ↓ ❌ 6 | print(add_numbers(3,4)) 7 | -------------------------------------------------------------------------------- /exercises/10.1-Creating-Your-First-Function/test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import app 3 | import os 4 | import io 5 | import re 6 | import mock 7 | import sys 8 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 9 | 10 | @pytest.mark.it('The function add_numbers should exist') 11 | def test_for_function(): 12 | try: 13 | app.add_numbers 14 | except AttributeError: 15 | raise AttributeError("The function add_numbers should exist") 16 | 17 | @pytest.mark.it('Print the function in console with the values: 3, 4') 18 | def test_for_function_print(): 19 | 20 | with open(path, 'r') as content_file: 21 | content = content_file.read() 22 | regex = re.compile(r"print\s*\(\s*add_numbers\s*\(\s*3\s*,\s*4\s*\)\s*\)") 23 | assert bool(regex.search(content)) == True 24 | 25 | 26 | @pytest.mark.it('Use the function print()') 27 | def test_for_print(): 28 | with open(path, 'r') as content_file: 29 | content = content_file.read() 30 | regex = re.compile(r"print\s*\(") 31 | assert bool(regex.search(content)) == True 32 | 33 | @pytest.mark.it('Function should sum the two given numbers') 34 | def test_for_return(): 35 | from app import add_numbers 36 | result = add_numbers(3,4) 37 | assert result == 7 38 | 39 | @pytest.mark.it('Function should sum the two given numbers. Testing with different numbers') 40 | def test_for_return_2(): 41 | from app import add_numbers 42 | result = add_numbers(10,5) 43 | assert result == 15 44 | -------------------------------------------------------------------------------- /exercises/11-Create-A-New-Function/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=6LhV15O9kvQ" 3 | --- 4 | 5 | # `11` Create a New Function 6 | 7 | Como sabes, las funciones son un bloque de código útil que puedes reusar tantas veces como necesites. 8 | 9 | En el último ejercicio, tenías una función que recibía dos parámetros (dos entradas) y devolvía la suma de ellos. Así: 10 | 11 | ```py 12 | def add_numbers(a, b): 13 | print(a + b) 14 | ``` 15 | 16 | Pero Python viene con un conjunto de funciones "pre-definidas" que puedes usar, por ejemplo: 17 | 18 | ```py 19 | import random 20 | # Genera un número aleatorio dentro de un rango positivo dado 21 | 22 | r1 = random.randint(0, 10) 23 | print("Random number between 0 and 10 is % s" % (r1)) 24 | ``` 25 | 26 | Puedes usar la función `randint()` para obtener un número entero aleatorio. Esta es una función incorporada del **módulo random** en Python3. 27 | 28 | El **módulo random** te da acceso a varias funciones útiles y una de ellas es, `randint()`, capaz de generar números aleatorios. 29 | 30 | ## 📝 Instrucciones: 31 | 32 | 1. Por favor, crea una función llamada `generate_random` que devuelva un número aleatorio entre 0 y 9 cada vez que se llame. 33 | 34 | 2. Imprime el resultado que la función retorna al ser llamada. 35 | 36 | ## 💡 Pistas: 37 | 38 | + Una posible solución involucra el uso de una de dos funciones predefinidas: la función `randint` o `randrange`. 39 | 40 | + No olvides importar el módulo `random`. 41 | 42 | + Puedes consultar la documentación en: https://docs.python.org/3/library/random.html#functions-for-integers 43 | -------------------------------------------------------------------------------- /exercises/11-Create-A-New-Function/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=XazswkTqKJI" 3 | --- 4 | 5 | # `11` Create a New Function 6 | 7 | As you know, functions are useful blocks of code that you can re-use as many times as you need. In the last exercise, you had a function that received two parameters (two inputs) and returned the sum of those. Like this: 8 | 9 | ```py 10 | def add_numbers(a, b): 11 | print(a + b) 12 | ``` 13 | 14 | But Python comes with a bunch of "pre-defined" functions that you can use, for example: 15 | 16 | ```py 17 | import random 18 | # Generates a random number between a given positive range 19 | 20 | r1 = random.randint(0, 10) 21 | print("Random number between 0 and 10 is % s" % (r1)) 22 | ``` 23 | 24 | You can use the `randint()` function to get a random whole number. `randint()` is an inbuilt function of the **random module** in Python3. 25 | 26 | The **random module** gives access to various useful functions, one of them being able to generate random numbers, which is `randint()`. 27 | 28 | ## 📝 Instructions: 29 | 30 | 1. Please now create a function called `generate_random` that returns a random number between 0 and 9 every time it is called. 31 | 32 | 2. Print the result that the function call returns. 33 | 34 | ## 💡 Hints: 35 | 36 | + One possible solution involves using one out of two predefined functions: the `randint()` or `randrange()` functions. 37 | 38 | + Don't forget to import the `random` module. 39 | 40 | + You can check the documentation here: https://docs.python.org/3/library/random.html#functions-for-integers 41 | -------------------------------------------------------------------------------- /exercises/11-Create-A-New-Function/app.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | # ✅↓ Write your code here ↓✅ 4 | -------------------------------------------------------------------------------- /exercises/11-Create-A-New-Function/solution.hide.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | # ✅↓ Write your code here ↓✅ 4 | def generate_random(): 5 | result = random.randint(0,9) 6 | return result 7 | 8 | print(generate_random()) 9 | -------------------------------------------------------------------------------- /exercises/11-Create-A-New-Function/test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import app 3 | import io 4 | import os 5 | import re 6 | import sys 7 | import mock 8 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 9 | 10 | 11 | @pytest.mark.it('The function generate_random should exist') 12 | def test_function_exists(): 13 | try: 14 | from app import generate_random 15 | except ImportError: 16 | raise ImportError( 17 | "The function 'generate_random' should exist on app.py") 18 | 19 | 20 | @pytest.mark.it("The function 'generate_random' should return a random number between 0 and 9") 21 | def test_for_return(): 22 | from app import generate_random 23 | result = generate_random() 24 | assert result is not None 25 | for x in range(0, 20): 26 | result = generate_random() 27 | assert result <= 9 and result >= 0 28 | 29 | 30 | @pytest.mark.it('Use the function randinit() or randrange()') 31 | def test_for_type_random(): 32 | with open(path, 'r') as content_file: 33 | content = content_file.read() 34 | regex = re.compile(r"random.randint\s*\(") 35 | regex2 = re.compile(r"random.randrange\s*\(") 36 | assert bool(regex.search(content)) == True or bool( 37 | regex2.search(content)) == True 38 | 39 | 40 | @pytest.mark.it('You should print() the output of the function') 41 | def test_function_called_for(): 42 | captured_output = io.StringIO() 43 | sys.stdout = captured_output 44 | app.generate_random() 45 | sys.stdout = sys.__stdout__ 46 | output = captured_output.getvalue() 47 | regex = re.compile(r"\d{0,9}") 48 | assert bool(regex.search(output)) == True 49 | -------------------------------------------------------------------------------- /exercises/12-Rand-From-One-to-Twelve/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=tqZIlc1gVi8" 3 | --- 4 | 5 | # `12` Rand From One to Twelve 6 | 7 | ## 📝 Instrucciones: 8 | 9 | 1. Cambia lo que necesites cambiar para hacer que el algoritmo imprima números enteros aleatorios entre 1 y 12. 10 | 11 | 2. Esta vez, utiliza la función `randrange()`. 12 | 13 | ## 💡 Pistas: 14 | 15 | + Debería imprimir números entre 1 y 12, no entre 0 y 12. 16 | 17 | + Este ejercicio es super simple, ¡no te compliques! 😃 18 | -------------------------------------------------------------------------------- /exercises/12-Rand-From-One-to-Twelve/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=EdyMlVlNUT0" 3 | --- 4 | 5 | # `12` Rand From One to Twelve 6 | 7 | ## 📝 Instructions: 8 | 9 | 1. Change whatever you need to change to make the algorithm print random integers between 1 and 12. 10 | 11 | 2. This time use the `randrange()` function. 12 | 13 | ## 💡 Hints: 14 | 15 | + It should print between 1 and 12, not between 0 and 12. 16 | 17 | + This exercise is super simple, don't complicate yourself! 😃 18 | -------------------------------------------------------------------------------- /exercises/12-Rand-From-One-to-Twelve/app.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def get_randomInt(): 4 | # ✅↓ Write your code here ↓✅ 5 | return None 6 | 7 | # ❌ ↓ DON'T CHANGE THE CODE BELOW ↓ ❌ 8 | print(get_randomInt()) 9 | -------------------------------------------------------------------------------- /exercises/12-Rand-From-One-to-Twelve/solution.hide.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def get_randomInt(): 4 | # ✅↓ Write your code here ↓✅ 5 | random_number = random.randrange(1,13) 6 | return random_number 7 | 8 | # ❌ ↓ DON'T CHANGE THE CODE BELOW ↓ ❌ 9 | print(get_randomInt()) 10 | -------------------------------------------------------------------------------- /exercises/12-Rand-From-One-to-Twelve/test.py: -------------------------------------------------------------------------------- 1 | import io 2 | import sys 3 | sys.stdout = buffer = io.StringIO() 4 | 5 | # from app import my_function 6 | import pytest 7 | import os 8 | import app 9 | import re 10 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 11 | 12 | @pytest.mark.it('The function get_randomInt should exist') 13 | def test_function_existence(app): 14 | try: 15 | app.get_randomInt 16 | except AttributeError: 17 | raise AttributeError("The function get_randomInt should exist") 18 | 19 | @pytest.mark.it("Check that you are setting the correct values for the randrange function") 20 | def test_conditional(): 21 | with open(path, 'r') as content_file: 22 | content = content_file.read() 23 | pattern = r"random\s*\.\s*randrange\s*\(\s*1\s*,\s*13\s*\)" 24 | regex = re.compile(pattern) 25 | assert bool(regex.search(content)) == True 26 | 27 | @pytest.mark.it('The console must return numbers between 1 and 12 included') 28 | def test_print_output(capsys, app): 29 | result = app.get_randomInt() 30 | assert result >= 1 or result <= 12 31 | 32 | @pytest.mark.it('You must call the function inside the print() function') 33 | def test_function_called_for(): 34 | with open(path, 'r') as content_file: 35 | content = content_file.read() 36 | regex = re.compile(r"print\s*\(\s*get_randomInt\s*\(\s*\)\s*\)") 37 | assert bool(regex.search(content)) == True 38 | -------------------------------------------------------------------------------- /exercises/13-Your-First-Loop/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=0-vljraNvwE" 3 | --- 4 | 5 | # `13` Your First Loop 6 | 7 | ## 📝 Instrucciones: 8 | 9 | 1. Ejecuta este código, verás una cuenta de 0 a 9. 10 | 11 | 2. Corrígelo para que cuente hasta 11. 12 | 13 | ## 🔎 Importante: 14 | 15 | + Hay una serie de ejercicios dedicados a listas y bucles, te invitamos a realizarlos antes de continuar: [https://github.com/4GeeksAcademy/python-lists-loops-programming-exercises](https://github.com/4GeeksAcademy/python-lists-loops-programming-exercises). 16 | 17 | ¡Luego, regresa! 😊 18 | 19 | ## 💡 Pista: 20 | + Puedes encontrar información adicional aquí: https://tutorial.recursospython.com/bucles/ 21 | -------------------------------------------------------------------------------- /exercises/13-Your-First-Loop/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=30sizcnVdGg" 3 | --- 4 | 5 | # `13` Your First Loop 6 | 7 | ## 📝 Instructions: 8 | 9 | 1. Run this code, and you'll see a count from 0 to 9. 10 | 11 | 2. Fix it so that it counts up to 11. 12 | 13 | ## 🔎 Important: 14 | 15 | + There's a series of exercises dedicated to Lists and Loops, we encourage you to go and finish those before continuing: [https://github.com/4GeeksAcademy/python-lists-loops-programming-exercises](https://github.com/4GeeksAcademy/python-lists-loops-programming-exercises). 16 | 17 | Then, come back! 😊 18 | 19 | ## 💡 Hint: 20 | + You can find additional information on loops here: https://www.w3schools.com/python/python_for_loops.asp 21 | -------------------------------------------------------------------------------- /exercises/13-Your-First-Loop/app.py: -------------------------------------------------------------------------------- 1 | def start_counting(): 2 | for i in range(10): 3 | print(i) 4 | return i 5 | 6 | start_counting() -------------------------------------------------------------------------------- /exercises/13-Your-First-Loop/solution.hide.py: -------------------------------------------------------------------------------- 1 | def start_counting(): 2 | for i in range(12): 3 | print(i) 4 | return i 5 | 6 | start_counting() -------------------------------------------------------------------------------- /exercises/13-Your-First-Loop/test.py: -------------------------------------------------------------------------------- 1 | import io 2 | import sys 3 | sys.stdout = buffer = io.StringIO() 4 | 5 | # from app import my_function 6 | import pytest 7 | import os 8 | import app 9 | import re 10 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 11 | 12 | @pytest.mark.it('The function start_counting should exist') 13 | def test_for_function_existence(): 14 | try: 15 | app.start_counting 16 | except AttributeError: 17 | raise AttributeError('The function start_counting should exist') 18 | 19 | @pytest.mark.it('The function start_counting should return the expected output') 20 | def test_for_function_output(capsys): 21 | app.start_counting() 22 | captured = capsys.readouterr() 23 | assert "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n" in captured.out 24 | 25 | @pytest.mark.it('Use a for loop') 26 | def test_for_loop(): 27 | with open(path, 'r') as content_file: 28 | content = content_file.read() 29 | regex = re.compile(r"for\s*") 30 | assert bool(regex.search(content)) == True 31 | -------------------------------------------------------------------------------- /exercises/14-Create-A-For-Loop/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=ckSAqxzi5vs" 3 | --- 4 | 5 | # `14` Create A For Loop 6 | 7 | Los bucles o loops son muy útiles. No tienes que reescribir las mismas líneas muchas veces. 8 | 9 | El bucle o loop `for` te permite ejecutar el mismo código varias veces para diferentes valores. 10 | 11 | ## 📝 Instrucciones: 12 | 13 | 1. Completa la función llamada `standards_maker()`. 14 | 15 | 2. La función tiene que imprimir 300 veces la frase "Haré preguntas si estoy atascado". 16 | 17 | 3. Llama a la función `standards_maker()`. 18 | 19 | ## 💡 Pista: 20 | 21 | + Puedes usar la función `range()` para el ciclo `for`. 22 | 23 | ## 🔎 Importante: 24 | 25 | + Puedes leer más al respecto aquí: https://ellibrodepython.com/for-python 26 | -------------------------------------------------------------------------------- /exercises/14-Create-A-For-Loop/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=-HQtwsBnbMQ" 3 | --- 4 | 5 | # `14` Create A For Loop 6 | 7 | Loops are very useful. You don't have to rewrite the same lines many times. 8 | 9 | The `for` loop lets you run the same code for different values. 10 | 11 | ## 📝 Instructions: 12 | 13 | 1. Complete the function called `standards_maker`. 14 | 15 | 2. The function has to print 300 times the phrase "I will ask questions if I am stuck". 16 | 17 | 3. Call the function `standards_maker()`. 18 | 19 | ## 💡 Hint: 20 | 21 | + You can use the `range()` function in the for loop. 22 | 23 | ## 🔎 Important: 24 | 25 | + Read more on loops: https://www.w3schools.com/python/python_for_loops.asp 26 | -------------------------------------------------------------------------------- /exercises/14-Create-A-For-Loop/app.py: -------------------------------------------------------------------------------- 1 | def standards_maker(): 2 | # ✅↓ Write your code here ↓✅ 3 | 4 | 5 | # ✅↓ remember to call the function outside (here) ↓✅ 6 | -------------------------------------------------------------------------------- /exercises/14-Create-A-For-Loop/solution.hide.py: -------------------------------------------------------------------------------- 1 | def standards_maker(): 2 | # ✅↓ Write your code here ↓✅ 3 | for i in range(0, 300): 4 | print("I will ask questions if I am stuck") 5 | 6 | # ✅↓ remember to call the function outside (here) ↓✅ 7 | standards_maker() 8 | -------------------------------------------------------------------------------- /exercises/14-Create-A-For-Loop/test.py: -------------------------------------------------------------------------------- 1 | import io 2 | import sys 3 | sys.stdout = buffer = io.StringIO() 4 | 5 | # from app import my_function 6 | import pytest 7 | import os 8 | import app 9 | import re 10 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 11 | 12 | @pytest.mark.it("You should define a function named standards_maker") 13 | def test_variable_exists(): 14 | try: 15 | from app import standards_maker 16 | except ImportError: 17 | raise ImportError("The function 'standards_maker' should exist on app.py") 18 | 19 | @pytest.mark.it('You should use a for loop') 20 | def test_for_loop(): 21 | with open(path, 'r') as content_file: 22 | content = content_file.read() 23 | regex = re.compile(r"for") 24 | assert bool(regex.search(content)) == True 25 | 26 | @pytest.mark.it("In the function standards_maker include a for loop which prints the string in the instructions 300 times") 27 | def test_for_file_output(capsys): 28 | captured = buffer.getvalue() 29 | expected = ["I will ask questions if I am stuck\n" for x in range(300)] 30 | expected_2 = ["Haré preguntas si estoy atascado\n" for x in range(300)] 31 | 32 | hasCorrectAnswer = ((captured == "".join(expected)) or (captured == "".join(expected_2))) 33 | 34 | assert hasCorrectAnswer #add \n because the console jumps the line on every print 35 | 36 | @pytest.mark.it('Use the function print()') 37 | def test_for_print(): 38 | with open(path, 'r') as content_file: 39 | content = content_file.read() 40 | regex = re.compile(r"print\s*\(.+\)") 41 | assert bool(regex.search(content)) == True 42 | 43 | @pytest.mark.it("You should call the function standards_maker") 44 | def test_callTheFunction(): 45 | with open(path, 'r') as content_file: 46 | content = content_file.read() 47 | pattern = r"standards_maker\(\)" 48 | regex = re.compile(pattern) 49 | assert bool(regex.search(content)) == True 50 | -------------------------------------------------------------------------------- /exercises/15-Looping-With-FizzBuzz/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=VkAccivrOPM" 3 | --- 4 | 5 | # `15` Looping With FizzBuzz 6 | 7 | Esta es una típica prueba de principiante que es exigida para las entrevistas en Google, Facebook y las demás grandes compañías de tecnología. 8 | 9 | ## 📝 Instrucciones: 10 | 11 | 1. Escribe el código necesario para imprimir en la consola todos los números del 1 al 100. 12 | 13 | 2. Para múltiplos de 3, en lugar de imprimir el número, imprime "Fizz". 14 | 15 | 3. Para múltiplos de 5, imprime "Buzz". 16 | 17 | 4. Para números que son múltiplos de 3 y de 5, imprime "FizzBuzz". 18 | 19 | ## 💻 Resultado esperado: 20 | 21 | ```py 22 | 1 23 | 2 24 | Fizz 25 | 4 26 | Buzz 27 | Fizz 28 | 7 29 | 8 30 | Fizz 31 | Buzz 32 | 11 33 | Fizz 34 | 13 35 | 14 36 | FizzBuzz 37 | 16 38 | .... 39 | .... 40 | 98 41 | Fizz 42 | Buzz 43 | ``` 44 | 45 | ## 🔎 Importante: 46 | 47 | Hay una serie de ejercicios dedicados a listas y bucles, te invitamos a realizarlos antes de continuar: [https://github.com/4GeeksAcademy/python-lists-loops-programming-exercises](https://github.com/4GeeksAcademy/python-lists-loops-programming-exercises). 48 | 49 | ¡Luego, regresa! 😊 50 | 51 | 52 | ## 💡 Pistas: 53 | 54 | + Debes usar instrucciones `if`. 55 | 56 | + Piensa en el orden correcto de esos `if` para hacer que tu código haga lo que quieres. 57 | 58 | -------------------------------------------------------------------------------- /exercises/15-Looping-With-FizzBuzz/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=fw3ukgmlSwQ" 3 | --- 4 | 5 | # `15` Looping With FizzBuzz 6 | 7 | This is a typical beginner test that is required to complete interviews at Google, Facebook and all the other big tech companies. 8 | 9 | ## 📝 Instructions: 10 | 11 | 1. Write the code needed to print in the console all the numbers from 1 to 100. 12 | 13 | 2. For multiples of 3, instead of the number, print "Fizz". 14 | 15 | 3. For multiples of 5, print "Buzz". 16 | 17 | 4. For numbers that are multiples of both 3 and 5, print "FizzBuzz". 18 | 19 | ## 💻 Expected result: 20 | 21 | ```py 22 | 1 23 | 2 24 | Fizz 25 | 4 26 | Buzz 27 | Fizz 28 | 7 29 | 8 30 | Fizz 31 | Buzz 32 | 11 33 | Fizz 34 | 13 35 | 14 36 | FizzBuzz 37 | 16 38 | .... 39 | .... 40 | 98 41 | Fizz 42 | Buzz 43 | ``` 44 | 45 | 46 | ## 🔎 Important: 47 | 48 | There's a series of exercises dedicated to Lists and Loops, we encourage you to go and finish them before continuing: [https://github.com/4GeeksAcademy/python-lists-loops-programming-exercises](https://github.com/4GeeksAcademy/python-lists-loops-programming-exercises) 49 | 50 | Then, come back! 😊 51 | 52 | ## 💡 Hint: 53 | 54 | + You have to use multiple `if` statements. 55 | 56 | + Think about the correct order of the different `if` statements to make the code do what you want. 57 | -------------------------------------------------------------------------------- /exercises/15-Looping-With-FizzBuzz/app.py: -------------------------------------------------------------------------------- 1 | def fizz_buzz(): 2 | # ✅↓ Write your code here ↓✅ 3 | 4 | # ❌↓ DON'T CHANGE THE CODE BELOW ↓❌ 5 | fizz_buzz() 6 | -------------------------------------------------------------------------------- /exercises/15-Looping-With-FizzBuzz/solution.hide.py: -------------------------------------------------------------------------------- 1 | def fizz_buzz(): 2 | # ✅↓ Write your code here ↓✅ 3 | for i in range(1, 101): 4 | if i % 3 == 0 and i % 5 == 0: 5 | print("FizzBuzz") 6 | elif i % 3 == 0: 7 | print("Fizz") 8 | elif i % 5 == 0: 9 | print("Buzz") 10 | else: 11 | print(i) 12 | 13 | # ❌↓ DON'T CHANGE THE CODE BELOW ↓❌ 14 | fizz_buzz() 15 | -------------------------------------------------------------------------------- /exercises/15-Looping-With-FizzBuzz/test.py: -------------------------------------------------------------------------------- 1 | import io 2 | import sys 3 | sys.stdout = buffer = io.StringIO() 4 | from app import fizz_buzz 5 | # from app import my_function 6 | import pytest 7 | import app 8 | import os 9 | import re 10 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 11 | 12 | @pytest.mark.it('The function fizz_buzz should exist') 13 | def test_function_existence(): 14 | try: 15 | app.fizz_buzz 16 | except AttributeError: 17 | raise AttributeError('The function fizz_buzz should exist') 18 | 19 | @pytest.mark.it('Use a for loop') 20 | def test_for_loop(): 21 | with open(path, 'r') as content_file: 22 | content = content_file.read() 23 | regex = re.compile(r"for\s*") 24 | assert bool(regex.search(content)) == True 25 | 26 | @pytest.mark.it('Your function needs to print the correct output') 27 | def test_for_function_output(capsys): 28 | fizz_buzz() 29 | captured = capsys.readouterr() 30 | assert "1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n13\n14\nFizzBuzz\n16\n17\nFizz\n19\nBuzz\nFizz\n22\n23\nFizz\nBuzz\n26\nFizz\n28\n29\nFizzBuzz\n31\n32\nFizz\n34\nBuzz\nFizz\n37\n38\nFizz\nBuzz\n41\nFizz\n43\n44\nFizzBuzz\n46\n47\nFizz\n49\nBuzz\nFizz\n52\n53\nFizz\nBuzz\n56\nFizz\n58\n59\nFizzBuzz\n61\n62\nFizz\n64\nBuzz\nFizz\n67\n68\nFizz\nBuzz\n71\nFizz\n73\n74\nFizzBuzz\n76\n77\nFizz\n79\nBuzz\nFizz\n82\n83\nFizz\nBuzz\n86\nFizz\n88\n89\nFizzBuzz\n91\n92\nFizz\n94\nBuzz\nFizz\n97\n98\nFizz\nBuzz\n" in captured.out 31 | -------------------------------------------------------------------------------- /exercises/16-Random-Colors-Loop/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=jYK2i0_dtns" 3 | --- 4 | 5 | 6 | # `16` Random Colors (Loop) 7 | 8 | Hemos creado una función que devuelve un color basado en un número entre 0 y 3 (cualquier otro número retornará el color `black`). 9 | 10 | Supongamos que somos profesores en un aula con 10 estudiantes y queremos asignar a **cada estudiante** un color aleatorio entre `red`, `yellow`, `blue` y `green`. 11 | 12 | (solo 1 color por estudiante) 13 | 14 | ## 📝 Instrucciones: 15 | 16 | 1. Cambia la función `get_allStudentColors` para que devuelva una lista con 10 colores, en donde cada elemento de la lista representa el color asignado a cada estudiante. 17 | 18 | ## 💡 Pistas: 19 | 20 | + Tienes 10 estudiantes, necesitas que el ciclo itere 10 veces y añadir estos valores a una lista. 21 | 22 | + En cada iteración, genera un número aleatorio entre 0 y 3 usando la función `randint()` que hemos visto en ejercicios anteriores. 23 | 24 | + Usa la función `get_color` en este ejercicio, para saber qué color le corresponde al número obtenido. 25 | 26 | + Llama (ejecuta) la función `get_allStudentColors` e imprime su resultado en la consola. 27 | -------------------------------------------------------------------------------- /exercises/16-Random-Colors-Loop/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=8zH3JT3AuAw" 3 | --- 4 | 5 | # `16` Random Colors (Loop) 6 | 7 | We have created a function that returns a color based on a number between 0 and 3 (for any different number, it will return the color `black`). 8 | 9 | Let's say that we are teachers in a 10 student classroom, and we want to randomly assign ONE color, between `red`, `yellow`, `blue` and `green`, to EACH student. 10 | 11 | (only 1 color per student) 12 | 13 | ## 📝 Instructions: 14 | 15 | 1. Change the function `get_allStudentColors` so it returns a list of 10 colors, where each item in the list represents the color assigned to each student. 16 | 17 | ## 💡 Hints: 18 | 19 | - You have 10 students, you need the loop to iterate 10 times and add these values to a list. 20 | 21 | - In each iteration, generate a random number between 0 and 3 using the `randint()` function that we have seen in previous exercises. 22 | 23 | - Use the `get_color` function in this exercise, to find out what color corresponds to the number obtained. 24 | 25 | - Call (execute) the function `get_allStudentColors` and print its result in the console. 26 | -------------------------------------------------------------------------------- /exercises/16-Random-Colors-Loop/app.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def get_color(color_number=4): 4 | # Making sure is a number and not a string 5 | color_number = int(color_number) 6 | 7 | switcher = { 8 | 0:'red', 9 | 1:'yellow', 10 | 2:'blue', 11 | 3:'green', 12 | 4:'black' 13 | } 14 | 15 | return switcher.get(color_number,"Invalid Color Number") 16 | 17 | # ❌ ⬆ DON'T CHANGE THE CODE ABOVE ⬆ ❌ 18 | 19 | def get_allStudentColors(): 20 | example_color = get_color(1) 21 | students_array = [] 22 | # ✅ ↓ your loop here ↓ ✅ 23 | 24 | 25 | print(get_allStudentColors()) 26 | -------------------------------------------------------------------------------- /exercises/16-Random-Colors-Loop/solution.hide.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def get_color(color_number=4): 4 | # Making sure is a number and not a string 5 | color_number = int(color_number) 6 | 7 | switcher = { 8 | 0:'red', 9 | 1:'yellow', 10 | 2:'blue', 11 | 3:'green', 12 | 4:'black' 13 | } 14 | 15 | return switcher.get(color_number,"Invalid Color Number") 16 | 17 | # ❌ ⬆ DON'T CHANGE THE CODE ABOVE ⬆ ❌ 18 | 19 | def get_allStudentColors(): 20 | example_color = get_color(1) 21 | students_array = [] 22 | # ✅ ↓ your loop here ↓ ✅ 23 | for i in range(10): 24 | students_array.append(get_color(random.randint(0,3))) 25 | 26 | return students_array 27 | 28 | 29 | print(get_allStudentColors()) 30 | -------------------------------------------------------------------------------- /exercises/16-Random-Colors-Loop/test.py: -------------------------------------------------------------------------------- 1 | import io 2 | import sys 3 | sys.stdout = buffer = io.StringIO() 4 | 5 | # from app import my_function 6 | import pytest 7 | import app 8 | import os 9 | import re 10 | 11 | @pytest.mark.it('Function get_color should exist') 12 | def test_get_color_exists(capsys, app): 13 | try: 14 | app.get_color 15 | except AttributeError: 16 | raise AttributeError("The function 'get_color' should exist on app.py") 17 | @pytest.mark.it('Function get_allStudentColors should exist') 18 | def test_get_allStudentColors_exists(capsys, app): 19 | try: 20 | app.get_allStudentColors 21 | except AttributeError: 22 | raise AttributeError("The function 'get_allStudentColors' should exist on app.py") 23 | 24 | @pytest.mark.it('Function get_allStudentColors should return ten colors') 25 | def test_ten_colors(capsys, app): 26 | result = app.get_allStudentColors() 27 | assert len(result) == 10 28 | 29 | @pytest.mark.it("Function get_allStudentColors shouldn't return an array with the black color") 30 | def test_black_in_array(capsys, app): 31 | result = app.get_allStudentColors() 32 | assert result.count("black") == 0 33 | 34 | @pytest.mark.it('You should use a for loop to iterate 10 times') 35 | def use_for_loop(capsys): 36 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 37 | with open(path, 'r') as content_file: 38 | content = content_file.read() 39 | pattern = r"for\s*" 40 | regex = re.compile(pattern) 41 | assert bool(regex.search(content)) == True 42 | -------------------------------------------------------------------------------- /exercises/17-Russian-Roulette/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=KqO8ebdqs5I" 3 | --- 4 | 5 | # `17` Russian Roulette 6 | 7 | ¿Has jugado a la ruleta rusa? ¡Es muy divertido! Si no pierdes... (¡¡¡muuuajajajaja!!!). 8 | 9 | Un revolver tiene seis recámaras para balas... inserta una bala en una de las recámaras, gira el tambor del revolver para hacer aleatorio el juego. Nadie sabrá dónde está la bala. 10 | 11 | ¡¡¡FUEGO!!!...... ¿Has muerto? 12 | 13 | ## 📝 Instrucciones: 14 | 15 | 1. El juego casi funciona, por favor completa la función `fire_gun` para que el juego funcione. 16 | 17 | 2. Compara la posición de la bala con la posición de la recámara. 18 | 19 | 3. Si la posición de la bala es igual a la posición de la recámara, entonces la función debe retornar `You are dead!`, de lo contrario, debe retornar `Keep playing!` 20 | 21 | ## 💡 Pistas: 22 | 23 | - Puedes obtener la posición de la recámara llamando a la función `spin_chamber`. 24 | 25 | - Si la bala está en el mismo compartimento que la recámara del revólver, entonces será disparada (`You are dead!`). 26 | -------------------------------------------------------------------------------- /exercises/17-Russian-Roulette/README.md: -------------------------------------------------------------------------------- 1 | # `17` Russian Roulette 2 | 3 | Have you ever played Russian Roulette? It's super fun! If you make it (muahahahaha). 4 | 5 | The revolver gun has only 6 slots for bullets... insert one bullet in one of the slots, spin the revolver chamber to make the game random, nobody knows the bullet position. 6 | 7 | FIRE!!!...... are you dead? 8 | 9 | ## 📝 Instructions: 10 | 11 | 1. The game is almost working, please fill the function `fire_gun` to make the game work. 12 | 13 | 2. Compare the bullet position against the chamber position. 14 | 15 | 3. If the bullet position is equal to the chamber position, then the function should return `You are dead!`, else it should return `Keep playing!` 16 | 17 | ## 💡 Hints: 18 | 19 | + You can get the chamber position by calling the `spin_chamber` function 20 | 21 | + If the bullet is at the same slot as the revolver chamber, then it will be fired (`You are dead!`). 22 | -------------------------------------------------------------------------------- /exercises/17-Russian-Roulette/app.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | bullet_position = 3 4 | 5 | def spin_chamber(): 6 | chamber_position = random.randint(1,6) 7 | return chamber_position 8 | 9 | # ❌ ⬆ DON'T CHANGE THE CODE ABOVE ⬆ ❌ 10 | def fire_gun(): 11 | # ✅ ↓ your code here ↓ ✅ 12 | return None 13 | 14 | 15 | print(fire_gun()) 16 | -------------------------------------------------------------------------------- /exercises/17-Russian-Roulette/solution.hide.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | bullet_position = 3 4 | 5 | def spin_chamber(): 6 | chamber_position = random.randint(1,6) 7 | return chamber_position 8 | 9 | # ❌ ⬆ DON'T CHANGE THE CODE ABOVE ⬆ ❌ 10 | def fire_gun(): 11 | # ✅ ↓ your loop here ↓ ✅ 12 | if spin_chamber() == bullet_position: 13 | return "You are dead!" 14 | else: 15 | return "Keep playing!" 16 | 17 | print(fire_gun()) 18 | -------------------------------------------------------------------------------- /exercises/17-Russian-Roulette/test.py: -------------------------------------------------------------------------------- 1 | import io 2 | import sys 3 | sys.stdout = buffer = io.StringIO() 4 | 5 | # from app import my_function 6 | import pytest 7 | import app 8 | import re 9 | import os 10 | 11 | @pytest.mark.it('The function spin_chamber must exist') 12 | def test_function_spin_chamber(capsys, app): 13 | assert app.spin_chamber 14 | 15 | @pytest.mark.it('The function fire_gun must exist') 16 | def test_function_fire_gun(capsys, app): 17 | assert app.fire_gun 18 | 19 | @pytest.mark.it('The function fire_gun should return the expected output in both cases') 20 | def test_function_output(capsys, app): 21 | if(app.spin_chamber() == app.bullet_position): 22 | assert app.fire_gun() == "You are dead!" 23 | else: 24 | assert app.fire_gun() == "Keep playing!" 25 | 26 | @pytest.mark.it('Your code needs to print the correct output on the console') 27 | def test_for_file_output(capsys): 28 | f = open(os.path.dirname(os.path.abspath(__file__))+'/app.py') 29 | content = f.readlines() 30 | content = [x.strip() for x in content] 31 | my_codeCall = [s for s in content[3:] if "print(fire_gun())" in s] 32 | my_codeCallVar = content.index(my_codeCall[0]) 33 | regex = r"print\(fire_gun\(\)\)" 34 | assert re.match(regex, content[my_codeCallVar]) 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /exercises/18-The-Beatles/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=0Y2mHwwQBGE" 3 | --- 4 | 5 | # `18` The Beatles 6 | 7 | ¿A quién no le gusta The Beatles? 8 | 9 | Un estudio de la BBC ha probado que el 90% de los niños y niñas no conocen la banda... muy triste. :( 10 | 11 | Este es el coro de una de las canciones más famosas de la banda: 12 | 13 | > Let it be, let it be, let it be, let it be, 14 | > 15 | > Whisper words of wisdom, 16 | > 17 | > Let it be 18 | 19 | ## 📝 Instrucciones: 20 | 21 | 1. Crea una función llamada `sing()` que imprima en consola la misma letra que puedes escuchar desde el segundo 3:21 hasta el final de la canción en el segundo 3:50 https://www.youtube.com/watch?v=QDYfEBY9NM4 22 | 23 | 2. Llama tu función al final del código. 24 | 25 | ## 💻 Resultado esperado: 26 | 27 | ```text 28 | let it be, 29 | let it be, 30 | let it be, 31 | let it be, 32 | there will be an answer, 33 | let it be, 34 | let it be, 35 | let it be, 36 | let it be, 37 | let it be, 38 | whisper words of wisdom, let it be 39 | ``` 40 | 41 | ## 💡 Pistas: 42 | 43 | + La frase "let it be" se repite todo el tiempo. Probablemente, deberías usar un bucle o loop para eso. 😊 44 | 45 | + Si necesitas un repaso sobre los loops y/o condicionales, échale un vistazo a esto: https://docs.python.org/es/3/tutorial/controlflow.html 46 | -------------------------------------------------------------------------------- /exercises/18-The-Beatles/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=cuSaRROMTDY" 3 | --- 4 | 5 | # `18` The Beatles 6 | 7 | Who does not like The Beatles? 8 | 9 | A BBC study has proved that 90% of kids don't know the band... so sad. :( 10 | 11 | This is the chorus of one of the most famous Beatles songs: 12 | 13 | > Let it be, let it be, let it be, let it be, 14 | > 15 | > Whisper words of wisdom, 16 | > 17 | > Let it be 18 | 19 | ## 📝 Instructions: 20 | 21 | 1. Create a function called `sing()` that prints on the console the lyrics that you can hear from 3:21 sec to the end of the song at 3:50 sec https://www.youtube.com/watch?v=QDYfEBY9NM4 22 | 23 | 2. Call your function at the end. 24 | 25 | ## 💻 Expected output: 26 | 27 | ```text 28 | let it be, 29 | let it be, 30 | let it be, 31 | let it be, 32 | there will be an answer, 33 | let it be, 34 | let it be, 35 | let it be, 36 | let it be, 37 | let it be, 38 | whisper words of wisdom, let it be 39 | ``` 40 | 41 | ## 💡 Hints: 42 | 43 | + The words "let it be" repeat all the time, you should probably create a loop for that. 44 | 45 | + If you need a refresher on loops and conditionals, check out this awesome resource: https://docs.python.org/3/tutorial/controlflow.html 46 | -------------------------------------------------------------------------------- /exercises/18-The-Beatles/app.py: -------------------------------------------------------------------------------- 1 | # ✅↓ Write your code here ↓✅ 2 | 3 | -------------------------------------------------------------------------------- /exercises/18-The-Beatles/solution.hide.py: -------------------------------------------------------------------------------- 1 | # ✅↓ Write your code here ↓✅ 2 | def sing(): 3 | song = "" 4 | for i in range(11): 5 | if i == 4: 6 | song += "there will be an answer,\n" 7 | elif i == 10: 8 | song += "whisper words of wisdom, let it be" 9 | else: 10 | song += "let it be,\n" 11 | return song 12 | 13 | sing() 14 | -------------------------------------------------------------------------------- /exercises/18-The-Beatles/test.py: -------------------------------------------------------------------------------- 1 | import io 2 | import sys 3 | sys.stdout = buffer = io.StringIO() 4 | 5 | # from app import my_function 6 | import pytest 7 | import app 8 | import re 9 | import os 10 | 11 | @pytest.mark.it("You should declare a function named sing()") 12 | def test_function_sing_exists(app): 13 | try: 14 | assert app.sing 15 | except AttributeError: 16 | raise AttributeError("The function 'sing' should exist on app.py") 17 | 18 | @pytest.mark.it("You should not be hard coding the output") 19 | def test_function_hardcode_output(): 20 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 21 | with open(path, 'r') as content_file: 22 | content = content_file.read() 23 | regex = re.compile(r"\breturn\s*[^\"][a-zA-Z0-9]*\b\s*") 24 | assert bool(regex.search(content)) == True 25 | 26 | @pytest.mark.it("The function sing() should return a string with the song lyrics") 27 | def test_function_sing_exists(app): 28 | try: 29 | assert app.sing() == "let it be,\nlet it be,\nlet it be,\nlet it be,\nthere will be an answer,\nlet it be,\nlet it be,\nlet it be,\nlet it be,\nlet it be,\nwhisper words of wisdom, let it be" 30 | except AttributeError: 31 | raise AttributeError("The function 'sing' should exist on app.py") 32 | -------------------------------------------------------------------------------- /exercises/19-Bottles-Of-Milk/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=iLH9Hg4PAmw" 3 | --- 4 | 5 | # `19` Bottles Of Milk 6 | 7 | ¿Has escuchado la canción sobre las 99 botellas de leche? Es una gran canción, para nada aburrida... 8 | 9 | Aquí puedes escucharla: https://www.youtube.com/watch?v=Xy-da43E6Lo 10 | 11 | ## 📝 Instrucciones: 12 | 13 | 1. Por favor, declara una función llamada `number_of_bottles()`. 14 | 15 | 2. La función necesita imprimir la letra exacta de la canción (usa el método `print()` y no `return`). 16 | 17 | ## 💻 Resultado esperado: 18 | 19 | El resultado debería ser algo como esto: 20 | 21 | ```text 22 | 99 bottles of milk on the wall, 99 bottles of milk. 23 | Take one down and pass it around, 98 bottles of milk on the wall. 24 | 25 | 98 bottles of milk on the wall, 98 bottles of milk. 26 | Take one down and pass it around, 97 bottles of milk on the wall. 27 | ... 28 | ... 29 | 2 bottles of milk on the wall, 2 bottles of milk. 30 | Take one down and pass it around, 1 bottle of milk on the wall. 31 | 32 | 1 bottle of milk on the wall, 1 bottle of milk. 33 | Take one down and pass it around, no more bottles of milk on the wall. 34 | 35 | No more bottles of milk on the wall, no more bottles of milk. 36 | Go to the store and buy some more, 99 bottles of milk on the wall. 37 | ``` 38 | 39 | ## 💡 Pistas: 40 | 41 | + Al final de la canción, la letra cambia porque es solo una botella (singular en lugar del plural). 42 | 43 | + Lee la última parte de la letra y verás como cambia la última línea a `"Go to the store and buy some more, 99 bottles of milk on the wall."`. 44 | -------------------------------------------------------------------------------- /exercises/19-Bottles-Of-Milk/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=mKNqjPh1JE0" 3 | --- 4 | 5 | # `19` Bottles Of Milk 6 | 7 | Have you ever heard the song about 99 bottles of milk? Is a great song, is not boring at all... 8 | 9 | Here you can listen to the song: https://www.youtube.com/watch?v=Xy-da43E6Lo 10 | 11 | ## 📝 Instructions: 12 | 13 | 1. Please declare a function named `number_of_bottles()`. 14 | 15 | 2. The function needs to **print** (use the `print` statement and not `return`) the exact same lyrics in the song. 16 | 17 | ## 💻 Expected result: 18 | 19 | The result should be something like this: 20 | 21 | ```text 22 | 99 bottles of milk on the wall, 99 bottles of milk. 23 | Take one down and pass it around, 98 bottles of milk on the wall. 24 | 25 | 98 bottles of milk on the wall, 98 bottles of milk. 26 | Take one down and pass it around, 97 bottles of milk on the wall. 27 | ... 28 | ... 29 | 2 bottles of milk on the wall, 2 bottles of milk. 30 | Take one down and pass it around, 1 bottle of milk on the wall. 31 | 32 | 1 bottle of milk on the wall, 1 bottle of milk. 33 | Take one down and pass it around, no more bottles of milk on the wall. 34 | 35 | No more bottles of milk on the wall, no more bottles of milk. 36 | Go to the store and buy some more, 99 bottles of milk on the wall. 37 | ``` 38 | 39 | ## 💡 Hints: 40 | 41 | + At the end of the song, the lyrics change because there is only **one** bottle (singular instead of plural). 42 | 43 | + Read the last lyrics, and you will see how the last line changes to `"Go to the store and buy some more, 99 bottles of milk on the wall."`. 44 | -------------------------------------------------------------------------------- /exercises/19-Bottles-Of-Milk/app.py: -------------------------------------------------------------------------------- 1 | # ✅↓ Write your code here ↓✅ 2 | -------------------------------------------------------------------------------- /exercises/19-Bottles-Of-Milk/solution.hide.py: -------------------------------------------------------------------------------- 1 | # ✅↓ Write your code here ↓✅ 2 | def number_of_bottles(): 3 | for x in range(99,2,-1): 4 | print(str(x) + " bottles of milk on the wall, " + str(x) + " bottles of milk. Take one down and pass it around, " + str(x-1)+ " bottles of milk on the wall.") 5 | print("2 bottles of milk on the wall, 2 bottles of milk. Take one down and pass it around, 1 bottle of milk on the wall.") 6 | print("1 bottle of milk on the wall, 1 bottle of milk. Take one down and pass it around, no more bottles of milk on the wall.") 7 | print("No more bottles of milk on the wall, no more bottles of milk. Go to the store and buy some more, 99 bottles of milk on the wall.") 8 | return None 9 | 10 | number_of_bottles() 11 | -------------------------------------------------------------------------------- /exercises/19-Bottles-Of-Milk/test.py: -------------------------------------------------------------------------------- 1 | import io 2 | import sys 3 | sys.stdout = buffer = io.StringIO() 4 | from app import number_of_bottles 5 | import pytest 6 | import os 7 | import app 8 | import re 9 | 10 | @pytest.mark.it('The function number_of_bottles must exist') 11 | def test_function_spin_chamber(capsys, app): 12 | try: 13 | app.number_of_bottles 14 | except AttributeError: 15 | raise AttributeError("The function number_of_bottles should exist") 16 | 17 | f = open(os.path.dirname(os.path.abspath(__file__))+'/app.py') 18 | content = f.readlines() 19 | my_funcCall = [s for s in content if "def number_of_bottles():" in s] 20 | my_funcCallVar = content.index(my_funcCall[0]) 21 | regex = r"def number_of_bottles\(\):" 22 | assert re.match(regex, content[my_funcCallVar]) 23 | my_printCall = [s for s in content[3:] if "number_of_bottles()" in s] 24 | my_printCallVar = content.index(my_printCall[0]) 25 | regex = r"number_of_bottles\(\)" 26 | assert re.match(regex, content[my_printCallVar]) 27 | 28 | @pytest.mark.it('The function must print the expected output') 29 | def test_for_function_output(capsys): 30 | number_of_bottles() 31 | captured = capsys.readouterr() 32 | text='' 33 | for x in range(99,-1,-1): 34 | if (x==0): 35 | text+=("No more bottles of milk on the wall, no more bottles of milk. Go to the store and buy some more, 99 bottles of milk on the wall.\n") 36 | elif (x==1): 37 | text+=("1 bottle of milk on the wall, 1 bottle of milk. Take one down and pass it around, no more bottles of milk on the wall.\n") 38 | elif (x==2): 39 | text+=("2 bottles of milk on the wall, 2 bottles of milk. Take one down and pass it around, 1 bottle of milk on the wall.\n") 40 | else: 41 | text+=(str(x) + " bottles of milk on the wall, " + str(x) + " bottles of milk. Take one down and pass it around, " + str(x-1)+ " bottles of milk on the wall.\n") 42 | 43 | assert captured.out == text 44 | 45 | -------------------------------------------------------------------------------- /learn.json: -------------------------------------------------------------------------------- 1 | 2 | { 3 | "slug": "python-beginner-programming-exercises", 4 | "title": { 5 | "us": "Learn Python Interactively (beginner)", 6 | "es": "Aprende Python Interactivamente (Principiante)" 7 | }, 8 | "intro": "https://www.youtube.com/watch?v=amyDNhZwGJQ", 9 | "repository": "https://github.com/4GeeksAcademy/python-beginner-programming-exercises", 10 | "preview": "https://github.com/4GeeksAcademy/python-beginner-programming-exercises/blob/master/.learn/assets/preview.png?raw=true", 11 | "description": { 12 | "us": "Python exercises for beginners, starting from the basics like `Hello World` to more advanced concepts like variables, loops, functions, and data structures. These hands-on challenges guide you step by step through Python programming, offering interactive and auto-graded lessons to build a solid foundation.", 13 | "es": "Ejercicios de Python para principiantes, comenzando desde lo básico como `Hola Mundo` hasta conceptos más avanzados como variables, bucles, funciones y estructuras de datos. Estos desafíos prácticos te guían paso a paso en la programación con Python, ofreciendo lecciones interactivas y autoevaluadas para construir una base sólida." 14 | }, 15 | "duration": 10, 16 | "difficulty": "easy", 17 | "videoSolutions": true, 18 | "projectType": "tutorial", 19 | "bugsLink": "https://github.com/learnpack/learnpack/issues/new", 20 | "graded": true, 21 | "technologies": ["strings", "python-functions", "conditionals", "variables", "condicionales", "funciones-de-python"], 22 | "editor": { 23 | "version": "5.0" 24 | }, 25 | "telemetry": { 26 | "batch": "https://breathecode.herokuapp.com/v1/assignment/me/telemetry?asset_id=145" 27 | }, 28 | "video": { 29 | "intro": { 30 | "es": "https://www.youtube.com/watch?v=IXNSwnN-YqM", 31 | "en": "https://www.youtube.com/watch?v=amyDNhZwGJQ" 32 | } 33 | } 34 | 35 | 36 | } 37 | --------------------------------------------------------------------------------