Re: [Tutor] while loop

2014-04-01 Thread Scott Dunning

On Mar 31, 2014, at 5:15 AM, Dave Angel  wrote:
> 
> Do you know how to define and initialize a second local variable? 
> Create one called i,  with a value zero.
> 
> You test expression will not have a literal,  but compare the two
> locals. And the statement that increments will change i,  not
> n.

So like this?  
def print_n(s,n):
i = 0
while i < n:
print s,
i += 1

print_n('a',3)

So this is basically making i bigger by +1 every time the while loop passes 
until it passes n, then it becomes false right?  

Also, with this exercise it’s using a doctest so I don’t actually call the 
function so I can’t figure out a way to make the string’s print on separate 
lines without changing the doctest code?  

Thanks for all of the help!


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] exercise (while loop)

2014-04-01 Thread Mark Lawrence

On 01/04/2014 02:47, Danny Yoo wrote:


On Mar 31, 2014 6:22 PM, "Scott W Dunning" mailto:scott@cox.net>> wrote:
 >
 > I’m working on a few exercises and I’m a little stuck on this one.
 >
 > This is what the book has but it just gives me an endless loop.
 >
 > def square_root(a, eps=1e-6):
 > while True:
 > print x
 > y = (x + a/x) / 2
 > if abs(y-x) < epsilon:
 > break
 >
 > round(square_root(9))

Hi Scott,

Ah.  I think I see what might be wrong, but let's make sure about this.

Can you explain what 'x', 'y' are in this function?



And the difference between eps and epsilon while (ouch) we're at it.

--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] exercise (while loop)

2014-04-01 Thread Dave Angel
 Scott W Dunning  Wrote in message:
> I’m working on a few exercises and I’m a little stuck on this one.  
> 
> This is what the book has but it just gives me an endless loop.
> 
> def square_root(a, eps=1e-6):
>   while True:
>   print x
>   y = (x + a/x) / 2
>   if abs(y-x) < epsilon:
>   break
> 

Without an initial value for x, this should give an immediate
 exception.   Assuming you fix that as below,  you now have the
 problem that they never change x, so if it isn't right on first
 loop, it never will be. Next you have the problem of inconsistent
 spelling of eps. And final thing I notice is that it doesn't
 return a value.  Once you remove the debug print in the function,
  there's no way to see the result. 


> round(square_root(9))
> 
> I tweaked

Good job, you fixed most of the bugs. 

> it to what I thought was correct but when I test it I get nothing back.
> 
> def square_root(a, eps=1e-6):
>x = a/2.0
>while True:
>y = (x + a/x)/2.0
>if abs(x - y) < eps:
>return y
>x = y
> 
> round(square_root(9))
> 
> The way I tweaked it seems to work, I’m getting the correct answer on the 
> calculator but the interpreter is not returning anything when I check in 
> python.

Sure it is, you're just not printing it. You forgot to save the
 result of rounding,  and forgot to print the saved
 value.



-- 
DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loop

2014-04-01 Thread Dave Angel
 Scott Dunning  Wrote in message:
> 
> On Mar 31, 2014, at 5:15 AM, Dave Angel  wrote:
>> 
>> Do you know how to define and initialize a second local variable? 
>> Create one called i,  with a value zero.
>> 
>> You test expression will not have a literal,  but compare the two
>> locals. And the statement that increments will change i,  not
>> n.
> 
> So like this?  
> def print_n(s,n):
> i = 0
> while i < n:
> print s,
> i += 1
> 
> print_n('a',3)
> 
> So this is basically making i bigger by +1 every time the while loop passes 
> until it passes n, then it becomes false right?  
> 
> Also, with this exercise it’s using a doctest so I don’t actually call 
> the function so I can’t figure out a way to make the string’s print on 
> separate lines without changing the doctest code?  
> 

The trailing comma on the print statement is suppressing the
 newline that's printed by default. If you want them on separate
 lines, get rid of the comma.



