Skip to content

Commit

Permalink
Merge pull request #5 from igui/master
Browse files Browse the repository at this point in the history
Adventure 2 - Variables
  • Loading branch information
pricco committed May 15, 2017
2 parents 977e887 + 7e12291 commit 3286659
Show file tree
Hide file tree
Showing 72 changed files with 2,465 additions and 27 deletions.
8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,11 @@ target/

# pyenv python configuration file
.python-version

# Idea (PyCharms and Idea based IDEs)
.idea/

# Local test files
test.py
requirements_local.pip

10 changes: 10 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,21 @@ A pyschool story for learning Python Basics.
Credits
-------

*“The only way to learn a new programming language is by writing programs in it.”*

\― `Dennis Ritchie <https://wikipedia.org/wiki/Dennis_Ritchie>`_

This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template.

.. _Cookiecutter: https://github.com/audreyr/cookiecutter
.. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage

Also we inspired in the following sites, which are great sources for learning Python basics:

* `workshopper/javascripting <https://github.com/workshopper/javascripting>`_
* `learnpython.org <https://www.learnpython.org>`_
* `tutorialspoint.com <https://www.tutorialspoint.com/python>`_

License
-------

Expand Down
11 changes: 6 additions & 5 deletions py101/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from story.story import BaseStory
from story.translation import gettext as _

from . import (introduction,)
from . import (introduction, variables, lists, operators, formatting, strings,
conditions, loops, functions, classes, dictionaries, modules)


__author__ = """Sophilabs"""
Expand All @@ -10,9 +11,9 @@


class Story(BaseStory):
"Python Essentials Adventure"
"""Python Essentials Adventure"""
name = 'py101'
title = _('Learn Python essentials using the command line')
adventures = [
introduction
]
adventures = (introduction, variables, lists, operators, formatting,
strings, conditions, loops, functions, classes, dictionaries,
modules)
14 changes: 14 additions & 0 deletions py101/boilerplate/README.es.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
Boilerplate
-----------

Insertar alguna introducción aquí.

.. sourcecode:: python

print('Some python code here')


Desafío
-------

Describir el desafío aquí.
14 changes: 14 additions & 0 deletions py101/boilerplate/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
Boilerplate
-----------

Insert some introduction here.

.. sourcecode:: python

print('Some python code here')


Challenge
---------

Describe the challenge here
3 changes: 3 additions & 0 deletions py101/boilerplate/SOLUTION.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.. sourcecode:: python

print('Some solution here')
51 changes: 51 additions & 0 deletions py101/boilerplate/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
""""
Boilerplate Adventure
Author: Ignacio Avas ([email protected])
"""
import codecs
import io
import sys
import unittest
from story.adventures import AdventureVerificationError, BaseAdventure


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

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

def setUp(self):
self.__old_stdout = sys.stdout
sys.stdout = self.__mockstdout = io.StringIO()

def tearDown(self):
sys.stdout = self.__old_stdout
self.__mockstdout.close()

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")


class Adventure(BaseAdventure):
"""Boilerplate Adventure"""
title = '<Insert Title Here>'

@classmethod
def test(cls, sourcefile):
"""Test against the provided file"""
suite = unittest.TestSuite()
raw_program = codecs.open(sourcefile).read()
suite.addTest(TestOutput(raw_program, sourcefile))
result = unittest.TextTestRunner().run(suite)
if not result.wasSuccessful():
raise AdventureVerificationError()
81 changes: 81 additions & 0 deletions py101/classes/README.es.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
Clases and Objectos
-------------------

Las clases son una encapsulación de estado y comportamiento, definido por
variables y miembros respectivamente, en un solo tipo. Los objetos son
instancias de clases que tienen sus variables y funciones desde una clase.
Las clases son esencialmente una plantilla para crear objetos

Una clase básica se ve como sigue:

.. sourcecode:: python

class Persona(object):
def __init__(self, name):
self.name = name

def print_name(self):
print("Hola {}".format(self.name))

La función especial "__init__" se llama cuando se crea un objeto Persona.
Pueded definir y asignar variables que se usan dentro del objeto Persona
creado. Por ejemplo la clase de arriba asigna una nueva variable dentro del
objeto Persona, llamada "name" usando el valor provisto a la función
__init__. El parámetro "self" hace referencia al objeto implícito que se
está creando. En otros lenguajes de programación el objeto implícito se
denomina "this".

El siguiente código crea una instancia de Persona pasando 'Alex' a la
función __init__

.. sourcecode:: python

myperson = Person('Alex')

En la clase Person "print_name" es una función definida por el usuario que
puede ser invocada para realizar cierta tarea. La difrencia entre una
función definida dentro de una clase y otra que no lo está es que las
funciones definidas dentro de clases tienen acceso a las variables
individuales. Esas variables son referencidas accediendo al objeto self.

