Skip to content

Commit

Permalink
Add loops story
Browse files Browse the repository at this point in the history
  • Loading branch information
Ignacio Avas committed May 2, 2017
1 parent b76a900 commit bebc6a8
Show file tree
Hide file tree
Showing 5 changed files with 120 additions and 14 deletions.
50 changes: 45 additions & 5 deletions py101/loops/README.es.rst
Original file line number Diff line number Diff line change
@@ -1,14 +1,54 @@
Boilerplate
-----------
Bucles While
------------

Insertar alguna introducción aquí.
En general las sentencias son ejecutadas secuencialmente: la primera sentencia es ejecutada el princio, seguida por la segunda, y así sucesivamente. En algunas situaciones es necesario ejecutar un bloque de código varias veces. El siguiente ejemplo imprimer los números del 1 al 100 y luego "Terminado"

.. sourcecode:: python

print('Some python code here')
mynumber = 1
while mynumber < 100:
print(mynumber)
mynumber = mynumber + 1
print("Terminado!")

Los lenguages de programación proveen varias estructuras de control que permiten flujos de control más complejos, entre los que se encuentran los búcles "while" y "for".

Los bucles while, ejecutan las sentencias dentro de él siempre y cuando cierta condición se cumpla. Cuando la condición deja de cumplirse el flujo pasa a la línea exactamente luego del bucle.

Bucles for
----------

Los bucles for tienen la habilidad de iterar sobre los items de cualquier secuencia, ya sea lista o cadena de caracteres.

.. sourcecode:: python
ingredients = ['banana', 'manzana', 'mango']
for ingredient in ingredients:
print('Ingrediente actual: {{0}}'.format(ingredient))

for some_char in 'Python':
print(some_char)

The previous example will generate the following output:

.. sourcecode::
Ingrediente actual: banana
Ingrediente actual: manzana
Ingrediente actual: mango
P
y
t
h
o
n

La función "range" puede ser usada para iterar sobre una lista de números

.. sourcecode:: python
for number in range(100):
print(number)
print("Fin!")

Desafío
-------

Describir el desafío aquí.
Usando sentencias while for e if, escribe un programa que imprima todos los números impares del 1 al 100, uno por línea.
48 changes: 44 additions & 4 deletions py101/loops/README.rst
Original file line number Diff line number Diff line change
@@ -1,14 +1,54 @@
Boilerplate
While loops
-----------

Insert some introduction here.
In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when is need to execute a block of code several number of times. The following example will print the number 1 through 100 and then "Done!":

.. sourcecode:: python

print('Some python code here')
mynumber = 1
while mynumber < 100:
print(mynumber)
mynumber = mynumber + 1
print("Done!")

Programming languages provide various control structures that allow for more complicated execution paths. They are "while" loops and "for" loops

While loops, which repeatedly executes a target statement as long as a given condition is true. When the condition becomes false, program control passes to the line immediately following the loop.

For loops
---------

The for loops have the ability to iterate over the items of any sequence, such as a list or a string.

.. sourcecode:: python
ingredients = ['banana', 'apple', 'mango']
for ingredient in ingredients:
print('Current ingredient: {{0}}'.format(ingredient))

for some_char in 'Python':
print(some_char)

The previous example will generate the following output:

.. sourcecode::
Current ingredient: banana
Current ingredient: apple
Current ingredient: mango
P
y
t
h
o
n

Also the "range" function can be used to iterate through a list of numbers

.. sourcecode:: python
for number in range(100):
print(number)
print("Done!")

Challenge
---------

Describe the challenge here
Using while, for and if statements, write a program that prints all the odd integers from 1 through 100, one per line.
4 changes: 3 additions & 1 deletion py101/loops/SOLUTION.rst
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
.. sourcecode:: python

print('Some solution here')
for number in range(100):
if number % 2 == 1:
print(number)
24 changes: 21 additions & 3 deletions py101/loops/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,20 @@
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"""

correct_output = '\n'.join(
[str(number) for number in range(1, 100, 2)] +
['']
)


def __init__(self, candidate_code, file_name='<inline>'):
"""Init the test"""
super(TestOutput, self).__init__()
Expand All @@ -31,9 +38,20 @@ 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')
code = compile(self.candidate_code, self.file_name, 'exec', optimize=0)
exec(code)

if_statements = [
node
for node in ast.walk(body)
if isinstance(node, ast.If)
]
self.assertGreater(len(if_statements), 0, "Should have at least on if statement")

self.assertMultiLineEqual(self.correct_output,
self.__mockstdout.getvalue(),
"Output should be correct")


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


Expand Down Expand Up @@ -62,7 +63,12 @@ def __init__(self, test_module, good_solution):
else:
print("Error")
"""
)
),
AdventureData(
py101.loops,
"""for number in range(100):
if number % 2 == 1: print(number)"""
),
]


Expand Down

0 comments on commit bebc6a8

Please sign in to comment.