-- 
DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] exercise (while loop)

2014-04-01 Thread Alan Gauld

On 01/04/14 02:07, Scott W Dunning wrote:

I’m working on a few exercises and I’m a little stuck on this one.

This is what the book has but it just gives me an endless loop.

def square_root(a, eps=1e-6):
while True:
print x
y = (x + a/x) / 2
if abs(y-x) < epsilon:
break



Are you sure that's what the book has?
If so I'd consider another book. That code is seriously broken.
- It prints x before an x is defined.
- It never modifies x and so the abs(y-x) will always be the
  same so the loop never breaks.
- it tests for epsilon but has eps as parameter
- It also never returns any value from the function.


round(square_root(9))


So this call will always try to round None(the default return value)
And of course it produces no output since it prints nothing.

Are you sure that's actually what is in the book?


I tweaked it to what I thought was correct but when I test it I get nothing 
back.

def square_root(a, eps=1e-6):
x = a/2.0
while True:
y = (x + a/x)/2.0
if abs(x - y) < eps:
return y
x = y


This is slightly better than the above, at least it creates an x and 
modifies it and returns a value.


And it seems to work on my system. How did you test it?


round(square_root(9))


If you used the >>> prompt this would have produced a result but if you 
used a script file you would need to print it.



HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loop

2014-04-01 Thread Alan Gauld

On 01/04/14 00:22, Scott Dunning wrote:


def print_n(s,n):
 i = 0
 while i < n:
 print s,
 i += 1

print_n('a',3)

Also, with this exercise it’s using a doctest so I don’t actually call the 
function


I have no idea what you mean buy this?
There is no doctest above and you do call the function...


so I can’t figure out a way to make the string’s print on

> separate lines without changing the doctest code?

You don't have any doctest code and the printing on one line
is a result of the comma in the print statement.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] unittests

2014-04-01 Thread Sydney Shall

Another debutant!
I am having trouble learning to use unittests.
My question is;
In the example below, did you write the class 
"SquareRootTests(unittest.TestCase):" ?

   Or do I find a set of them in the library?
   And what is the significance of the name chosen 
"self.assertAlmostEqual(square_root(3), 2.0) "?
  I take it the first argument is calling my function with its argument 
and the second argument is the correct answer?


I am quite unclear how one proceeds to set up unittests.

With many thanks in advance,

Sydney


On 01/04/2014 03:10, Danny Yoo wrote:

I tweaked it to what I thought was correct but when I test it I get nothing 
back.

def square_root(a, eps=1e-6):
x = a/2.0
while True:
y = (x + a/x)/2.0
if abs(x - y) < eps:
return y
x = y

round(square_root(9))

The way I tweaked it seems to work, I’m getting the correct answer on the 
calculator but the interpreter is not returning anything when I check in python.


I didn't want to keep you waiting, so I'll cut to the chase.  This
line here in your program:

 round(square_root(9))

computes a value... But it doesn't do anything with that value.

Try printing the value.


You may also try to see that your program is doing something effective
by "unit testing" it.  This is often a lot better than just printing
values and looking at them, because the test case will say what the
_expected_ value is, so it's more informative.



For this example, the following is a start at unit testing the above
function.  Add the following to the bottom of your program's source.


###
## See:  http://www.openp2p.com/pub/a/python/2004/12/02/tdd_pyunit.html
import unittest
class SquareRootTests(unittest.TestCase):
 def testSimpleCases(self):
 self.assertAlmostEqual(square_root(1), 1.0)
 self.assertAlmostEqual(square_root(4), 2.0)

if __name__ == '__main__':
 unittest.main()
###


Here's what it looks like when I run this:

##
$ python sqrt.py
4.472135955
.
--
Ran 1 test in 0.000s

OK
##


You can then start adding more and more to tests to gain confidence
that the code is doing something reasonable.



