Skip to content

Commit

Permalink
Functions adventure
Browse files Browse the repository at this point in the history
  • Loading branch information
Ignacio Avas committed May 3, 2017
1 parent 0f42915 commit 2fc5121
Show file tree
Hide file tree
Showing 5 changed files with 131 additions and 15 deletions.
50 changes: 44 additions & 6 deletions py101/functions/README.es.rst
Original file line number Diff line number Diff line change
@@ -1,14 +1,52 @@
Boilerplate
-----------
Funciones
---------

Insertar alguna introducción aquí.
Una función es un bloque de código organizado y reusable que puede ser utilizado para realizar cierta acción. Python ofrece un número importante de funciones predefinidas como print() o len(), pero se pueden definir nuevas funciones en el código, que son denominadas funciones definidas por el usuario.

.. sourcecode:: python

print('Some python code here')
def di_hola():
print("Hola")
print("¿Cómo estás?")

Las funciones también pueden recibir argumentos: variables que se pasan desde el invocador a la función. Por ejemplo

.. sourcecode:: python

def decir_hola_con_nombre(name):
print("Hola {{0}}".format(name))
print("¿Cómo estás?")

Las funciones también pueden retornar un valor al invocador, usando la palabra clave "return", por ejemplo:

.. sourcecode:: python

def hacer_division(x, y):
if y != 0:
return x / y
else:
print("y no puede ser 0")
return 0

En algunos casos las funciones pueden ser vacías y no hacer nada. Por ejemplo si se planea ser escritas luego. En esos casos, esas funciones solo tienen la palabra clave "pass" en el cuerpo

.. sourcecode:: python

def a_ser_escrita_luego(lista_de_ingredientes):
pass


Llamando a una función
----------------------
Definir una función solo le da un nombre, especifica los parámetros que se van a incluir en la función y estructura los bloques de código. Una vez que la estructura de una función está terminada, puede ser ejecutada llamándola. En el siguiente ejemplo se llaman a las funciones que fueron definidas previamente:

.. sourcecode:: python

result = hacer_division(2343, 22)
decir_hola_con_nombre("Alex")
print("Resultado es {{0}}".format(result))

Desafío
-------
---------

Describir el desafío aquí.
Crea un programa que imprima los números pares desde el 2 al 100 inclusive, definiendo al menos una función y llamándola.
50 changes: 45 additions & 5 deletions py101/functions/README.rst
Original file line number Diff line number Diff line change
@@ -1,14 +1,54 @@
Boilerplate
-----------
Functions
---------

A function is a block of organized, reusable code that is used to perform a single, related action. Python already define many built-in functions like print() or len(), but new functions can be defined in the code, which are called user-defined functions.

.. sourcecode:: python

def say_hello():
print("Hello")
print("How are you?")

Insert some introduction here.
Functions may also receive arguments (variables passed from the caller to the function). For example:

.. sourcecode:: python

print('Some python code here')
def say_hello_with_name(name):
print("Hello {{0}}".format(name))
print("How are you?")

Also they may return a value to the caller, using "return" keyword. For example:

.. sourcecode:: python

def make_division(x, y):
if y != 0:
return x / y
else:
print("y can't be zero")
return 0

In rare cases some functions may be empty and do nothing. For example if they are planned to be written later. In those cases, those functions have only the "pass" keyword on the body:

.. sourcecode:: python

def will_be_written_tomorrow(list_of_ingredients):
pass


Calling a Function
------------------

Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code. Once the basic structure of a function is finalized, it can be executed by calling it. Following is the example to call the previous defined functions:

.. sourcecode:: python

result = make_division(2343, 22)
say_hello_with_name("Alex")
print("Result is {{0}}".format(result))

Challenge
---------

Describe the challenge here
Create a program that prints the even numbers from 2 through 100 defining at least a function and calling it.

7 changes: 6 additions & 1 deletion py101/functions/SOLUTION.rst
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
.. sourcecode:: python

print('Some solution here')
def print_even(upper_bound):
for number in range(upper_bound+1):
if number % 2 == 0 and number > 1:
print(number)

print_even(100)
29 changes: 26 additions & 3 deletions py101/functions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,16 @@
import io
import sys
import unittest
import ast
from story.adventures import AdventureVerificationError, BaseAdventure
from story.translation import gettext as _


class TestOutput(unittest.TestCase):
"""Adventure test"""

expected_output = '\n'.join([str(element) for element in range(2, 101, 2)]) + '\n'

def __init__(self, candidate_code, file_name='<inline>'):
"""Init the test"""
super(TestOutput, self).__init__()
Expand All @@ -31,9 +34,29 @@ def tearDown(self):
def runTest(self):
"""Makes a simple test of the output"""

#code = compile(self.candidate_code, self.file_name, 'exec', optimize=0)
#exec(code)
self.fail("Test not implemented")
body = ast.parse(self.candidate_code, self.file_name, 'exec')

defined_functions = set([
node.name
for node in ast.walk(body)
if isinstance(node, ast.FunctionDef)
])

called_functions = set([
node.func.id
for node in ast.walk(body)
if isinstance(node, ast.Call)
])

self.assertTrue(len(defined_functions & called_functions) > 0, "Should call at least one defined function")

code = compile(self.candidate_code, self.file_name, 'exec', optimize=0)
exec(code)

self.assertMultiLineEqual(self.expected_output,
self.__mockstdout.getvalue(),
"Output should match expected output"
)


class Adventure(BaseAdventure):
Expand Down
10 changes: 10 additions & 0 deletions tests/test_story.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import py101.strings
import py101.conditions
import py101.loops
import py101.functions
import unittest


Expand Down Expand Up @@ -69,6 +70,15 @@ def __init__(self, test_module, good_solution):
"""for number in range(100):
if number % 2 == 1: print(number)"""
),
AdventureData(
py101.functions,
"""
def print_even(upper_bound):
for number in range(upper_bound+1):
if number % 2 == 0 and number > 1:
print(number)
print_even(100)"""
)
]


Expand Down

0 comments on commit 2fc5121

Please sign in to comment.