Para invocar una función de un objeto se puede utilizar la siguiente sintaxis.

.. sourcecode:: python

alex = Person('Alex')
alex.print_name() # Imprime 'Hola Alex'


Las variables del objeto pueden ser accedidas también utilizando una
sintáxis similar:

.. sourcecode:: python

alex = Person('Alex')
john = Person('Johnnie')
print(alex.name) # Imprime 'Alex'
print(john.name) # Imprime 'Johnnie'
john.name = 'John Walker'
print(john.name) # Imprime 'John Walker'


Desafío
-------

Considera la clase "Vehicle" que almacena el costo de un Vehículo, y una
función que retorna información acerca del vehículo como una cadena. Escribe
un programa que imprima las líneas "Vehicle cost is 12000" y "Vechicle cost is
5999.99" en ese orden usando la clase Vehicle y la función description

.. sourcecode:: python

# No modifiques este código
class Vehicle:
def __init__(self, cost):
self.cost = cost

def description(self):
return "Vehicle cost is {}".format(self.cost)

# Tu código va aquí

79 changes: 79 additions & 0 deletions py101/classes/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
Classes and Objects
-------------------

Classes are an encapsulation of state and behaviour, defined by variables and
members respectively, into a single type. Objects are instances of classes,
which get their variables and functions from classes. Classes are
essentially a template to create objects.

A basic class would look something like this:

.. sourcecode:: python

class Person(object):
def __init__(self, name):
self.name = name

def print_name(self):
print("Hello {}".format(self.name))

The special "__init__" function is called when a Person object is created.
It can define and assigne variables inside a created Person object. For
example the class above assigns a new variable inside a Person object called
name using the value provided to the __init__ function. The "self" parameter
makes reference to the implicit object which was created. In other
programming languages the implicit object is called "this".

The following code creates an instance of Person, passing 'Alex' to the
__init__ function.

.. sourcecode:: python

myperson = Person('Alex')

In the Person class "print_name" is a user defined function that can be
invoked to perform custom behaviour. The difference between a function
defined inside a class an user defined function which not, is that functions
inside classes do have access to the individual variables, those variables
are referenced by accessing the self object.

To invoke a function from an object, the following syntax can be used:

.. sourcecode:: python

alex = Person('Alex')
alex.print_name() # Prints 'Hello Alex'


Object variables can be accessed as well, by using a similar syntax

.. sourcecode:: python

alex = Person('Alex')
john = Person('Johnnie')
print(alex.name) # Prints 'Alex'
print(john.name) # Prints 'Johnnie'
john.name = 'John Walker'
print(john.name) # Prints 'John Walker'


Challenge
---------

Consider a class called "Vehicle" that stores a Vehicle cost, and a
function that returns information about the vehicle as an string. Write a
program that prints the lines "Vechicle cost is 12000" and "Vechicle cost is
5999.99" in that order using the Vehicle class and the description function

.. sourcecode:: python

# dont modify this code
class Vehicle:
def __init__(self, cost):
self.cost = cost

def description(self):
return "Vehicle cost is {}".format(self.cost)

# your code goes here

14 changes: 14 additions & 0 deletions py101/classes/SOLUTION.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
.. sourcecode:: python

class Vehicle:
def __init__(self, cost):
self.cost = cost

def description(self):
return "Vehicle cost is {}".format(self.cost)

car1 = Vehicle(12000)
car2 = Vehicle(5999.99)

print(car1.description())
print(car2.description())
57 changes: 57 additions & 0 deletions py101/classes/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
""""
Classes Adventure
Author: Ignacio Avas ([email protected])
"""
import codecs
import io
import sys
import unittest
from story.adventures import AdventureVerificationError, BaseAdventure
from story.translation import gettext as _


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

expected_output = "Vehicle cost is 12000\nVehicle cost is 5999.99\n"

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

def setUp(self):
self.__old_stdout = sys.stdout
sys.stdout = self.__mockstdout = io.StringIO()

def tearDown(self):
sys.stdout = self.__old_stdout
self.__mockstdout.close()

def runTest(self):
"""Makes a simple test of the output"""

# TODO check for class definition, and check if method was called
code = compile(self.candidate_code, self.file_name, 'exec', optimize=0)
exec(code)
self.assertMultiLineEqual(self.expected_output,
self.__mockstdout.getvalue(),
"Should have same output"
)


class Adventure(BaseAdventure):
"""Classes Adventure"""
title = _('Classes')

@classmethod
def test(cls, sourcefile):
"""Test against the provided file"""
suite = unittest.TestSuite()
raw_program = codecs.open(sourcefile).read()
suite.addTest(TestOutput(raw_program, sourcefile))
result = unittest.TextTestRunner().run(suite)
if not result.wasSuccessful():
raise AdventureVerificationError()
Loading

0 comments on commit 3286659

Please sign in to comment.