If we try to put in an intentionally broken test, like:

 self.assertAlmostEqual(square_root(3), 2.0)

in the body of testSimpleCases(), then we'll see the following error
when running the program:


##
$ python sqrt.py
4.472135955
F
==
FAIL: testSimpleCases (__main__.SquareRootTests)
--
Traceback (most recent call last):
   File "sq.py", line 20, in testSimpleCases
 self.assertAlmostEqual(square_root(3), 2.0)
AssertionError: 1.7320508075688772 != 2.0 within 7 places

--
Ran 1 test in 0.000s

FAILED (failures=1)
##


And that's what you want to see.  If either the test or the code is
bad, it'll say something about it.


One other thing: you will want to check a particularly insidious case
that will cause the program here to behave badly.  Consider the zero
case: square_root(0).  Write the test case.  Run it.  You'll see
something interesting.



Good luck!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor



--
Sydney Shall
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] unittests

2014-04-01 Thread Steven D'Aprano
On Tue, Apr 01, 2014 at 12:30:46PM +0100, Sydney Shall wrote:
> Another debutant!
> I am having trouble learning to use unittests.
> My question is;
> In the example below, did you write the class 
> "SquareRootTests(unittest.TestCase):" ?


Yes, that unit test was written by Danny (I assume -- I suppose he might 
have copied it from somewhere else.)

>Or do I find a set of them in the library?

There are a HUGE number of unit tests that come supplied with Python's 
source code, but they are used for testing Python itself. If your Python 
installation includes a "test" subdirectory, you can see the tests in 
there. They aren't reusable in your own code, except to read them and 
learn from them.

Instead, you write your own tests, to suit your own code, using the 
unittest module to do all the heavy-lifting.


>And what is the significance of the name chosen 
> "self.assertAlmostEqual(square_root(3), 2.0) "?
>   I take it the first argument is calling my function with its argument 
> and the second argument is the correct answer?

Correct. This "assertAlmostEqual" test takes two numbers:

- first Python calls your square_root function with 3, and gets 
  some number which hopefully will be around 1.732;

- then Python takes the number 2.0;

- finally it calls the "assertAlmostEqual" test, which tests whether or 
  not 1.732 is "almost equal" to 2.0, according to whatever scheme it 
  uses to compare two numbers. (They don't.)

If they compared "almost equal", then that specific test would have 
counted as a passing test. But since they don't, then it counts as a 
test failure. The idea is that you collect all the test failures, and 
they represent bugs in your code that should be fixed.

Although they might be a bug in the test! In this case, Danny intends 
that as a deliberately buggy test -- 1.732... is *not* "approximately 
equal" to 2, at least not according to the rules of unittest.


> I am quite unclear how one proceeds to set up unittests.

Fortunately, most of the hard work is done for you by the unittest 
module. Suppose you have a simple module with one function and you want 
to test it:

# module pizza.py
def make_pizzas(number):
return "made %d pizzas" % number


That's pretty simple, right? So simple that you can almost look at it 
and see that it works correctly.

make_pizza(5) 
=> returns "made 5 pizzas"


But let's do some nice simple unit tests for it. Start with a new file, 
which I would call "test_pizza.py", and import two modules: unittest, 
and your own module. (You need to import your module, so Python knows 
what you are testing.)

# test_pizza.py
import pizza
import unittest


The unittest module has a *lot* of complex code in it, because it has a 
lot of work that it needs to do. It needs to find the tests, initialise 
them, run the tests, collect the results, display a visual indication of 
whether tests are passing or failing, and so on. But to make this work, 
all we need do is write the tests in a way that the unittest module 
understands. We do that by using inheritance: we inherit from the 
TestCase class:


class MakePizzaTests(unittest.TestCase):
 """Collect all the tests for the make_pizza function."""


It's good practice to have a separate class for each group of related 
tests. In this case, because there's only one function, we can put all 
the tests for that function into one class. If there was a second 
function, we would use a second class:

class MakeSaladTests(unittest.TestCase):
...

but there isn't, so we won't.

At the moment, if we run the tests in this, there will be zero tests run 
and zero failed. Because we haven't actually written any tests, just the 
beginnings of it! So let's add a simple test. What's the simplest thing 
we can think of about the make_pizza function? It returns a string! So 
let's test it:


class MakePizzaTests(unittest.TestCase):
"""Collect all the tests for the make_pizza function."""

def test_make_pizza_returns_string(self):
# Test that make_pizza returns a string.
for num in (1, 2, 3, 100, 1000, 78901):
result = pizza.make_pizza(num)
self.assertIsInstance(result, str)



Here, we don't actually case what result make_pizza gives us, we just 
want to check that it returns a string. Any old string will do. It's 
good practice to start with more general tests, then work your way down 
to writing specific tests.

Notice that this test tries the function with half a dozen different 
values. If I tried it with only one value, say 23, and the test passed, 
maybe the code only passes with 23 but fails with everything else. In a 
perfect world, I could try testing with *every* possible value, but that 
might take a while, a long, long while, so I compromise by testing with 
just a handful of representative values.

Now, let's test this out. At your shell prompt (not the Python 
interactive interpreter!), run this command from inside the same 
directory as your pizza.p

