Skip to content

Commit

Permalink
Add conditions lesson
Browse files Browse the repository at this point in the history
  • Loading branch information
Ignacio Avas committed May 2, 2017
1 parent b3f52c8 commit b76a900
Show file tree
Hide file tree
Showing 5 changed files with 162 additions and 14 deletions.
56 changes: 51 additions & 5 deletions py101/conditions/README.es.rst
Original file line number Diff line number Diff line change
@@ -1,14 +1,60 @@
Boilerplate
-----------
Toma de decisiones
------------------

Insertar alguna introducción aquí.
En programación, la toma de decisiones es la anticipación a las condiciones que pueden ocurrir durante la ejecución del programa, así como la espcecificación de las acciones tomadas de acuerdo a las condiciones. El programa determina que acción tomar y que sentencias ejecutar dependiendo del valor de las expresiones. El siguiente es un ejemplo de toma de decisiones encontrado en la mayoría de los lenguajes de programación:

.. sourcecode:: python

print('Some python code here')
edad = 45

if edad > 18:
print('Eres muy viejo')

Python provee las sentencias "if", que consisten de una expressión booleana (True o False) seguida de uno o más sentencias, como la mostrada arriba. Las sentencias if pueden ser sucedidas por sentencias "else" que son ejecutadas si la condición del "if" no se cumple.

.. sourcecode:: python

x = 32
y = 2

if y == 0:
print('El divisor no debe ser 0')
else:
print('El resultado es{0}'.format(x/y))

Las sentencias if pueden ser anidadas, permitiendo ejecutar código más complejo.

.. sourcecode:: python

age = 23
if age < 18:
if age < 0:
print('Age no es válido')
print('Eres muy pequeño para manejar')
else:
print('Puedes manejar')



Desafío
-------

Describir el desafío aquí.
Usando el siguiente programa, modifica las variables para que el programa imprima las líneas "1", "2" y "3".

.. sourcecode:: python

# change this code
first_number = 0
second_number = 0

# don't change this code
if first_number > 15:
print("1")
if second_number > 15:
print("2")

if first_number < second_number:
print("3")
else:
print("Error")

56 changes: 51 additions & 5 deletions py101/conditions/README.rst
Original file line number Diff line number Diff line change
@@ -1,14 +1,60 @@
Boilerplate
-----------
Decision making
---------------

Insert some introduction here.
Decision making is anticipation of conditions occurring while execution of the program and specifying actions taken according to the conditions. Decision structures evaluate multiple expressions which produce True or False. The program determine which action to take and which statements to execute, depending of the value of the expressions. Following is an example of a typical decision making structure found in most of the programming languages:

.. sourcecode:: python

print('Some python code here')
age = 45

if age > 18:
print('You are too old')

Python provides the "if" statements, consisting of a boolean expression followed by one or more statementsIf statements can be followed by an else "else" statements executed if the top "if" condition doesn't held.

.. sourcecode:: python

x = 32
y = 2

if y == 0:
print('divisor y should not be zero')
else:
print('Result is {0}'.format(x/y))

If statements can be nested allowing more complex logic to be executed:

.. sourcecode:: python

age = 23
if age < 18:
if age < 0:
print('Age is invalid')
print('You are too young to drive')
else:
print('You are allowed to drive')



Challenge
---------

Describe the challenge here
Using the following program, modify the variables so the program prints the lines "1", "2", and "3"

.. sourcecode:: python

# change this code
first_number = 0
second_number = 0

# don't change this code
if first_number > 15:
print("1")
if second_number > 15:
print("2")

if first_number < second_number:
print("3")
else:
print("Error")

15 changes: 14 additions & 1 deletion py101/conditions/SOLUTION.rst
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
.. sourcecode:: python

print('Some solution here')
# change this code
first_number = 20
second_number = 22

# don't change this code
if first_number > 15:
print("1")
if second_number > 15:
print("2")

if first_number < second_number:
print("3")
else:
print("Error")
30 changes: 27 additions & 3 deletions py101/conditions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,32 @@
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"""

inmutable_code_str = """
if first_number > 15:
print("1")
if second_number > 15:
print("2")
if first_number < second_number:
print("3")
else:
print("Error")
"""

def __init__(self, candidate_code, file_name='<inline>'):
"""Init the test"""
super(TestOutput, self).__init__()
self.candidate_code = candidate_code
self.file_name = file_name
self.inmutable_code = ast.parse(self.inmutable_code_str, file_name, 'exec')

def setUp(self):
self.__old_stdout = sys.stdout
Expand All @@ -31,9 +45,19 @@ 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')

# Looks if the code is the same as the provided code.
body_dump = ast.dump(body)
for node in self.inmutable_code.body:
self.assertTrue(body_dump.find(ast.dump(node)) >= 0, "Provided code should not be modified")

code = compile(self.candidate_code, self.file_name, 'exec')
exec(code)
self.assertMultiLineEqual('1\n2\n3\n',
self.__mockstdout.getvalue(),
'Output is not correct')



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


Expand Down Expand Up @@ -42,6 +43,24 @@ def __init__(self, test_module, good_solution):
print(mystring.upper())
print(mystring.lower())
print(mystring.split(' '))
"""
),
AdventureData(
py101.conditions,
"""# change this code
first_number = 20
second_number = 22
# don't change this code
if first_number > 15:
print("1")
if second_number > 15:
print("2")
if first_number < second_number:
print("3")
else:
print("Error")
"""
)
]
Expand Down

0 comments on commit b76a900

Please sign in to comment.