diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..8d6afa7 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,42 @@ + +// For format details, see https://aka.ms/devcontainer.json. For config options, see the +// README at: https://github.com/devcontainers/templates/tree/main/src/python +{ + "name": "Python 3", + // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile + "image": "mcr.microsoft.com/devcontainers/python:0-3.10", + "features": { + "ghcr.io/devcontainers/features/node:1": { + "nodeGypDependencies": true, + "version": "16" + } + }, + "customizations": { + "vscode": { + "settings": { + "editor.defaultFormatter": "esbenp.prettier-vscode", + "workbench.editorAssociations": { + "*.md": "vscode.markdown.preview.editor" + } + }, + "extensions": ["learn-pack.learnpack-vscode"] + } + }, + "onCreateCommand": "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" + + // Features to add to the dev container. More info: https://containers.dev/features. + // "features": {}, + + // Use 'forwardPorts' to make a list of ports inside the container available locally. + // "forwardPorts": [], + + // Use 'postCreateCommand' to run commands after the container is created. + // "postCreateCommand": "pip3 install --user -r requirements.txt", + + // Configure tool-specific properties. + // "customizations": {}, + + // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. + // "remoteUser": "root" +} + diff --git a/.github/workflows/learnpack-audit.yml b/.github/workflows/learnpack-audit.yml new file mode 100644 index 0000000..95814c2 --- /dev/null +++ b/.github/workflows/learnpack-audit.yml @@ -0,0 +1,29 @@ +# 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 +# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions + +name: Learnpack audit + +on: + push: + branches: [ main ] + pull_request: + branches: [ main ] + +jobs: + build: + + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: [20.x] + # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ + + steps: + - uses: actions/checkout@v2 + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v2 + with: + node-version: ${{ matrix.node-version }} + - run: npm install @learnpack/learnpack@latest -g + - run: learnpack audit \ No newline at end of file diff --git a/.gitignore b/.gitignore index f3ca55f..964585a 100644 --- a/.gitignore +++ b/.gitignore @@ -2,12 +2,15 @@ /* !.gitignore +!.devcontainer +!.devcontainer/* !.gitpod.yml !.gitpod.Dockerfile !bc.json !learn.json !README.md !README.*.md +!.vscode !/exercises !/exercises/* diff --git a/.gitpod.Dockerfile b/.gitpod.Dockerfile index 6408d52..25ac192 100644 --- a/.gitpod.Dockerfile +++ b/.gitpod.Dockerfile @@ -1,4 +1,28 @@ FROM gitpod/workspace-full:latest + +SHELL ["/bin/bash", "-c"] + +RUN sudo apt-get update \ + && sudo apt-get update \ + && sudo apt-get clean \ + && sudo rm -rf /var/cache/apt/* /var/lib/apt/lists/* /tmp/* + +# That Gitpod install pyenv for me? no, thanks +WORKDIR /home/gitpod/ +RUN rm .pyenv -Rf +RUN rm .gp_pyenv.d -Rf +RUN curl https://pyenv.run | bash + + +RUN pyenv update && pyenv install 3.10.7 && pyenv global 3.10.7 +RUN pip install pipenv + +# remove PIP_USER environment USER gitpod -RUN pip3 install pytest==4.4.2 pytest-testdox mock -RUN npm i -g learnpack && learnpack plugins:install learnpack-python +RUN if ! grep -q "export PIP_USER=no" "$HOME/.bashrc"; then printf '%s\n' "export PIP_USER=no" >> "$HOME/.bashrc"; fi +RUN echo "" >> $HOME/.bashrc +RUN echo "unset DATABASE_URL" >> $HOME/.bashrc +RUN echo "export DATABASE_URL" >> $HOME/.bashrc + +RUN pip3 install pytest==6.2.5 pytest-testdox mock +RUN npm i @learnpack/learnpack@2.1.47 -g && learnpack plugins:install @learnpack/python@1.0.3 diff --git a/.gitpod.yml b/.gitpod.yml index 2ea8d8d..1d3e46c 100644 --- a/.gitpod.yml +++ b/.gitpod.yml @@ -3,9 +3,12 @@ image: ports: - port: 3000 - onOpen: open-preview -tasks: - - command: learnpack start + onOpen: ignore + +vscode: + extensions: + - learn-pack.learnpack-vscode + github: prebuilds: # enable for the master/default branch (defaults to true) diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..2f5ad94 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,8 @@ +{ + "files.autoSave": "afterDelay", + "files.autoSaveDelay": 700, + "editor.minimap.enabled": false, + "workbench.editorAssociations": { + "*.md": "vscode.markdown.preview.editor" + } +} \ No newline at end of file diff --git a/README.es.md b/README.es.md new file mode 100644 index 0000000..70a7973 --- /dev/null +++ b/README.es.md @@ -0,0 +1,84 @@ + +# 🐍 Tutorial y Ejercicios sobre Funciones de Python +Creado por @alesanchezr y otros contribuyentes en 4Geeks Academy + + + + +Aprende y practica las funciones de Python. Vas a ver los siguientes conceptos: + +1. Declarar una función. + +2. Llamar a una función. + +3. Alcance de una función. + +4. Funciones anidadas. + +5. Recursividad de funciones y muchos otros conceptos funcionales. + +Todo el tutorial es 👆 interactivo, ✅ calificado automáticamente y con 📹 video tutoriales. + +Estos ejercicios son colaborativos, ¡te necesitamos! Si encuentras algún error o falta de ortografía, por favor contribuye y repórtalo. + + + +## Instalación en un clic (recomendado) + +Puedes empezar estos ejercicios en pocos segundos haciendo clic en: [Abrir en Codespaces](https://codespaces.new/?repo=4GeeksAcademy/python-functions-programming-exercises) (recomendado) o [Abrir en Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/python-functions-programming-exercises.git). + +> 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` + +## Instalación local: + +1. Asegúrate de instalar [LearnPack](https://learnpack.co), node.js version 14+ y Python version 3+. Este es el comando para instalar LearnPack: + +```bash +$ npm i -g @learnpack/learnpack@2.1.20 && learnpack plugins:install @learnpack/python@1.0.0 +``` + +2. Clona o descarga este repositorio en tu ambiente local. + +```bash +$ git clone https://github.com/4GeeksAcademy/python-functions-programming-exercises.git +$ cd python-functions-programming-exercises +``` + +> Nota: Una vez que termine de descargar, encontrarás la carpeta "exercises" que contiene todos los ejercicios. + +3. Comienza el tutorial/ejercicios ejecutando el siguiente comando en la raíz del proyecto: + +```bash +$ pip3 install pytest==6.2.5 pytest-testdox mock +$ learnpack start +``` + + + +## ¿Cómo están organizados los ejercicios? + +Cada ejercicio es un pequeño proyecto en Python que contiene los siguientes archivos: + +1. **app.py:** representa el archivo de entrada de Python que será ejecutado en el computador. +2. **README.md:** contiene las instrucciones del ejercicio. +3. **test.py:** no tienes que abrir este archivo, contiene los scripts de pruebas del ejercicio. + +> 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. + +## Colaboradores + +Gracias a estas personas maravillosas ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): + +1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribución: (programador) 💻, (idea) 🤔, (build-tests) ⚠️, (pull-request-review) 👀, (build-tutorial) ✅, (documentación) 📖 + +2. [Paolo (plucodev)](https://github.com/plucodev), contribución: (bug reports) 🐛, (programador) 💻, (traducción) 🌎 + +3. [Marco Gómez (marcogonzalo)](https://github.com/marcogonzalo), contribution: (bug reports) 🐛, (traducción) 🌎 + +Este proyecto sigue la especificación [all-contributors](https://github.com/kentcdodds/all-contributors). + +¡Todas las contribuciones son bienvenidas! + +Este proyecto sigue la especificación [all-contributors](https://github.com/kentcdodds/all-contributors). ¡Todas las contribuciones son bienvenidas! + +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). diff --git a/README.md b/README.md index 3c46c2f..18994a9 100644 --- a/README.md +++ b/README.md @@ -1,82 +1,86 @@ - - - - - -
-

🐍 Python Funtions Tutorial and Exercises

-

By @alesanchezr and other contributors at 4Geeks Academy

- - - follow on Twitter - -
- -Learn and practice Python Functions: Declaring a functoin, Calling a function, function scopes, nest functions, function recursivity and many other functional concepts. The entire tutorial is 👆 interactive, ✅ auto-graded and with. 📹 video tutorials. - -

📚 Table of contents:

- - - - - - - - - - - - -
1. Python for Beginners
2. Practice Looping Lists and Tuples
3. Practice functions← 🔥 your are here now
4. Master Python (intermediate)
5. Python API Requests
6. What next? Request a new tutorial or collaborate.
We will feature your profile in our list of contributors
- -These exercises were built in collaboration, we need you! If you find any bugs or misspells plese contribute and report them. - -

- -

- -

One click installation:

- -[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io#https://github.com/4GeeksAcademy/python-functions-programming-exercises.git) + +# 🐍 Python Functions Tutorial and Exercises +By @alesanchezr and other contributors at 4Geeks Academy + + + + +*Estas instrucciones [están disponibles en 🇪🇸 español](https://github.com/4GeeksAcademy/python-functions-programming-exercises/blob/master/README.es.md) :es:* + +Learn and practice Python Functions. You will see the following concepts: + +1. Declaring a function. + +2. Calling a function. + +3. Function scopes. + +4. Nest functions. + +5. Recursive functions and many other functional concepts. + +> Note: The entire tutorial is 👆 interactive, ✅ auto-graded and with 📹 video tutorials. + +These exercises were built in collaboration, we need you! If you find any bugs or misspellings, please contribute and report them. + + + +## One click installation (recommended): + +You can open these exercises in just a few seconds by clicking: [Open in Codespaces](https://codespaces.new/?repo=4GeeksAcademy/python-functions-programming-exercises) (recommended) or [Open in Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/python-functions-programming-exercises). + +> 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` ## Local Installation -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: -``` -$ npm i learnpack -g && learnpack plugins:install learnpack-python +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: + +```bash +$ npm i -g @learnpack/learnpack@2.1.20 && learnpack plugins:install @learnpack/python@1.0.0 ``` -2) Clone or download this repository. Once you finish downloading, you will find a new folder with a subdirectory "exercises" that contains all the exercises within. +2. Clone or download this repository in your local environment. -``` +```bash $ git clone https://github.com/4GeeksAcademy/python-functions-programming-exercises.git +$ cd python-functions-programming-exercises ``` -3) Start the tutorial/exercises by running the following command from the root of the project: +> Note: Once you finish downloading, you will find an "exercises" folder that contains all the exercises within. -```sh -$ cd python-functions-programming-exercises -$ pip install pytest==4.4.2 mock pytest-testdox +3. Start the tutorial/exercises by running the following command from the root of the project: + +```bash +$ pip3 install pytest==6.2.5 pytest-testdox mock $ learnpack start ``` + + ## How are the exercises organized? -Each exercise is a small react application containing the following files: +Each exercise is a small Python application containing the following files: -1. **app.py:** represents the entry python file that will be executed by the computer. +1. **app.py:** represents the entry Python file that will be executed by the computer. 2. **README.md:** contains exercise instructions. 3. **test.py:** you don't have to open this file, it contains the testing script for the exercise. +> 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. + ## Contributors -Thanks goes to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): +Thanks to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): + +1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribution: (coder) 💻, (idea) 🤔, (build-tests) ⚠️, (pull-request-review) 👀, (build-tutorial) ✅ (documentation) 📖 + +2. [Paolo (plucodev)](https://github.com/plucodev), contribution: (bug reports) 🐛, (coder) 💻, (translation) 🌎 + +3. [Marco Gómez (marcogonzalo)](https://github.com/marcogonzalo), contribution: (bug reports) :🐛, (translation) 🌎 + + +This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. -1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribution: (coder) :computer: (idea) 🤔, (build-tests) :warning:, (pull-request-review) :eyes: (build-tutorial) :white_check_mark: (documentation) :book: -2. [Paolo (plucodev)](https://github.com/plucodev), contribution: (bug reports) :bug:, contribution: (coder), (translation) :earth_americas: -3. [Marco Gómez (marcogonzalo)](https://github.com/marcogonzalo), contribution: (bug reports) :bug:, (translation) :earth_africa: +Contributions of any kind are welcome! -This project follows the -[all-contributors](https://github.com/kentcdodds/all-contributors) -specification. Contributions of any kind are welcome! +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). diff --git a/exercises/00-Welcome/README.es.md b/exercises/00-Welcome/README.es.md new file mode 100644 index 0000000..a2964b0 --- /dev/null +++ b/exercises/00-Welcome/README.es.md @@ -0,0 +1,30 @@ +--- +intro: "https://www.youtube.com/watch?v=SD9lqR67yMY" +--- +# Welcome to Python Functions! + +¡¡Nos entusiasma mucho tenerte aquí!! 🎉 😂 + +Presiona `Next →` en la esquina superior derecha cuando quieras empezar. + +En este curso aprenderás los siguientes conceptos: + +1. Cómo crear y llamar funciones. + +2. Construir tus primeras funciones. + +3. Practicar las funciones Lambda de Python. + +4. Construir funciones con parámetros. + +5. Ejemplos de la vida real con funciones. + +## Contributors + +Thanks goes to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): + +1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribution: (coder) 💻, (idea) 🤔, (build-tests) ⚠️, (pull-request-review) 🤓, (build-tutorial) ✅, (documentation) 📖 +2. [Paolo (plucodev)](https://github.com/plucodev), contribución: (bug reports) 🐛, (coder) 💻, (traducción) 🌎 +3. [Marco Gómez (marcogonzalo)](https://github.com/marcogonzalo), contribución: (bug reports) 🐛, (traducción) 🌎 + +This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind are welcome! diff --git a/exercises/00-Welcome/README.md b/exercises/00-Welcome/README.md new file mode 100644 index 0000000..4b14bc8 --- /dev/null +++ b/exercises/00-Welcome/README.md @@ -0,0 +1,31 @@ +--- +intro: "https://www.youtube.com/watch?v=06rxSj-9wM4" +--- + +# Welcome to Python Functions! + +We are very excited to have you here !! 🎉 😂 + +Click `Next →` on the top right of these instructions when you are ready to start. + +During this course, you will be learning the following concepts: + +1. Learning how to create and call functions. + +2. Building your first real functions. + +3. Get comfortable using Python Lambda Functions. + +4. Construct functions with parameters. + +5. Real life examples for functions. + +## Contributors + +Thanks goes to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): + +1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribution: (coder) 💻, (idea) 🤔, (build-tests) ⚠️, (pull-request-review) 🤓, (build-tutorial) ✅, (documentation) 📖 +2. [Paolo (plucodev)](https://github.com/plucodev), contribution: (bug reports) 🐛, (coder) 💻, (translation) 🌎 +3. [Marco Gómez (marcogonzalo)](https://github.com/marcogonzalo), contribution: (bug reports) 🐛, (translation) 🌎 + +This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind are welcome! diff --git a/exercises/01-Hello-World/README.es.md b/exercises/01-Hello-World/README.es.md new file mode 100644 index 0000000..bafbb75 --- /dev/null +++ b/exercises/01-Hello-World/README.es.md @@ -0,0 +1,25 @@ +--- +tutorial: "https://www.youtube.com/watch?v=X1XZ4d-DE4Q" +--- + +# `01` Hello World + +En Python, usamos **print** para hacer que el computador escriba cualquier cosa que queramos (el contenido de una variable, un string dado, etc.) en algo llamado "la consola". + +Cada lenguaje tiene **funciones** para integrarse con la consola, ya que al principio era la única forma de interactuar con los usuarios (antes de que llegaran Windows, Linux o macOS). + +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. + +Este es un ejemplo de cómo usarla: + +```py +print("How are you?") +``` + +## 📝 Instrucciones: + +1. Usa la función `print()` para escribir `"Hello World"` en la consola. Siéntete libre de intentar otras cosas también. + +## 💡 Pista: + ++ 📹 Puedes ver este breve video (2 minutos) sobre la consola: https://www.youtube.com/watch?v=vROGBvX_MHQ diff --git a/exercises/01-Hello-World/README.md b/exercises/01-Hello-World/README.md new file mode 100644 index 0000000..943c535 --- /dev/null +++ b/exercises/01-Hello-World/README.md @@ -0,0 +1,25 @@ +--- +tutorial: "https://www.youtube.com/watch?v=_0zvPIS587w" +--- + +# `01` Hello World + +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". + +Every language has **functions** to integrate with the console, as it was the only way to interact with the users at the beginning (before Windows, Linux or macOS arrived). + +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. + +This is an example of how to use it: + +```py +print("How are you?") +``` + +## 📝 Instructions: + +1. Use `print()` to display `"Hello World"` on the console. Feel free to try other things as well. + +## 💡 Hint: + ++ 📹 You can watch this 2 minute video about the console: https://www.youtube.com/watch?v=vROGBvX_MHQ diff --git a/exercises/01-Hello-World/app.py b/exercises/01-Hello-World/app.py new file mode 100644 index 0000000..fce62c1 --- /dev/null +++ b/exercises/01-Hello-World/app.py @@ -0,0 +1 @@ +# Your code here diff --git a/exercises/01-Hello-World/solution.hide.py b/exercises/01-Hello-World/solution.hide.py new file mode 100644 index 0000000..a033754 --- /dev/null +++ b/exercises/01-Hello-World/solution.hide.py @@ -0,0 +1,3 @@ +# Your code here + +print("Hello World") diff --git a/exercises/02-Hello-World/test.py b/exercises/01-Hello-World/test.py similarity index 90% rename from exercises/02-Hello-World/test.py rename to exercises/01-Hello-World/test.py index 54698bd..808d21d 100644 --- a/exercises/02-Hello-World/test.py +++ b/exercises/01-Hello-World/test.py @@ -4,7 +4,7 @@ def test_output(): f = open(os.path.dirname(os.path.abspath(__file__)) + '/app.py') content = f.read() - assert content.find("print(") > 0 + assert content.find("print") >= 0 @pytest.mark.it('The printed value on the console should be "Hello World"') def test_for_file_output(capsys, app): diff --git a/exercises/01-hello-world/README.es.md b/exercises/01-hello-world/README.es.md deleted file mode 100644 index e164d50..0000000 --- a/exercises/01-hello-world/README.es.md +++ /dev/null @@ -1,24 +0,0 @@ -# Aprende Funciones en Python! - -¡¡Nos estusiasma mucho tenerte aquí!! 🎉 😂 -Presiona `Next` `Next →` de arriba a la derecha cuando quieras empezar. - -En este curso aprenderás los siguientes conceptos: - -1. Cómo crear y llamar Funciones. -2. Construir tus primeras funciones reales -3. Sentirte cómod@ usando Funciones Lambda en Python -4. Construir Funciones con parametros. -5. Ejemplos de la vida real con funciones - -## Contributors - -Thanks goes to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): - -1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribution: (coder) :computer: (idea) 🤔, (build-tests) :warning:, (pull-request-review) :eyes: (build-tutorial) :white_check_mark: (documentation) :book: -2. [Paolo (plucodev)](https://github.com/plucodev), contribución: (bug reports) :bug: (coder) :computer:, (traducción) :earth_americas: -3. [Marco Gómez (marcogonzalo)](https://github.com/marcogonzalo), contribución: (bug reports) :bug:, (traducción) :earth_africa: - -This project follows the -[all-contributors](https://github.com/kentcdodds/all-contributors) -specification. Contributions of any kind are welcome! diff --git a/exercises/01-hello-world/README.md b/exercises/01-hello-world/README.md deleted file mode 100644 index 37c7913..0000000 --- a/exercises/01-hello-world/README.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -intro: "https://www.youtube.com/watch?v=awa_yfGgy9s" ---- - -# Learn Python Functions! - -We are very excited to have you here !! 🎉 😂 -Click `next` on the top right of this instructions when you are ready to start. - -During this course you will be learning the following concepts: - -1. Learning how to create and call Functions. -2. Building your first real functions -3. Get comfortable using Python Lambda Functions -4. Construct Functions with parameters. -5. Real life examples for functions - -## Contributors - -Thanks goes to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): - -1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribution: (coder) :computer: (idea) 🤔, (build-tests) :warning:, (pull-request-review) :eyes: (build-tutorial) :white_check_mark: (documentation) :book: -2. [Paolo (plucodev)](https://github.com/plucodev), contribution: (bug reports) :bug:, contribution: (coder), (translation) :earth_americas: -3. [Marco Gómez (marcogonzalo)](https://github.com/marcogonzalo), contribution: (bug reports) :bug:, (translation) :earth_africa: - -This project follows the -[all-contributors](https://github.com/kentcdodds/all-contributors) -specification. Contributions of any kind are welcome! diff --git a/exercises/02-Hello-World/README.es.md b/exercises/02-Hello-World/README.es.md deleted file mode 100644 index da0a93d..0000000 --- a/exercises/02-Hello-World/README.es.md +++ /dev/null @@ -1,19 +0,0 @@ -# `02` Hola, Mundo - -En Python, usamos `print` para hacer que el computador escriba cualquier cosa que queramos (el contenido de una variable, un texto dado, etc.) in algo llamado `la consola`. - -Cada idioma tiene funciones para integrarse con la consola, ya que al principio era la única forma de interactuar con los usuarios (antes de que llegara Windows o MacOS o Linux). Hoy en día, la impresión en la consola se utiliza sobre todo como herramienta de monitorización, ideal para dejar un rastro del contenido de las variables durante la ejecución del programa. - -Este es un ejemplo de cómo usarlo: -```js -print("How are you?") -``` - -## 📝 Instrucciones: - -Usa la función `print()` para escribir "Hello World!" en la consola. Siéntete libre de intentar otras cosas también. - -## 💡 Ayuda: - -Video de 5 minutos sobre la consola: -https://www.youtube.com/watch?v=vROGBvX_MHQ diff --git a/exercises/02-Hello-World/README.md b/exercises/02-Hello-World/README.md deleted file mode 100644 index 8cf9228..0000000 --- a/exercises/02-Hello-World/README.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -tutorial: "https://www.youtube.com/watch?v=voBO7a0KPtE" ---- - -# `02` Hello World - -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`. - -Every language has functions to integrate with the console, as it was the only way to interact with the users at the beginning (before the Windows or Linux or MacOS arrived). Today, printing in the console is used mostly as a monitoring tool, ideal to leave a trace of the content of variables during the program execution. - -This is an example of how to use it: -```js -print("How are you?") -``` - -## 📝 Instructions: - -Use print to display "Hello World" on the console. Feel free to try other things as well. - -## 💡 Hint: - -5 minutes video about the console: -https://www.youtube.com/watch?v=vROGBvX_MHQ diff --git a/exercises/02-Hello-World/app.py b/exercises/02-Hello-World/app.py deleted file mode 100644 index 801de24..0000000 --- a/exercises/02-Hello-World/app.py +++ /dev/null @@ -1 +0,0 @@ -# your code here \ No newline at end of file diff --git a/exercises/02-What-is-a-function/README.es.md b/exercises/02-What-is-a-function/README.es.md new file mode 100644 index 0000000..6fe4214 --- /dev/null +++ b/exercises/02-What-is-a-function/README.es.md @@ -0,0 +1,27 @@ +--- +tutorial: "https://www.youtube.com/watch?v=4JzHH2qR8n0" +--- +# `02` What is a function? + +Puedes ver una función como un **fragmento de código** que puedes usar varias veces. + +Por ejemplo, si queremos obtener la suma de dos números, podemos declarar una función llamada `sum` que devuelve la suma de `number1` y `number2`: + +```python +def sum(number1,number2): + return number1 + number2 +``` + +Después de declarar la función, podemos usarla tantas veces como queramos, así: + +```python +total = sum(2,3) +total2 = sum(5,10) + +print(total) # Imprime 5 en la consola +print(total2) # Imprime 15 en la consola +``` + +## 📝 Instrucciones: + +1. Calcula la suma entre `3445324` y `53454423` y asigna el resultado a una variable llamada `super_duper`. diff --git a/exercises/02-What-is-a-function/README.md b/exercises/02-What-is-a-function/README.md new file mode 100755 index 0000000..24569d2 --- /dev/null +++ b/exercises/02-What-is-a-function/README.md @@ -0,0 +1,28 @@ +--- +tutorial: "https://www.youtube.com/watch?v=U5GId8yOc-A" +--- + +# `02` What is a function? + +You can see a function as a **fragment of code** we can use several times. + +For example: If we want to get the sum of two numbers, we can declare a function called `sum` that returns the sum of `number1` and `number2`: + +```python +def sum(number1,number2): + return number1 + number2 +``` + +After the function is declared, we can use it as many times as we want, like this: + +```python +total = sum(2,3) +total2 = sum(5,10) + +print(total) # Prints 5 on the console +print(total2) # Prints 15 on the console +``` + +## 📝 Instructions: + +1. Please calculate the sum between `3445324` and `53454423` and assign the result to a variable called `super_duper`. diff --git a/exercises/03-What-is-a-function/app.py b/exercises/02-What-is-a-function/app.py similarity index 83% rename from exercises/03-What-is-a-function/app.py rename to exercises/02-What-is-a-function/app.py index 551610b..efeec63 100755 --- a/exercises/03-What-is-a-function/app.py +++ b/exercises/02-What-is-a-function/app.py @@ -1,12 +1,6 @@ def sum(number1,number2): return number1 + number2 +# Your code here total = sum(2,3) print(total) - - - - - - - diff --git a/exercises/02-What-is-a-function/solution.hide.py b/exercises/02-What-is-a-function/solution.hide.py new file mode 100644 index 0000000..a313431 --- /dev/null +++ b/exercises/02-What-is-a-function/solution.hide.py @@ -0,0 +1,6 @@ +def sum(number1,number2): + return number1 + number2 + +# Your code here +super_duper = sum(3445324,53454423) +print(super_duper) diff --git a/exercises/03-What-is-a-function/tests.py b/exercises/02-What-is-a-function/tests.py similarity index 100% rename from exercises/03-What-is-a-function/tests.py rename to exercises/02-What-is-a-function/tests.py diff --git a/exercises/03-Call-a-function/README.es.md b/exercises/03-Call-a-function/README.es.md new file mode 100644 index 0000000..8748075 --- /dev/null +++ b/exercises/03-Call-a-function/README.es.md @@ -0,0 +1,46 @@ +--- +tutorial: "https://www.youtube.com/watch?v=F7_I8PD38ZQ" +--- +# `03` Calling a Function + +Una función podría recibir 0 parámetros y devolverá algo siempre, incluso si no añades explícitamente el `return`. + +👉 [Clic aquí para saber más sobre funciones](https://4geeks.com/es/lesson/working-with-functions-python-es). + +Por ejemplo, una función que calcula el área de un cuadrado sería algo como esto: + +```python +def calculate_area(length, width): + return length * width +``` + +Si deseas usar esa función para calcular el área de un cuadrado con: + +```python +length = 3 +width = 6 +``` + +Tendrías que hacer algo como esto: + +```python +area = calculate_area(3,6) +# El valor de 'area' sería 18 +``` + +## 📝 Instrucciones: + +1. Crea nuevas variables llamadas `square_area1`, `square_area2`, `square_area3` y llama a la función `calculate_area` 3 veces, una por cada cuadrado en la foto, utilizando las dimensiones de la figura, por ejemplo: + +```python +# Para la primera figura: +square_area1 = calculate_area(4,4) +``` + +![Cuadrados](http://i.imgur.com/VyoJRAL.png) + +## 💡 Pistas: + +- Llama 3 veces a la función `calculate_area`, una por cada cuadrado, pasando la longitud y el ancho de cada cuadrado. + ++ 📹 [Video de 9 min sobre funciones en Python](https://www.youtube.com/watch?v=NE97ylAnrz4). diff --git a/exercises/03-Call-a-function/README.md b/exercises/03-Call-a-function/README.md new file mode 100755 index 0000000..07ce82d --- /dev/null +++ b/exercises/03-Call-a-function/README.md @@ -0,0 +1,48 @@ +--- +tutorial: "https://www.youtube.com/watch?v=8tvkCp3EMiM" +--- + +# `03` Calling a Function + +A function could receive zero parameters, and it always returns something, even if you don't explicitly add the `return` statement. + +👉 [Click here to read more about functions](https://4geeks.com/lesson/working-with-functions-python). + +For example: a function that calculates the area of a square will be something like this: + +```python +def calculate_area(length, width): + return length * width +``` + +If you want to use that function to calculate the area of a square with: + +```python +length = 3 +width = 6 +``` + +You need to do something like this: + +```python +area = calculate_area(3,6) +# The value of 'area' will be set to 18 +``` + +## 📝 Instructions: + +1. Create new variables named `square_area1`, `square_area2`, `square_area3` and call the function `calculate_area` three times, one for each square in the picture, for example: + +```python +# For the first figure: +square_area1 = calculate_area(4,4) +``` + +![Squares](http://i.imgur.com/VyoJRAL.png) + +## 💡 Hints: + ++ Call the `calculate_area` function three times, one per each square, passing the length and edge of each square. + ++ 📹 [9 min video about functions in Python](https://www.youtube.com/watch?v=NE97ylAnrz4). + diff --git a/exercises/03-Call-a-function/app.py b/exercises/03-Call-a-function/app.py new file mode 100755 index 0000000..0c131b3 --- /dev/null +++ b/exercises/03-Call-a-function/app.py @@ -0,0 +1,4 @@ +def calculate_area(length, width): + return length * width + +# Your code below this line diff --git a/exercises/03-Call-a-function/solution.hide.py b/exercises/03-Call-a-function/solution.hide.py new file mode 100644 index 0000000..758b6e6 --- /dev/null +++ b/exercises/03-Call-a-function/solution.hide.py @@ -0,0 +1,7 @@ +def calculate_area(length, width): + return length * width + +# Your code below this line +square_area1 = calculate_area(4,4) +square_area2 = calculate_area(2,2) +square_area3 = calculate_area(5,5) diff --git a/exercises/04-Call-a-function/tests.py b/exercises/03-Call-a-function/tests.py similarity index 83% rename from exercises/04-Call-a-function/tests.py rename to exercises/03-Call-a-function/tests.py index cbd4870..3657291 100755 --- a/exercises/04-Call-a-function/tests.py +++ b/exercises/03-Call-a-function/tests.py @@ -1,6 +1,6 @@ import io, sys, pytest, os, re, mock -@pytest.mark.it("Create a function 'calculate_area'") +@pytest.mark.it("Create the function 'calculate_area'") def test_declare_variable(): path = os.path.dirname(os.path.abspath(__file__))+'/app.py' with open(path, 'r') as content_file: @@ -16,7 +16,7 @@ def test_for_callable(capsys, app): def test_for_integer(capsys, app): assert isinstance(app.calculate_area(3,4), int) -@pytest.mark.it('We tried the function sum with a=3 and b=4 and it did not return 7') +@pytest.mark.it('We tried the function sum with length=3 and width=4 and it did not return 12') def test_for_return(capsys, app): assert app.calculate_area(3,4) == 12 assert app.calculate_area(5,4) == 20 @@ -43,10 +43,10 @@ def test_for_square_area_value2(capsys, app): def test_for_square_area_value3(capsys, app): assert app.square_area3 == 25 -@pytest.mark.it("Create a function calculate_area must be called 3 times, one for each figure") +@pytest.mark.it("The function calculate_area must be called 3 times, one for each square") def test_call_calculate_area(): path = os.path.dirname(os.path.abspath(__file__))+'/app.py' with open(path, 'r') as content_file: content = content_file.read() - regex = re.compile(r"=(\s*)calculate_area\(") - assert bool(regex.search(content)) == True \ No newline at end of file + regex = re.compile(r"=(\s*)calculate_area\s*\(") + assert bool(regex.search(content)) == True diff --git a/exercises/03-What-is-a-function/README.es.md b/exercises/03-What-is-a-function/README.es.md deleted file mode 100644 index 4f0aa47..0000000 --- a/exercises/03-What-is-a-function/README.es.md +++ /dev/null @@ -1,24 +0,0 @@ -# `03` ¿Qué es una función (function)? - -Puedes ver una función como un **fragmento de código** que puedes encapsular entre llaves para poder usarla varias veces. - -Por ejemplo, si queremos obtener la suma de dos números, podemos declarar una función llamada `sum` que devuelve la suma de number1 y number2: - -```python -def sum(number1,number2): - return number1 + number2 -``` - -Después de declarar la función, podemos usarla tantas veces como queramos, así: - -```python -total = sum(2,3) -total2 = sum(5,10) - -print(total) # prints 5 on the terminal -print(total2) # prints 15 on the terminal -``` - -# 📝 Instrucciones - -Calcula la suma entre **3445324** y **53454423** y asigna el resultado a una variable llamada `super_duper` diff --git a/exercises/03-What-is-a-function/README.md b/exercises/03-What-is-a-function/README.md deleted file mode 100755 index c49d55c..0000000 --- a/exercises/03-What-is-a-function/README.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -tutorial: "https://www.youtube.com/watch?v=tgTLyZ0cKj4" ---- - -# `03` What is a function? - -You can see a function as a **fragment of code** we can use several times. - -For example: If we want to get the sum of two numbers, we can declare a function called `sum` that returns the sum of number1 and number2: - -```python -def sum(number1,number2): - return number1 + number2 -``` - -After the function is declared we can use it as many times as we want, like this: - -```python -total = sum(2,3) -total2 = sum(5,10) - -print(total) # prints 5 on the terminal -print(total2) # prints 15 on the terminal -``` - -# 📝 Instructions - -Please calculate the sum between **3445324** and **53454423** and assign the result to a variable called `super_duper` diff --git a/exercises/04-Call-a-function/README.es.md b/exercises/04-Call-a-function/README.es.md deleted file mode 100644 index 9dcd538..0000000 --- a/exercises/04-Call-a-function/README.es.md +++ /dev/null @@ -1,42 +0,0 @@ -# `04` Llamando a una función - -Una función podría recibir 0 parámetros y tú puedes devolver algo siempre, incluso si no añades explícitamente el `return`. - -:point_up: [Presiona aquí para saber más sobre funciones](https://content.breatheco.de/lesson/working-with-functions-python) - -Por ejemplo, una función que calcula el área de un cuadrado sería algo como esto: - -```python -def calculate_area(length, edge): - return length * edge -``` - -Si deseas usar esa función para calcular el área de un cuadrado con - -```python -length = 3 -edge = 6 -``` - -Necesitas hacer algo como esto: -```python -area = calculate_area(3,6) -# The value of area will be set to 18 -``` - -# 📝 Instrucciones: - -Crea una nueva variable llamada squareArea para cada nueva iteración de la función CalculateArea utilizando las dimensiones de la figura, por ejemplo, para la primera figura, - -```python -# For the first figure: -square_area1 = calculate_area(4,4) -``` - -![img](http://i.imgur.com/VyoJRAL.png) - -# 💡 Sugerencia: - -- Llama 3 veces a la función `calculate_area`, una por cada cuadrado, pasando la longitud y el borde de cada cuadrado. - -:tv: [Video de 9 min sobre funciones en Python](https://www.youtube.com/watch?v=NE97ylAnrz4) diff --git a/exercises/04-Call-a-function/README.md b/exercises/04-Call-a-function/README.md deleted file mode 100755 index cbf2ccd..0000000 --- a/exercises/04-Call-a-function/README.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -tutorial: "https://www.youtube.com/watch?v=NU5iW_bWwmY" ---- - -# `04` Calling a function - -A function could receive 0 parameters, and you can it always returns something, event if you don't explicitly add the `return` statement. - -:point_up: [Click here to read more about functions](https://content.breatheco.de/lesson/working-with-functions-python) - -For example: a function that calculates the area of a square will be something like this: - -```python -def calculate_area(length, edge): - return length * edge -``` - -If you want to use that function to calculate the area of a square with - -```python -length = 3 -edge = 6 -``` - -You need to do something like this: -```python -area = calculate_area(3,6) -# The value of area will be set to 18 -``` - -# 📝 Instructions: - -Create a new variables named square_area1, square_area2, square_area3 and call the function calculate_area 3 times one fo each square in the picture, for example: - -```python -# For the first figure: -square_area1 = calculate_area(4,4) -``` - -![img](http://i.imgur.com/VyoJRAL.png) - -# 💡 Hint: - -Call the `calculate_area` function 3 times, one per each square, passing the length and edge of each square. - -:tv: [9 min video about functions in python](https://www.youtube.com/watch?v=NE97ylAnrz4) - diff --git a/exercises/04-Call-a-function/app.py b/exercises/04-Call-a-function/app.py deleted file mode 100755 index c856d48..0000000 --- a/exercises/04-Call-a-function/app.py +++ /dev/null @@ -1,4 +0,0 @@ -def calculate_area(length,edge): - return length * edge - -# Your code Below this line: \ No newline at end of file diff --git a/exercises/04-Defining-vs-Calling-a-function/README.es.md b/exercises/04-Defining-vs-Calling-a-function/README.es.md new file mode 100644 index 0000000..9f2d53f --- /dev/null +++ b/exercises/04-Defining-vs-Calling-a-function/README.es.md @@ -0,0 +1,54 @@ +--- +tutorial: "https://www.youtube.com/watch?v=ztyFrIY7U3o" +--- + +# `04` Defining vs Calling a Function + +Las funciones solo existen si tú u otra persona las define... es la única forma en que el compilador/intérprete de lenguaje sabe que existen, por lo tanto, puede ejecutarlas cuando las llamas. + +Para definir una función necesitamos escribir esta fórmula básica de código: + +```python +def nombre_de_funcion(parametro1, parametro2, ...parametroX): + # Código de la función aquí + return algo +``` + +La palabra `def` es una palabra reservada en Python, esto significa que solo se usa para definir una función. + +**El nombre** de la función podría ser lo que quieras. + +*Consejo:* usa un nombre descriptivo (no intentes ahorrar palabras, usa tantas como necesites) de esta manera entenderás lo que hace la función (y lo que devuelve). + +Nombres de ejemplo: `add_two_integers` (suma dos números enteros), `calculate_taxes` (calcular impuestos), `get_random_number` (obtener número aleatorio), etc. + +**Parámetros:** puedes definir tantos parámetros como desees, más aún, si los necesitas. La cantidad de parámetros dependerá de las operaciones realizadas dentro de la función. + +Ejemplo: si la función está sumando dos enteros (a + b), esto significa que la función necesitará dos parámetros (uno para cada entero). + +**Alcance:** Todo el código que contenga la función debe tener una sangría a la derecha, todo lo que esté en una sangría diferente no será considerado como parte de la función, a esto se llama **alcance**, y puede ser local (dentro de la función) y global (fuera de la función). + +**El retorno**: no todas las funciones necesitan devolver algo, pero se recomienda que lo hagan. + +*Consejo*: devolver `None` es un buen valor por defecto para cuando, aún, no sabes si tu función debe devolver algo. + +Ejemplo de una función: + +```python +def concatenate_number_to_string(local_number, local_string): + local_variable = local_string + str(local_number) + return local_variable +``` + + +## 📝 Instrucciones: + +1. Define una función llamada `multi`. + +2. La función `multi` recibe dos números. + +3. Devuelve el resultado de la multiplicación entre ellos. + +## 💡 Pista: + ++ Recuerda agregar la línea de `return`. Una función siempre debería devolver algo. En este caso debería ser el resultado de la multiplicación. diff --git a/exercises/04-Defining-vs-Calling-a-function/README.md b/exercises/04-Defining-vs-Calling-a-function/README.md new file mode 100755 index 0000000..ea048df --- /dev/null +++ b/exercises/04-Defining-vs-Calling-a-function/README.md @@ -0,0 +1,48 @@ +--- +tutorial: "https://www.youtube.com/watch?v=XbDE19gR678" +--- + +# `04` Defining vs Calling a Function + +Functions will only exist if you or somebody else defines them; it is the only way the language compiler/interpreter knows they exist, therefore it's able to run them when you call them. + +To define a function, we need to write this basic code formula: + +```python +def my_function_name(parameter1, parameter2, ...parameterX): + # The function code here + return something +``` + +The word `def` is a reserved word in Python, this means it is only used to define a function. + +**The name** of the function could be anything you like. Tip: Use a descriptive name (don't be cheap with words, use as many as you need); this way, you will understand what the function does -and returns-. + +Example names: `add_two_integers`, `calculate_taxes`, `get_random_number`, etc. + +**Parameters:** You can define as many parameters as you like or need. The amount of parameters will depend on the operations done inside the function. I.E: If the function is adding two integers `(a + b)` this means the function will need two parameters (one for each integer). + +**Scope:** All the code that the function will contain needs to be indented one tab to the right, anything on a different indentation won't be considered as part of the function. This is called **the scope**, and it could be local (inside the function) and global (outside the function). + +**The Return**: not every function needs to return something, but it is recommended that it does. Tip: returning `None` is a good default for when you still don't know if you need to return something. + +Example of a function: + +```python +def concatenate_number_to_string(local_number, local_string): + local_variable = local_string + str(local_number) + return local_variable +``` + + +## 📝 Instructions: + +1. Define a function called `multi`. + +2. The `multi` function receives two numbers. + +3. Return the result of the multiplication between them. + +## 💡 Hint: + ++ Remember to add the `return` line. Every function should return something, in this case, it should be the result of the multiplication. diff --git a/exercises/04-Defining-vs-Calling-a-function/app.py b/exercises/04-Defining-vs-Calling-a-function/app.py new file mode 100755 index 0000000..eedeae6 --- /dev/null +++ b/exercises/04-Defining-vs-Calling-a-function/app.py @@ -0,0 +1,5 @@ +# Define below the function called "multi" that expects 2 parameters + +# Don't edit anything below this line +return_value = multi(7,53812212) +print(return_value) diff --git a/exercises/04-Defining-vs-Calling-a-function/solution.hide.py b/exercises/04-Defining-vs-Calling-a-function/solution.hide.py new file mode 100644 index 0000000..afa0209 --- /dev/null +++ b/exercises/04-Defining-vs-Calling-a-function/solution.hide.py @@ -0,0 +1,7 @@ +# Define below the function called "multi" that expects 2 parameters +def multi(num1, num2): + total = num1 * num2 + return total +# Don't edit anything below this line +return_value = multi(7,53812212) +print(return_value) diff --git a/exercises/05-Defining-vs-Calling-a-function/tests.py b/exercises/04-Defining-vs-Calling-a-function/tests.py similarity index 52% rename from exercises/05-Defining-vs-Calling-a-function/tests.py rename to exercises/04-Defining-vs-Calling-a-function/tests.py index 7dd33c3..ab63ea7 100755 --- a/exercises/05-Defining-vs-Calling-a-function/tests.py +++ b/exercises/04-Defining-vs-Calling-a-function/tests.py @@ -1,17 +1,25 @@ import io, sys, pytest, os, re, mock -@pytest.mark.it("Create a function 'multi'") +@pytest.mark.it("Create the function 'multi'") def test_declare_variable(): path = os.path.dirname(os.path.abspath(__file__))+'/app.py' with open(path, 'r') as content_file: content = content_file.read() - regex = re.compile(r"def(\s*)multi\(") + regex = re.compile(r"def\s*multi\s*\(") assert bool(regex.search(content)) == True @pytest.mark.it('The function multi must exist') def test_for_callable(capsys, app): assert callable(app.multi) +@pytest.mark.it('The function multi must return a value') +def test_for_return_something(capsys, app): + assert app.multi(1, 1) == True + @pytest.mark.it('The function multi must receive two numbers and return their multiplication') def test_for_integer(capsys, app): - assert app.multi(3,4) == 12 \ No newline at end of file + assert app.multi(3,4) == 12 + +@pytest.mark.it('The function multi must receive two numbers and return their multiplication. Testing with different values') +def test_for_function_return(capsys, app): + assert app.multi(10, 6) == 60 diff --git a/exercises/05-Defining-vs-Calling-a-function/README.es.md b/exercises/05-Defining-vs-Calling-a-function/README.es.md deleted file mode 100644 index b615ca4..0000000 --- a/exercises/05-Defining-vs-Calling-a-function/README.es.md +++ /dev/null @@ -1,43 +0,0 @@ -# `05` Definir vs llamar a una función - -Las funciones solo existirán si usted u otra persona las define ... es la única forma en que el compilador/intérprete de idiomas sabe que existen, por lo tanto, puede ejecutarlas cuando las llama. - -Para definir una función necesitamos escribir esta fórmula básica de código: - -```python -def myFunctionName(parameter, parameter2, ...parameterX): - # the function code here - return something -``` - -La palabra `def` es una palabra reservada en Python, esto significa que solo se usa para definir una función. - -**El nombre** de la función podría ser lo que quieras. Consejo: usa un nombre descriptivo (no intentes ahorrar palabras, usa tantas como necesites) de esta manera entenderás lo que hace la función -y lo que devuelve-. -Nombres de ejemplo: add_two_integers , calculate_taxes , get_random_number, etc. - -**Parámetros:** puedes definir tantos parámetros como desees, más aún, si los necesitas. La cantidad de parámetros dependerá de las operaciones realizadas dentro de la función. Ejemplo: si la función está agregando dos enteros (3 + 4), esto significa que la función necesitará dos parámetros (uno para cada entero). - -**Ámbito:** Todo el código que contenga la función debe tener una sangría a la derecha, todo lo que esté en una sangría diferente no será considerado como parte de la función, esto se llama **ámbito**, y puede ser local (dentro de la función) y global (fuera de la función). - -**El retorno**: no todas las funciones necesitan devolver algo, pero se recomienda que lo haga. -Consejo: devolviendo `None` es un buen valor por defecto para cuando, aún, no sabes si se necesita devolver algo. - -Ejemplo de una función: - - -```python -def concatenate_number_to_string(local_number, local_string): - local_variable = local_string+""+str(local_number) - return local_variable -``` - - -# 📝 Instrucciones: - -1. Define una función llamada "multi". -2. La función múltiple recibe dos números -3. Devuelve el resultado de la multiplicación entre ellos. - -# 💡 Pista: - -Recuerda agregar la línea de `return`. Cada función debe devolver algo. En este caso debería ser el resultado de la multiplicación. diff --git a/exercises/05-Defining-vs-Calling-a-function/README.md b/exercises/05-Defining-vs-Calling-a-function/README.md deleted file mode 100755 index 771ec35..0000000 --- a/exercises/05-Defining-vs-Calling-a-function/README.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -tutorial: "https://www.youtube.com/watch?v=fz4ttmwZWuc" ---- - -# `05` Defining vs Calling a function - -Functions will only exists if you or somebody else defines them... is the only way the language compiler/interpreter knows they exist, therefore is able to run them when you call them. - -To define a function we need to write this basic code formula: - -```python -def myFunctionName(parameter, parameter2, ...parameterX): - # the function code here - return something -``` - -The word `def` is a reserved word in Python, this means it is only used to define a function. - -**The name** of the function could be anything you like. -Tip: use a descriptive name (don't be cheap with words, -use as many as you need) this way you will understand what the function -does -and returns-. -Example names: add_two_integers , calculate_taxes , get_random_number, etc. - -**Parameters:** you can define as many parameters as you like or need. -The amount of parameters will depend on the operations done inside the function, -I.E: if the function is adding two integers `(3 + 4)` this means the function -will need two parameters (one for each integer). - -**Scope:** All the code that the function will contain need to be indented - one tab to the right, anything on a different indentation -won't be considered as part of the function, -this is called **the scope**, and it could be local (inside the function) -and global (outside of the function). - -**The Return**: not every function needs to return something, but it is recommended that it does. -Tip: returning `None` is a good default for when you, still, doesn't know if you need to return something. - -Example of a function: - -```python -def concatenate_number_to_string(local_number, local_string): - local_variable = local_string+""+str(local_number) - return local_variable -``` - - -# 📝 Instructions: - -1. Define a function called "multi". -2. Multi function receive two numbers -3. Return the result of the multiplication between them. - -# 💡 Hint - -Remember to add the "return" line, every function must return something, in this case it should be the result of the multiplication. diff --git a/exercises/05-Defining-vs-Calling-a-function/app.py b/exercises/05-Defining-vs-Calling-a-function/app.py deleted file mode 100755 index 79b86d8..0000000 --- a/exercises/05-Defining-vs-Calling-a-function/app.py +++ /dev/null @@ -1,5 +0,0 @@ -# Define the function called "multi" that expects 2 parameters: - -# don't edit anything below this line -return_value = multi(7,53812212) -print(return_value) \ No newline at end of file diff --git a/exercises/05-lambda-functions/README.es.md b/exercises/05-lambda-functions/README.es.md new file mode 100644 index 0000000..8298707 --- /dev/null +++ b/exercises/05-lambda-functions/README.es.md @@ -0,0 +1,45 @@ +--- +tutorial: "https://www.youtube.com/watch?v=UH__beyfTlo" +--- + +# `05` Lambda Functions in Python + +Una **función lambda** es una función con solo una línea de código y sin nombre. + +Es un tipo de función muy especial en el mundo Python porque puedes usarla como una pequeña utilidad para una programación muy ágil: + +```python +# Declarando una función normal para una multiplicación +def multiply(p1, p2): + return p1 * p2 + +# Declarándola en una línea como una función lambda +multiply = lambda p1,p2: p1 * p2 +``` + +### 👉 Caracteristicas: + ++ Las **funciones lambda** tienen que ser siempre muy pequeñas. + ++ Las **funciones lambda** pueden tener únicamente una línea. + ++ Las **funciones lambda** no necesitan un `return`, se asume que lo que haya en esa línea devolverá un valor. + ++ Las **funciones lambda** pueden almacenarse en variables o ser pasadas como parámetro a otra función. + + +## 📝 Instrucciones: + +1. Crea una variable llamada `is_odd`. + +2. Asígnale una función **lambda** que devuelva `True` o `False` dependiendo de si un número dado es impar o no. + +## 💡 Pista: + ++ Así es como declararías una función normal: + +```python +# Esta función retorna "True" si el número es impar +def is_odd(num): + return (num % 2) != 0 +``` diff --git a/exercises/05-lambda-functions/README.md b/exercises/05-lambda-functions/README.md new file mode 100755 index 0000000..6ce4581 --- /dev/null +++ b/exercises/05-lambda-functions/README.md @@ -0,0 +1,46 @@ +--- +tutorial: "https://www.youtube.com/watch?v=vRusUCDa3-k" +--- + + +# `05` Lambda Functions in Python + +A **lambda function** is a function with just one line of code and no name. + +It is a very special type of function in the world of Python because you can use it as a small utility for very agile coding: + +```python +# Declaring a normal function for multiplication +def multiply(p1, p2): + return p1 * p2 + +# Declaring it now like a one line lambda function +multiply = lambda p1,p2: p1 * p2 +``` + +### 👉 Facts: + ++ **Lambda functions** have to always be very small. + ++ **Lambda functions** can only have one line. + ++ **Lambda functions** don't need a `return` statement (it is assumed that it will return whatever is on that one line). + ++ **Lambda functions** can be stored in variables or passed as parameters to another function. + +## 📝 Instructions: + +1. Create a variable called `is_odd`. + +2. Assign a **lambda function** to it that returns `True` or `False` if a given number is odd. + +## 💡 Hint + ++ Here is how you would declare it like a normal function: + +```py +# This function returns True if a number is odd +def is_odd(num): + return num % 2 != 0 +``` + diff --git a/exercises/05-lambda-functions/app.py b/exercises/05-lambda-functions/app.py new file mode 100755 index 0000000..b4ac556 --- /dev/null +++ b/exercises/05-lambda-functions/app.py @@ -0,0 +1,2 @@ +# Your function here + diff --git a/exercises/05-lambda-functions/solution.hide.py b/exercises/05-lambda-functions/solution.hide.py new file mode 100644 index 0000000..f134619 --- /dev/null +++ b/exercises/05-lambda-functions/solution.hide.py @@ -0,0 +1,3 @@ +# Your function here + +is_odd = lambda num: num % 2 != 0 diff --git a/exercises/06-lambda-functions/tests.py b/exercises/05-lambda-functions/tests.py similarity index 82% rename from exercises/06-lambda-functions/tests.py rename to exercises/05-lambda-functions/tests.py index bce6293..aa3054a 100755 --- a/exercises/06-lambda-functions/tests.py +++ b/exercises/05-lambda-functions/tests.py @@ -1,6 +1,6 @@ import io, sys, pytest, os, re, mock -@pytest.mark.it("Declare a function 'is_odd' as lambda") +@pytest.mark.it("Declare a function called 'is_odd' as lambda") def test_declare_variable(): path = os.path.dirname(os.path.abspath(__file__))+'/app.py' with open(path, 'r') as content_file: @@ -13,7 +13,7 @@ def test_for_callable(capsys): import app as app assert callable(app.is_odd) -@pytest.mark.it('The function is_odd must receive one number and return true if is odd or false otherwise') +@pytest.mark.it('The function is_odd must receive one number and return True if the number is odd or False otherwise') def test_for_integer(capsys): import app as app assert app.is_odd(3) == True @@ -21,4 +21,4 @@ def test_for_integer(capsys): @pytest.mark.it('We tested the function with 2 and the result was not False') def test_for_integer2(capsys): import app as app - assert app.is_odd(2) == False \ No newline at end of file + assert app.is_odd(2) == False diff --git a/exercises/06-lambda-function-two/README.es.md b/exercises/06-lambda-function-two/README.es.md new file mode 100644 index 0000000..fc990cb --- /dev/null +++ b/exercises/06-lambda-function-two/README.es.md @@ -0,0 +1,24 @@ +--- +tutorial: "https://www.youtube.com/watch?v=F30Vkf69SHI" +--- + +# `06` Lambda Functions + +### ☝ Recuerda: + +Las funciones Lambda permiten una sintaxis corta para escribir expresiones de funciones. + +```python +multiply = lambda x, y: x * y +print(multiply(2,2)) +``` + +## 📝 Instrucciones: + +1. Crea una función lambda llamada `rapid` que tendrá un parámetro de string. + +2. Devuelve el mismo string pero eliminándole la última letra. + +## 💡 Pista: + ++ Busca en Google "como eliminar el último caracter de un string python" (puedes usar los corchetes). diff --git a/exercises/06-lambda-function-two/README.md b/exercises/06-lambda-function-two/README.md new file mode 100755 index 0000000..c293196 --- /dev/null +++ b/exercises/06-lambda-function-two/README.md @@ -0,0 +1,24 @@ +--- +tutorial: "https://www.youtube.com/watch?v=0KX8Bh7d_9E" +--- + +# `06` Lambda Functions + +### ☝ Remember: + +Lambda functions allow a short syntax for writing function expressions. + +```python +multiply = lambda x, y: x * y +print(multiply(2,2)) +``` + +## 📝 Instructions: + +1. Create a lambda function called `rapid`, which will take one string parameter. + +2. Return the same string with the last letter removed. + +## 💡 Hint: + ++ Google "how to remove last letter from string python" (you can use the square brackets). diff --git a/exercises/06-lambda-function-two/app.py b/exercises/06-lambda-function-two/app.py new file mode 100755 index 0000000..a156102 --- /dev/null +++ b/exercises/06-lambda-function-two/app.py @@ -0,0 +1,5 @@ + + + +# Your code above, please do not change code below +print(rapid("bob")) # Should print "bo" diff --git a/exercises/06-lambda-function-two/solution.hide.py b/exercises/06-lambda-function-two/solution.hide.py new file mode 100644 index 0000000..ecfc065 --- /dev/null +++ b/exercises/06-lambda-function-two/solution.hide.py @@ -0,0 +1,4 @@ +rapid = lambda myStr: myStr[:-1] + +# Your code above, please do not change code below +print(rapid("bob")) # Should print "bo" diff --git a/exercises/07-lambda-function-two/tests.py b/exercises/06-lambda-function-two/tests.py similarity index 79% rename from exercises/07-lambda-function-two/tests.py rename to exercises/06-lambda-function-two/tests.py index 5d7e42b..7b6a474 100755 --- a/exercises/07-lambda-function-two/tests.py +++ b/exercises/06-lambda-function-two/tests.py @@ -1,6 +1,6 @@ import io, sys, pytest, os, re, mock -@pytest.mark.it("Declare a function 'rapid' as lambda") +@pytest.mark.it("Declare a function called 'rapid' as lambda") def test_declare_variable(): path = os.path.dirname(os.path.abspath(__file__))+'/app.py' with open(path, 'r') as content_file: @@ -12,8 +12,8 @@ def test_declare_variable(): def test_for_callable(capsys): from app import rapid -@pytest.mark.it('The function rapid must receive one string and return the same but without the last letter and uppercase') +@pytest.mark.it('The function rapid must receive one string and return the same string without the last character') def test_for_integer(capsys): from app import rapid assert rapid("maria") == "mari" - assert rapid("pepe") == "pep" \ No newline at end of file + assert rapid("pepe") == "pep" diff --git a/exercises/06-lambda-functions/README.es.md b/exercises/06-lambda-functions/README.es.md deleted file mode 100644 index b9ee110..0000000 --- a/exercises/06-lambda-functions/README.es.md +++ /dev/null @@ -1,33 +0,0 @@ -# `06` Funciones Lambda en Python - -Una función lambda es una función con solo una línea de código y sin nombre. -Es un tipo de función muy especial en el mundo Python porque puedes usarla como una pequeña utilidad para una programación muy ágil: - -```python -# declaring a normal funcion for multiplication -def multiply(p1, p2): - return p1 * p2 - -# declaring it now like a one line lambda -multiply = lambda p1,p2: p1 * p2 -``` - -1. Las funciones lambda tiene que ser siempre muy pequeñas -2. Las funciones lambda pueden tener únicamente una línea -3. Las funciones lambda no necesitan un `return`, se asume que lo que haya en esa línea devolverá un valor. -4. Las funciones lambda can be stored in variables or passed as parameters to another function - -# 📝 Instrucciones: - -1. Crea una variable llamada `is_odd` -2. Asígnale una función lambda que devuelva True o False dependiendo de si un número dado es impar o no - -## 💡 Ayuda: - -Así es como declararías una función normal - -```python -# this function return True if a number is odd. -def is_odd(num): - return (num % 2)! == 0: -``` diff --git a/exercises/06-lambda-functions/README.md b/exercises/06-lambda-functions/README.md deleted file mode 100755 index 3866aeb..0000000 --- a/exercises/06-lambda-functions/README.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -tutorial: "https://www.youtube.com/watch?v=HACQ9uerCuE" ---- - - -# `06` Lambda functions in Python - -A lambda function is a function with just one line of code and no name. -It is a very special type of funcion in the world of python because you can use it as a small utility for very agile coding: - -```python -# declaring a normal funcion for multiplication -def multiply(p1, p2): - return p1 * p2 - -# declaring it now like a one line lambda -multiply = lambda p1,p2: p1 * p2 -``` - -1. Lambda fuctions have to be always very small -2. Lambda function can only have one line -3. Lambda don't need a `return` statement, it is assumed that it will return whatever is on that one line. -4. Lambda functions can be stored in variables or passed as parameters to another function - -# 📝 Instructions: - -1. Create a variable called `is_odd` -2. Assign a lambda function to it that returns True or False if a given number is odd - -## 💡Hint - -Here is how you would declare it like a normal function - -```python -# this function return True if a number is odd. -def is_odd(num): - return (num % 2) !== 0: -``` -  diff --git a/exercises/06-lambda-functions/app.py b/exercises/06-lambda-functions/app.py deleted file mode 100755 index e59626e..0000000 --- a/exercises/06-lambda-functions/app.py +++ /dev/null @@ -1,2 +0,0 @@ -# your function here - diff --git a/exercises/07-Function-that-returns/README.es.md b/exercises/07-Function-that-returns/README.es.md new file mode 100644 index 0000000..80bd645 --- /dev/null +++ b/exercises/07-Function-that-returns/README.es.md @@ -0,0 +1,29 @@ +--- +tutorial: "https://www.youtube.com/watch?v=3V15moFzUjI" +--- + +# `07` Functions that return + +Es una muy buena práctica que las funciones devuelvan algo, incluso si es `None`. + +Si tus funciones devuelven algo, puedes crear algoritmos que usen muchas funciones al mismo tiempo. + +Por ejemplo, en este caso en particular tenemos dos funciones disponibles: + ++ `dollar_to_euro`: que calcula el valor en euros de un valor dado en dólares. + ++ `euro_to_yen`: calcula el valor en yenes de un valor dado en euros. + +## 📝 Instrucciones: + +1. Utilizando las dos funciones disponibles, imprime en la consola el valor de **137** dólares en yenes. + +## 💡 Pistas: + +Trabajando desde el final: + +- Nuestro valor esperado está en yenes. + +- Nuestra función disponible `euro_to_yen` proporcionará eso. + +- Para llegar al euro utilizaremos la función disponible `dollar_to_euro`. diff --git a/exercises/07-Function-that-returns/README.md b/exercises/07-Function-that-returns/README.md new file mode 100755 index 0000000..0103d2d --- /dev/null +++ b/exercises/07-Function-that-returns/README.md @@ -0,0 +1,29 @@ +--- +tutorial: "https://www.youtube.com/watch?v=H6Zps4dPqzs" +--- + +# `07` Functions that return + +It is very good practice that all functions return something, even if it is `None`. + +With what your function returns, you can create algorithms that use multiple functions at the same time. + +For example, in this particular case, we have two functions available: + ++ `dollar_to_euro`: that calculates the value in euros of a given value in dollars. + ++ `euro_to_yen`: calculates the value in yen of a given value in euros. + +## 📝 Instructions: + +1. Using the two functions available, print on the console the value of **137** dollars in yen. + +## 💡 Hints: + +Working backwards: + +- Our expected value is in yen. + +- Our available function `euro_to_yen` will provide that. + +- To get the euros, we will use the available function `dollar_to_euro`. diff --git a/exercises/07-Function-that-returns/app.py b/exercises/07-Function-that-returns/app.py new file mode 100755 index 0000000..fc81947 --- /dev/null +++ b/exercises/07-Function-that-returns/app.py @@ -0,0 +1,7 @@ +def dollar_to_euro(dollar_value): + return dollar_value * 0.91 + +def euro_to_yen(euro_value): + return euro_value * 161.70 + +####### ↓ YOUR CODE BELOW ↓ ####### diff --git a/exercises/07-Function-that-returns/solution.hide.py b/exercises/07-Function-that-returns/solution.hide.py new file mode 100644 index 0000000..82ee742 --- /dev/null +++ b/exercises/07-Function-that-returns/solution.hide.py @@ -0,0 +1,12 @@ +def dollar_to_euro(dollar_value): + return dollar_value * 0.91 + +def euro_to_yen(euro_value): + return euro_value * 161.70 + +####### ↓ YOUR CODE BELOW ↓ ####### + +euros = dollar_to_euro(137) +yen = euro_to_yen(euros) + +print(yen) diff --git a/exercises/08-Function-that-returns/test.py b/exercises/07-Function-that-returns/test.py similarity index 74% rename from exercises/08-Function-that-returns/test.py rename to exercises/07-Function-that-returns/test.py index 812e1c7..f45e234 100755 --- a/exercises/08-Function-that-returns/test.py +++ b/exercises/07-Function-that-returns/test.py @@ -1,6 +1,6 @@ import io, sys, pytest, os, re, mock -@pytest.mark.it("Call the function dollar_to_euro passing the 137 dollars to get the amount in Euro") +@pytest.mark.it("Call the function dollar_to_euro passing 137 dollars to get the amount in Euros") def test_declare_variable(): path = os.path.dirname(os.path.abspath(__file__))+'/app.py' with open(path, 'r') as content_file: @@ -9,7 +9,7 @@ def test_declare_variable(): assert bool(regex.search(content)) == True -@pytest.mark.it("Call the function euro_to_yen passing the Euro converted amount to get the amount in Yen") +@pytest.mark.it("Call the function euro_to_yen passing the Euros converted amount to get the amount in Yen") def test_euro_to_yen(): path = os.path.dirname(os.path.abspath(__file__))+'/app.py' with open(path, 'r') as content_file: @@ -22,4 +22,4 @@ def test_euro_to_yen(): def test_for_file_output(capsys): import app captured = capsys.readouterr() - assert "15137.609500000002\n" == captured.out \ No newline at end of file + assert "20159.139\n" == captured.out diff --git a/exercises/07-lambda-function-two/README.es.md b/exercises/07-lambda-function-two/README.es.md deleted file mode 100644 index 0a57ebd..0000000 --- a/exercises/07-lambda-function-two/README.es.md +++ /dev/null @@ -1,18 +0,0 @@ -# `07` Funciones Lambda - -Apunta y toma nota -Las funciones Lambda permiten una sintaxis corta para escribir expresiones de funciones. - -```python -multy = lambda x, y: x * y -print(multy(2,2)) -``` - -# 📝 Instrucciones: - -1. Crea una función lambda llamada `rapid` que tendrá un parámetro de string -2. Devuelve el mismo string pero eliminándole la última letra - -# 💡 Sugerencia - -Busca en Google "remove last letter form string python" (puedes usar los corchetes) diff --git a/exercises/07-lambda-function-two/README.md b/exercises/07-lambda-function-two/README.md deleted file mode 100755 index db92425..0000000 --- a/exercises/07-lambda-function-two/README.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -tutorial: "https://www.youtube.com/watch?v=1HwmTkQPeMo" ---- - -# `07` Lambda functions - -Take aim and note -Lambda functions allows a short syntax for writing function expressions. - -```python -multy = lambda x, y: x * y -print(multy(2,2)) -``` - -# 📝 Instructions: - -1. Create a lambda function called `rapid` it will take one string parameter -2. Return the same string but removing the last letter form it - -# 💡 Hint - -Google how to "remove last letter form string python" (you can use the square brackets) diff --git a/exercises/07-lambda-function-two/app.py b/exercises/07-lambda-function-two/app.py deleted file mode 100755 index fca265d..0000000 --- a/exercises/07-lambda-function-two/app.py +++ /dev/null @@ -1,5 +0,0 @@ - - - -# From this line above, plese do not change code below -print(rapid("bob")) #should print bo \ No newline at end of file diff --git a/exercises/08-Function-parameters/README.es.md b/exercises/08-Function-parameters/README.es.md new file mode 100644 index 0000000..a9b4992 --- /dev/null +++ b/exercises/08-Function-parameters/README.es.md @@ -0,0 +1,25 @@ +--- +tutorial: "https://www.youtube.com/watch?v=LuA-x5DYPr4" +--- + +# `08` Function parameters + +Puedes especificar tantos parámetros como desees en una función. + +Como desarrollador/a, encontrarás funciones con, incluso, 6 o 7 parámetros todo el tiempo. + +Los nombres de los parámetros no importan, pero debe ser **lo más explícito posible** porque esos nombres darán pistas a los otros desarrolladores (o a ti en el futuro) sobre de qué trata cada parámetro. + +## 📝 Instrucciones: + +1. Escribe la función `render_person` requerida para imprimir un string como el siguiente: + +```text +Bob is a 23 years old male born in 05/22/1983 with green eyes +``` + +## 💡 Pistas: + ++ Tienes que hacer una concatenación de string y devolver ese string. + ++ También, puedes buscar en Google "como insertar variables en un string python". diff --git a/exercises/08-Function-parameters/README.md b/exercises/08-Function-parameters/README.md new file mode 100755 index 0000000..86e9167 --- /dev/null +++ b/exercises/08-Function-parameters/README.md @@ -0,0 +1,25 @@ +--- +tutorial: "https://www.youtube.com/watch?v=BCMQF44H-BY" +--- + +# `08` Function parameters + +You can specify as many parameters as you want in a function. + +As a developer, you are going to find functions with even 6 or 7 parameters all the time. + +The names of the parameters don't matter, but you have to be **as explicit as you can** because these names will give clues to the other developers (or yourself in the future) about what is each parameter about. + +## 📝 Instructions: + +1. Please write the `render_person` function required to print a string like the following: + +```text +Bob is a 23 years old male born in 05/22/1983 with green eyes +``` + +## 💡 Hints: + ++ You have to do some string concatenation and return that string. + ++ Also, you can Google "how to insert variables into a string python". diff --git a/exercises/09-Function-parameters/app.py b/exercises/08-Function-parameters/app.py similarity index 100% rename from exercises/09-Function-parameters/app.py rename to exercises/08-Function-parameters/app.py diff --git a/exercises/08-Function-parameters/solution.hide.py b/exercises/08-Function-parameters/solution.hide.py new file mode 100644 index 0000000..1b50585 --- /dev/null +++ b/exercises/08-Function-parameters/solution.hide.py @@ -0,0 +1,7 @@ +# Your code goes here: +def render_person(name, birth_date, eye_color, age, gender): + return name + " is a " + str(age) + " years old " + gender + " born in " + birth_date + " with " + eye_color + " eyes" + + +# Do not edit below this line +print(render_person('Bob', '05/22/1983', 'green', 23, 'male')) diff --git a/exercises/09-Function-parameters/tests.py b/exercises/08-Function-parameters/tests.py similarity index 100% rename from exercises/09-Function-parameters/tests.py rename to exercises/08-Function-parameters/tests.py diff --git a/exercises/08-Function-that-returns/README.es.md b/exercises/08-Function-that-returns/README.es.md deleted file mode 100644 index ec37e28..0000000 --- a/exercises/08-Function-that-returns/README.es.md +++ /dev/null @@ -1,18 +0,0 @@ -# `08` Funciones que devuelven - -Es una muy buena práctica que las funciones devuelvan algo, incluso si es `None` si tus funciones devuelven algo, puedes crear algoritmos que usen muchas funciones al mismo tiempo. Por ejemplo, en este caso en particular tenemos dos funciones disponibles: - -```md -dollar_to_euro: que calcula el valor en euros de un valor dado en dólares. -euro_to_yen: calcula el valor en yenes de un valor dado en euros. -``` - -# 📝 Instrucciones: -Utilizando las dos funciones disponibles, imprima en la consola el valor de 137 dólares en yenes. - -# 💡 Ayuda - -Trabajando al revés: -- Nuestro valor esperado está en yenes. -- Nuestra función disponible euro_to_yen proporcionará eso -- Para llegar al euro utilizaremos la función disponible dollar_to_euro. \ No newline at end of file diff --git a/exercises/08-Function-that-returns/README.md b/exercises/08-Function-that-returns/README.md deleted file mode 100755 index d96addf..0000000 --- a/exercises/08-Function-that-returns/README.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -tutorial: "https://www.youtube.com/watch?v=-tqNmngh1PE" ---- - -# `08` Functions that return - - -Is a very good practice that all functions return something, even if it is `None` if your functions return something you can then create algorithms that use several functions at the same time. For example, in this particular case we have two functions available: - -```md -dollar_to_euro: that calculates the value in euros of a given value in dollars. -euro_to_yen: calculates the value in yen of a given value in euros. -``` - -# 📝 Instructions: -Using the two functions available, print on the console the value of 137 dollars in yen. - -# 💡 Hint - -Working backwards: -- Our expected value is in yen. -- Our available function euro_to_yen will provide that -- To get to euro we will use the available function dollar_to_euro. diff --git a/exercises/08-Function-that-returns/app.py b/exercises/08-Function-that-returns/app.py deleted file mode 100755 index 44ab611..0000000 --- a/exercises/08-Function-that-returns/app.py +++ /dev/null @@ -1,7 +0,0 @@ -def dollar_to_euro(dollar_value): - return dollar_value * 0.89 - -def euro_to_yen(euro_value): - return euro_value * 124.15 - -####### ↓ YOUR CODE BELOW ↓ ####### \ No newline at end of file diff --git a/exercises/09-Array-Methods/README.es.md b/exercises/09-Array-Methods/README.es.md new file mode 100644 index 0000000..16712e8 --- /dev/null +++ b/exercises/09-Array-Methods/README.es.md @@ -0,0 +1,17 @@ +--- +tutorial: "https://www.youtube.com/watch?v=Ne8ZRZTSaQA" +--- + +# `09` List Methods + +## 📝 Instrucciones: + +1. Escribe una función llamada `sort_names` que dada una lista de nombres, los devuelva en orden alfabético. + +## 💡 Pistas: + +- Cada lista viene con funciones predeterminadas que permiten ordenarla, ¡úsalas dentro de tu función! + ++ ¿Atascado? Lee esta página sobre cómo ordenar listas: + +https://www.freecodecamp.org/espanol/news/python-ordenar-lista-con-sort-ascendente-y-descendente-explicado-con-ejemplos/ diff --git a/exercises/09-Array-Methods/README.md b/exercises/09-Array-Methods/README.md new file mode 100755 index 0000000..b5812cd --- /dev/null +++ b/exercises/09-Array-Methods/README.md @@ -0,0 +1,17 @@ +--- +tutorial: "https://www.youtube.com/watch?v=5Wk2a16nnUY" +--- + +# `09` List Methods + +## 📝 Instructions: + +1. Write a function called `sort_names` that, given a list of names, returns them in alphabetical order. + +## 💡 Hints: + ++ Every list comes with default functions that allow sorting - use them inside your function! + ++ Stuck on sorting? Read the W3 Schools page on sorting lists: + +https://www.w3schools.com/python/ref_func_sorted.asp diff --git a/exercises/10-Array-Methods/app.py b/exercises/09-Array-Methods/app.py similarity index 99% rename from exercises/10-Array-Methods/app.py rename to exercises/09-Array-Methods/app.py index fdddc23..9d60f6b 100755 --- a/exercises/10-Array-Methods/app.py +++ b/exercises/09-Array-Methods/app.py @@ -1,4 +1,5 @@ names = ['John', 'Kenny', 'Tom', 'Bob', 'Dilan'] + ## CREATE YOUR FUNCTION HERE diff --git a/exercises/09-Array-Methods/solution.hide.py b/exercises/09-Array-Methods/solution.hide.py new file mode 100644 index 0000000..37e6930 --- /dev/null +++ b/exercises/09-Array-Methods/solution.hide.py @@ -0,0 +1,8 @@ +names = ['John', 'Kenny', 'Tom', 'Bob', 'Dilan'] + +## CREATE YOUR FUNCTION HERE +def sort_names (arr): + return sorted(arr) + + +print(sort_names(names)) diff --git a/exercises/10-Array-Methods/tests.py b/exercises/09-Array-Methods/tests.py similarity index 74% rename from exercises/10-Array-Methods/tests.py rename to exercises/09-Array-Methods/tests.py index 2effdc1..5cce1e5 100755 --- a/exercises/10-Array-Methods/tests.py +++ b/exercises/09-Array-Methods/tests.py @@ -1,11 +1,11 @@ import io, sys, pytest, os, re, mock -@pytest.mark.it("Declare the function sort_names") +@pytest.mark.it("Declare the function 'sort_names'") def test_declare_variable(): path = os.path.dirname(os.path.abspath(__file__))+'/app.py' with open(path, 'r') as content_file: content = content_file.read() - regex = re.compile(r"def sort_names\(.*\)\:") + regex = re.compile(r"def\s*sort_names\s*\(") assert bool(regex.search(content)) == True @@ -13,7 +13,7 @@ def test_declare_variable(): def test_for_functon_existence(capsys, app): assert callable(app.sort_names) -@pytest.mark.it('The function sort_names must accept 1 parameter and return a sorted one') +@pytest.mark.it('The function sort_names must accept a list and return a sorted one') def test_for_file_output(capsys): import app captured = capsys.readouterr() diff --git a/exercises/09-Function-parameters/README.es.md b/exercises/09-Function-parameters/README.es.md deleted file mode 100644 index 9059169..0000000 --- a/exercises/09-Function-parameters/README.es.md +++ /dev/null @@ -1,15 +0,0 @@ -# `09` Parámetros de funciones - -Puedes especificar tantos parámetros como desees en una función. Como desarrollador/a, encontrarás funciones con, incluso, 6 o 7 parámetros todo el tiempo. Los nombres de los parámetros no importan, pero debe ser lo más explícito posible porque esos nombres darán pistas a los otros desarrolladores (o a ti en el futuro) sobre de qué se trata cada parámetro. - -# 📝 Instrucciones: - -- Escribe la función "render_person" requerida para imprimir un string como el siguiente: - -```md -Bob is a 23 years old male born in 05/22/1983 with green eyes -``` - -# 💡 Pista - -- Tienes que hacer una concatenación de string y devolver ese string. diff --git a/exercises/09-Function-parameters/README.md b/exercises/09-Function-parameters/README.md deleted file mode 100755 index 51995c9..0000000 --- a/exercises/09-Function-parameters/README.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -tutorial: "https://www.youtube.com/watch?v=uaiDxW4LJNA" ---- - -# `09` Function parameters - -You can specify as many parameters as you want in a function. As a developer you are going to find functions with even 6 or 7 parameters all the time. The names of the parameters don't matter, but you have to be as explicit as you can because these names will give clues to the other developers (or yourself in the future) about what is each parameter about. - -# 📝 Instructions: -Please write the `render_person` function required to print a a string like the following: - -```md -Bob is a 23 years old male born in 05/22/1983 with green eyes -``` - -# 💡 Hint - -You have to do some string concatenation and return that string. diff --git a/exercises/10-Array-Methods/README.es.md b/exercises/10-Array-Methods/README.es.md deleted file mode 100644 index 392d979..0000000 --- a/exercises/10-Array-Methods/README.es.md +++ /dev/null @@ -1,13 +0,0 @@ -# `10` Métodos de listas - -# 📝 Instrucciones: - -- Escribe una función llamada sort_names que dada una lista de nombres, los devuelva en orden alfabético. - -# 💡 Pista - -- Cada lista viene con funciones predeterminadas que permiten la ordenación, ¡úsalas dentro de tu función! - -¿Atrapado en el ordenamiento? Lee la página de W3 Schools sobre ordenar los listas: - -https://www.w3schools.com/python/ref_list_sort.asp \ No newline at end of file diff --git a/exercises/10-Array-Methods/README.md b/exercises/10-Array-Methods/README.md deleted file mode 100755 index bed341a..0000000 --- a/exercises/10-Array-Methods/README.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -tutorial: "https://www.youtube.com/watch?v=jBXve_vh7dU" ---- - - -# `10` List Methods - -# 📝 Instructions: -Write a function called sort_names that, given a list of names, returns them in alphabetical order. - -# 💡 Hint -Every array comes with default functions that allows sorting- use it inside your function! - -Stuck on sorting? Read W3 Schools page on sorting lists: - -https://www.w3schools.com/python/ref_list_sort.asp diff --git a/learn.json b/learn.json index e2e7c62..dc1266d 100644 --- a/learn.json +++ b/learn.json @@ -1,31 +1,35 @@ { - "port": 3000, - "address": "https://a59821c5-aefc-458f-84bb-510905bccbff.ws-us03.gitpod.io", - "editor": "gitpod", - "configPath": { - "config": "bc.json", - "base": ".learn", - "exercises": "./exercises", - "output": ".learn/dist" + "intro": "https://youtu.be/GjQEotj3t6Y?si=cVWLDw5H_FcdOrIY", + "title": { + "us": "Learn Python Functions Interactively", + "es": "Aprende las funciones de Python Interactivamente" }, - "outputPath": "./.learn/dist", - "publicPath": "/preview", - "grading": "isolated", - "disable_grading": false, - "language": "python3", - "compiler": "python3", - "tester": "pytest", - "actions": [ - "run", - "test", - "reset" - ], - "title": "Learn Python Functions Interactively", + "slug": "python-function-exercises", "repository": "https://github.com/4GeeksAcademy/python-functions-programming-exercises", "preview": "https://github.com/4GeeksAcademy/python-functions-programming-exercises/blob/master/preview.gif?raw=true", - "description": "Learn and master functional programing by doing auto-graded interactive exercises.", + "description": { + "us": "Learn and master functional programming by doing auto-graded interactive exercises.", + "es": "Aprende y domina funciones en Python haciendo ejercicios interactivos y auto-evaluados." + }, "duration": 10, "difficulty": "easy", - "video-solutions": false, - "graded": true -} \ No newline at end of file + "projectType": "tutorial", + "videoSolutions": true, + "bugsLink": "https://github.com/learnpack/learnpack/issues/new", + "graded": true, + + "editor": { + "version": "5.0" + }, + "telemetry": { + "batch": "https://breathecode.herokuapp.com/v1/assignment/me/telemetry?asset_id=147" + }, + "video": { + "intro": { + "es": "https://www.youtube.com/watch?v=SD9lqR67yMY", + "en": "https://www.youtube.com/watch?v=06rxSj-9wM4" + } + } + + +} diff --git a/python-functions-badge.png b/python-functions-badge.png new file mode 100644 index 0000000..7148d8b Binary files /dev/null and b/python-functions-badge.png differ