[Tutor] Vending machine problem.

2014-04-01 Thread bob gailer

I'm posting this to include you in this conversation.

Recently I got the following Request: can you write me a code in python 
please or if you have one already


my response:
 print('hello world')
what more can I do for you?

 (next two lines are best guesses as I can't find the relevant emails.
Request:  can you write me a code for a vending machine  in python 
please or if you have one already

Response: I need a lot more detail.

Request:
The vending machine must have 5 prices with items
it should accept 10p, 20p 50p and £1 coins
it should allow the user to purchase a item and give him a choice of 
purchasing something else. it should display the remaining credit once 
the item is purchased. i will let you know of anything else


Tutors: sounds familiar, eh?

Response: This sounds like a homework assignment. We don't provide 
answers for homework. We will help you once you show some effort and 
tell us where you need a hand.


The requirements are kinda vague. I would have a hard time guessing 
exactly what the instructor is looking for.


Did you get any other information?

Did you get some sample of the expected input and output?

If no to the latter,  good starting place is to write down a sample 
dialog, then apply the Python functions you should have learned by now 
to make that dialog happen.


How would you store the collection of items and their prices? What 
Python data types have you learned that you could use here?


How would you look up an item to get its price?

Show us your answers to any of the above, tell us exactly where you are 
stuck, and we will see what we can do to help.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Vending machine problem.

2014-04-01 Thread bob gailer

On 4/1/2014 3:26 AM, Sebastien Gomez wrote:

The vending machine must have 5 prices with items
it should accept 10p, 20p 50p and £1 coins
it should allow the user to purchase a item and give him a choice of 
purchasing something else. it should display the remaining credit once 
the item is purchased. i will let you know of anything else


Thank you. I am copying this to tutor@python.org where a bunch of us 
hang out and collectively help others. PLEASE in future always reply-all 
so a copy goes to the list.


I am changing the subject line to something meaningful.

This sounds like a homework assignment. We don't provide answers for 
homework. We will help you once you show some effort and tell us where 
you need a hand.


The requirements are kinda vague. I would have a hard time guessing 
exactly what the instructor is looking for.


Did you get any other information?

Did you get some sample of the expected input and output?

If no th the latter,  good starting place is to write down a sample 
dialog, then apply the Python functions you should have learned by now 
to make that dialog happen.


How do you plan to store the collection of items and their prices? What 
Python data types have you learned that you could use here?


How do you plan to look up an item to get its price?

Show us your answers to any of the above, tell us exactly where you are 
stuck, and we will see what we can do to help.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] conditional execution

2014-04-01 Thread Patti Scott
I've been cheating:  comment out the conditional statement and adjust the 
indents. But, how do I make my program run with if __name__ == 'main': main() 
at the end?  I thought I understood the idea to run a module called directly 
but not a module imported.  My program isn't running, though.

Below is the last textbook example (Python Programming, Zelle) I reworked.  
Runs when I comment out the conditional statement.  I am self-studying.  Python 
2.7.3,  Notepad++,  Windows PowerShell.

# calc.pyw
# a 4-function calculator that uses Python arithmetic
# illustrates use of objects and lists to build a simple GUI

from graphics import *
from button import Button

class Calculator:
    # this class  implements simple calculator GUI
    
    def __init__(self):
        # create window for calculator
        win = GraphWin('calculator')
        win.setCoords(0,0,6,7)
        win.setBackground('slategray')
        self.win = win
        # now create the widgets
        self.__createButtons()
        self.__createDisplay()
        
    def __createButtons(self):
        # create list of buttons
        # start with all the standard-sized buttons
        # bSpecs gives center coords and labels of buttons
        bSpecs = [(2,1,'0'), (3,1,'.'), 
            (1,2,'1'), (2,2,'2'), (3,2,'3'), (4,2,'+'), (5,2,'-'),
            (1,3,'4'), (2,3,'5'), (3,3,'6'), (4,3,'*'), (5,3,'/'),
            (1,4,'7'), (2,4,'8'), (3,4,'9'), (4,4,'<-'), (5,4,'C')]
        self.buttons = []
        for (cx,cy, label) in bSpecs:
            self.buttons.append(Button(self.win, Point(cx,cy), .75,.75, label))
        # create the larger equals button
        self.buttons.append(Button(self.win, Point(4.5,1), 1.75, .75, '='))
        # activate all buttons
        for b in self.buttons:
            b.activate()
            
    def __createDisplay(self):
        bg = Rectangle(Point(.5,5.5), Point(5.5, 6.5))
        bg.setFill('white')
        bg.draw(self.win)
        text = Text(Point(3,6), "")
        text.setFace('courier')
        text.setStyle('bold')
        text.setSize(16)
        text.draw(self.win)
        self.display = text
        
    def getButton(self):
        # waits for button to be clicked and returns label of that button
        while True:
            p = self.win.getMouse()
            for b in self.buttons:
                if b.clicked(p):
                    return b.getLabel()  # method exit
    
    def processButton(self, key):
        # updates calculator display for press of this key
        text = self.display.getText()
        if key == 'C':
            self.display.setText("")
        elif key == "<-":
            # backspace, slice off the last character
            self.display.setText(text[:-1])
        elif key == '=':
            # evaluate the expression and display result
            # the try ... except mechanism catches errors in the 
            #    formula being evaluated
            try:
                result = eval(text)
            except:
                result ='ERROR'
            self.display.setText(str(result))
        else:
            # normal key press, append it to end of display
            self.display.setText(text+key)
            
    def run(self):
        # infinite event loop to process button clicks
        while True:
            key = self.getButton()
            self.processButton(key)
             
#this runs the program
if __name__ == 'main':
    #first create a calulator object
    theCalc = Calculator()
# now call the calculator's run methond
    theCalc.run()



and I get

PS C:\Users\Owner\Py Programs> python calc.py
PS C:\Users\Owner\Py Programs>



Thanks___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] conditional execution

2014-04-01 Thread Chris “Kwpolska” Warrick
On Tue, Apr 1, 2014 at 6:07 PM, Patti Scott  wrote:
> I've been cheating:  comment out the conditional statement and adjust the
> indents. But, how do I make my program run with if __name__ == 'main':
> main() at the end?  I thought I understood the idea to run a module called
> directly but not a module imported.  My program isn't running, though.

The statement is:

if __name__ == '__main__':

You’re missing the double underscores on both sides of __main__.  If
you added them in, this would work.

> Below is the last textbook example (Python Programming, Zelle) I reworked.
> Runs when I comment out the conditional statement.  I am self-studying.
> Python 2.7.3,  Notepad++,  Windows PowerShell.
>
> # calc.pyw
> # a 4-function calculator that uses Python arithmetic
> # illustrates use of objects and lists to build a simple GUI
>
> from graphics import *
> from button import Button
>
> class Calculator:

It’s better to inherit from object (i.e. use `class
Calculator(object):`) in this case.  Saves you a lot of trouble when
you encounter new-style-only things.

> # this class  implements simple calculator GUI
>
> def __init__(self):
> # create window for calculator
> win = GraphWin('calculator')
> win.setCoords(0,0,6,7)
> win.setBackground('slategray')
> self.win = win
> # now create the widgets
> self.__createButtons()
> self.__createDisplay()
>
> def __createButtons(self):
> # create list of buttons
> # start with all the standard-sized buttons
> # bSpecs gives center coords and labels of buttons
> bSpecs = [(2,1,'0'), (3,1,'.'),
> (1,2,'1'), (2,2,'2'), (3,2,'3'), (4,2,'+'), (5,2,'-'),
> (1,3,'4'), (2,3,'5'), (3,3,'6'), (4,3,'*'), (5,3,'/'),
> (1,4,'7'), (2,4,'8'), (3,4,'9'), (4,4,'<-'), (5,4,'C')]
> self.buttons = []
> for (cx,cy, label) in bSpecs:
> self.buttons.append(Button(self.win, Point(cx,cy), .75,.75,
> label))
> # create the larger equals button
> self.buttons.append(Button(self.win, Point(4.5,1), 1.75, .75, '='))
> # activate all buttons
> for b in self.buttons:
> b.activate()
>
> def __createDisplay(self):
> bg = Rectangle(Point(.5,5.5), Point(5.5, 6.5))
> bg.setFill('white')
> bg.draw(self.win)
> text = Text(Point(3,6), "")
> text.setFace('courier')
> text.setStyle('bold')
> text.setSize(16)
> text.draw(self.win)
> self.display = text
>
> def getButton(self):
> # waits for button to be clicked and returns label of that button
> while True:
> p = self.win.getMouse()
> for b in self.buttons:
> if b.clicked(p):
> return b.getLabel()  # method exit
>
> def processButton(self, key):
> # updates calculator display for press of this key
> text = self.display.getText()
> if key == 'C':
> self.display.setText("")
> elif key == "<-":
> # backspace, slice off the last character
> self.display.setText(text[:-1])
> elif key == '=':
> # evaluate the expression and display result
> # the try ... except mechanism catches errors in the
> #formula being evaluated
> try:
> result = eval(text)
> except:
> result ='ERROR'
> self.display.setText(str(result))
> else:
> # normal key press, append it to end of display
> self.display.setText(text+key)
>
> def run(self):
> # infinite event loop to process button clicks
> while True:
> key = self.getButton()
> self.processButton(key)
>
> #this runs the program
> if __name__ == 'main':
> #first create a calulator object
> theCalc = Calculator()
> # now call the calculator's run methond
> theCalc.run()
>
>
>
> and I get
>
> PS C:\Users\Owner\Py Programs> python calc.py
> PS C:\Users\Owner\Py Programs>
>
>
>
> Thanks
>
>
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Chris “Kwpolska” Warrick 
PGP: 5EAAEA16
stop html mail | always bottom-post | only UTF-8 makes sense
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] conditional execution

2014-04-01 Thread Zachary Ware
Hi Patti,

On Tue, Apr 1, 2014 at 11:07 AM, Patti Scott  wrote:
> I've been cheating:  comment out the conditional statement and adjust the
> indents. But, how do I make my program run with if __name__ == 'main':
> main() at the end?  I thought I understood the idea to run a module called
> directly but not a module imported.  My program isn't running, though.

The simple fix to get you going is to change your ``if __name__ ==
'main':`` statement to ``if __name__ == '__main__':`` (add two
underscores on each side of "main").  To debug this for yourself, try
putting ``print(__name__)`` right before your ``if __name__ ...``
line, and see what is printed when you run it in different ways.

Hope this helps, and if you need any more help or a more in-depth
explanation of what's going on, please don't hesitate to ask :)

Regards,
-- 
Zach
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] exercise (while loop)

2014-04-01 Thread Danny Yoo
> So this call will always try to round None(the default return value)
> And of course it produces no output since it prints nothing.
>
> Are you sure that's actually what is in the book?


No.  That's very much why I wanted a reference to the original source
of the problem.

Scott attributed too much to the book when he presented the problem.
In the original content,

http://greenteapress.com/thinkpython/html/thinkpython008.html#toc81

it simply presents a running dialogue exploring the idea of computing
square roots iteratively, culminating in a toplevel for-loop that
simply prints out its improving guess.  There is no function there.

This is why we want to be a bit more careful when saying "The book
said this..." following up with a paraphrase, because sometimes we can
get the paraphrasing wrong.  Similarly issues occur when one is
presenting error message content and asking for debugging advice.
Pointing to primary sources is usually a good idea, especially when
debugging or trying to get at root causes.


Let's head-off this sort of confusion quickly next time.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] unittests

2014-04-01 Thread Danny Yoo
> Yes, that unit test was written by Danny (I assume -- I suppose he might
> have copied it from somewhere else.)

Oh, who knows where I got that code from.  :P

---

Sydney, you can also take a look at some of the official documentation
of the unittest library:

https://docs.python.org/2/library/unittest.html#basic-example

You don't have to read all of it, but touching on it and knowing where
the documentation and reference is can be helpful.  The
"assertAlmostEqual" is part of the library,


https://docs.python.org/2/library/unittest.html#unittest.TestCase.assertAlmostEqual

In Scott's case, he was computing with floating point, so writing the
tests to use inexact almost-equality comparison seemed reasonable to
me.


You might find this also useful:

http://www.diveintopython.net/unit_testing/



> Although they might be a bug in the test! In this case, Danny intends
> that as a deliberately buggy test -- 1.732... is *not* "approximately
> equal" to 2, at least not according to the rules of unittest.

As a side note, when I'm writing tests, I usually write them
deliberately wrong the first time and run them to make sure that the
framework is properly reporting errors.  Only after I see failing
tests do I put in the right values for the test.  It helps me gain
more confidence that the universe is all right.


>> I am quite unclear how one proceeds to set up unittests.

Functions that take inputs and return values are usually easy to test.
 For simple programs, express a piece of functionality and some
property you expect that functionality to have.  In pure computations
like math functions, you can state the inputs and expected outputs as
a test.

By the way, if we can't even do that, to express the expected output
of our functions, then that might be a sign that we don't understand
what we're trying to code!  So there's a good reason to consider test
cases early: it forces us to put a stake in the ground and say: "This
is what the function is supposed to do, and if it doesn't do this, the
code is wrong."

If I know that a properly functioning f() is supposed to behave like this:

   f(9) ==> 3
   f(10) ==> 42
   f(1) ==> 32

then I want to write those concrete cases as tests.  An easy way to do
so is to use the unittest library to write those tests.  We can write
the cases above as the following test:

###
class MyTests(unittest.TestCase):
def testCrazyFunction(self):
   self.assertEqual(f(9), 3)
   self.assertEqual(f(10), 42)
   self.assertEqual(f(1), 32)
###

What this means is that I have some expectations on what the function
is supposed to do, apart from how it is actually coded.  That's
important, to express those expectations, because usually you trust
your expectations more than you trust the implementing code.  So if
the test breaks, usually it's the code that's broken, so it gives a
quick canary-in-the-coalmine.


If you want to explore this more, check for Kent Beck's: "Test-driven
Development: By Example".
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor