Re: [Tutor] Fwd: Function works one time then subsequently fails

2015-04-29 Thread Jim Mooney Py3.4.3winXP
Sure, but let me include the full working program after fixup

On 29 April 2015 at 19:09, Cameron Simpson  wrote:

>
> These could all do with docstrings. add() is pretty obvious, but the
> distinction between minus() and subtract() could do with elaboration.

etc, etc.

Thanks. Very comprehensive. I'll print it out and ponder it ;')

-- 
Jim

"What a rotten, failed experiment. I'll start over. Maybe dogs instead of
monkeys this time." --God
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] raise exception works as planned in program but not when imported into testing module

2015-04-29 Thread Jim Mooney Py3.4.3winXP
On 29 April 2015 at 21:14, Dave Angel  wrote:

> But why are you surprised?  There's no try/except protecting the latter
> line, so the exception will be uncaught, and you'll see it reported in
> parse_string().
>

I think I meant something like this. An exception in a function is caught
by the caller. I imported the program that did this into the test program,
expecting the exception to still be caught when the parse_string was
called, by the try except else block in the mainroutine of the imported
program..

def excepter():
raise ValueError

try:
excepter()
except ValueError:
print("Exception caught after function call")

REPL
>>>
Exception caught after function call
>>>


-- 
Jim

"What a rotten, failed experiment. I'll start over. Maybe dogs instead of
monkeys this time." --God
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Ancient Python versions (was: Is there a way to store and later use comparison operators (<, <=, =, >=, >) ?)

2015-04-29 Thread Ben Finney
boB Stepp  writes:

> One problem I have with searching the Python documentation is this:
> https://docs.python.org/release/2.4.4/lib/lib.html

If you actually need to read the documentation specifically for a Python
version that has not been supported since 2008, then I agree that is a
problem.

The documentation has improved since then. If you want newer-looking
documentation, maybe you should not expect it from a Python released
nearlt a decade ago?

-- 
 \ “Not to be absolutely certain is, I think, one of the essential |
  `\ things in rationality.” —Bertrand Russell |
_o__)  |
Ben Finney

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


Re: [Tutor] How to use Git from Windows PC for files on Solaris machine where Git cannot be installed?

2015-04-29 Thread Dave Angel

On 04/30/2015 12:28 AM, boB Stepp wrote:

The main danger as I see it is that if I am not careful, then the code
on the dev environment could diverge from the state of code on my
Windows PC, i.e., I forgot to do the scp part. But when I am actively
working on a section of code I always insert a few print statements
(Py 2.4!) to verify I am getting what I should when I test it
out--even if I don't have an actual problem yet. And so far this has
immediately revealed those few instances so far when I forgot to save
to the dev machine (Usually when someone has interrupted my workflow,
a near constant occurrence at work.).




Add an automatic file copy to the save-key definition in your editor. 
Then whenever you save the file locally, you'll also be copying it to 
the master location.


If that's too hard, or your editor can't support it, write a bash script 
that does an rsynch every 10 minutes.


rsynch does what scp does, but it works on whole directories, copying 
only those files that changed.  And you can fine tune what "changed" means.


There are other, less resource intense approaches, but if one of these 
works, it'll be pretty painless to set up.


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


Re: [Tutor] How to use Git from Windows PC for files on Solaris machine where Git cannot be installed?

2015-04-29 Thread boB Stepp
On Wed, Apr 29, 2015 at 10:39 PM, Cameron Simpson  wrote:
> On 29Apr2015 22:10, boB Stepp  wrote:

>> On the smart enterprise where we (now) do our clinical planning they
>> are very strict: no installing any external software; no accessing the
>> Internet; no email; etc. Not all centers adhere to this level of
>> strictness, but ours does. [...] But I am reluctant to do
>> anything that I am not allowed to replicate on smart enterprise. I am
>> trying to keep it as close to identical to the actual clinical
>> environment as I can.
>
>
> And fair enough too. I frequently wish our developers' dev environments more
> rigorously modelled the target environment.
>
>> Perhaps this is misguided on my part?
>
>
> Not necessarily.
>
> But I would be inclined to distinguish your working tools from the target
> environment.
>
> For example, I commend you making your dev environment as close to identical
> to the actual clinical environment as you can. But I wouldn't deprive
> yourself of tools that enhance your code management practices without
> affecting that environment.
>
> For example, there is much to be said for tracking your changes with a tool
> like git or hg. It encourages your to annotate your changes, and lets you
> review history to see when and why some change occurred, especially if a new
> bug has arisen. Distributed version control systems like git and hg also
> make it easier to work on distinct changes to the same code as separate work
> processes; of course the price for such a workflow is that you need to merge
> the two things later and ensure that they do not interact badly.

Totally, totally convinced of the correctness of this. Actively
working to implement this. See below.

> If you're serious about keeping the two environments very similar, you could
> always do your _coding_ on a third platform (a laptop or whatever) using
> your desired tools and _deploy_ the code to the dev (and later, prod)
> environments from there, keeping the dev environment pristine. By "deploy",
> that can be as simple as copying the code to the target.

That is what I have implemented as of today. I installed Git on my
Windows PC where I have been doing my actual coding anyway, created
the needed repositories, including an extra one on our intranet in
case my PC dies, etc. The current project is now in version control.
After doing some editing and saving, I use the Git bash shell that
came with Git and scp the file(s) to the dev environment, do my
testing (Still manual; working on getting automated, but this will
have more of a learning curve for me than using Git.), etc. When I get
a meaningful chunk of something done, I add and commit in Git on the
Windows PC. Less often I push to the intranet repo. Your comments
suggest that I am on a reasonable track.

The main danger as I see it is that if I am not careful, then the code
on the dev environment could diverge from the state of code on my
Windows PC, i.e., I forgot to do the scp part. But when I am actively
working on a section of code I always insert a few print statements
(Py 2.4!) to verify I am getting what I should when I test it
out--even if I don't have an actual problem yet. And so far this has
immediately revealed those few instances so far when I forgot to save
to the dev machine (Usually when someone has interrupted my workflow,
a near constant occurrence at work.).


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


Re: [Tutor] raise exception works as planned in program but not when imported into testing module

2015-04-29 Thread Dave Angel

On 04/29/2015 09:05 PM, Jim Mooney Py3.4.3winXP wrote:

I raised an exception in the parse_string function in my math parser
program, function_tosser.py, and caught it in the calling routine, and that
worked fine. But when I imported function_tosser.py into a test program,
tester.py, it threw the exception in the parse_string function instead of
handling it in the try block in the calling routine. Why did it work in one
and not the other? The testing program works fine if I return None as I did
before, instead of raising the exception.


It'd be nice if you were explicit about which code you're describing.  I 
can make guesses, but your above paragraph leaves a lot of confusion.


I'm guessing you're talking about the line in parse_string():
raise ValueError

And I assume you're talking about it being referenced in the other file 
by the line:

print(ft.parse_string(monkey_wrench), '\n')

But why are you surprised?  There's no try/except protecting the latter 
line, so the exception will be uncaught, and you'll see it reported in 
parse_string().


> in the try block in the calling routine.

What routine is that?  The line I quoted above is in top-level code, not 
in a routine. And it doesn't have a try/except there.




# function_tosser.py
"""
Takes the name of a binary math operation and two numbers from input,
repeatedly, and displays the results until done
"""


def add(a, b):
 return a + b


def subtract(a, b):
 return b - a

def minus(a, b):
 return a - b


def multiply(a, b):
 return a * b


def divide(a, b):
 return a / b


operations = {'add': add, '+': add, 'plus': add, 'subtract': subtract,
'subtracted': subtract,
   '-': minus, 'minus': minus, 'multiply': multiply, '*':
multiply, 'multiplied': multiply,
   'times': multiply, 'divide': divide, '/': divide, 'divided':
divide}

def test_number(astring):
 """
 Input: A string that should represent a valid int or float. Output:
 An int or float on success. None on failure.
 """
 for make_type in (int, float):
 try:
 return make_type(astring)
 except ValueError: # Previously returned None, which worked. This
works fine here but when imported into the test program
 pass   # it doesn't wait for the try block in the
calling routine.
 return None


def parse_string(math_string):
 """Input: A math string with a verbal or mathematical operation
 and two valid numbers to operate on. Extra numbers and operations
 are ignored. Output: A tuple containing a function corresponding
 to the operation and the two numbers. Returns None on failure.
 """
 operation = None
 tokens = math_string.split()
 numbers = []
 for token in tokens:
 if token in operations:
 operation = operations[token]
 elif test_number(token) != None:
 numbers.append(test_number(token))
 if len(numbers) > 1:
 break
 if operation is None or len(numbers) < 2:
 raise ValueError
 else:
 return operation, numbers[0], numbers[1]

if __name__ == "__main__":
 instructions = '''Enter two numbers and one of the four basid math
operations,
 either mathematical or verbal. i.e. 3 + 2, 12 divided by 14, 10 minus
4, etc.
 Enter done to quit.
 '''
 try:
 user_input = input(instructions)
 while True:
 if user_input == 'done':
 break
 try:
 result = parse_string(user_input)
 except ValueError:
 print("Not a valid math operation.")
 else:
 func, num1, num2 = result
 print(func(num1, num2))
 user_input = input()
 except KeyboardInterrupt:
 print("Program terminated by user")

# tester.py

'''Test function_tosser.py mainlogic against random operators, operands,
and bad input'''
import random
import function_tosser as ft
valid_terms = list(ft.operations.keys())
def eval_test():
 pass

trash = ['1 +', 'blah', '3-4', 'gargle', 'Newt Gingrich',
 ",", '{+=-33.44 minus12 3 times blarg 1445641654644555455']

for ctr in range(50):
 term = ' ' + random.choice(valid_terms) + ' '
 num1 = str(random.randint(1,1000))
 num2 = str(random.randint(1,1000))
 if term == ' subtract ' or term == ' subtracted ': term = ' subtracted
from '
 if ctr % 10 == 0: # stress testing for a None failure
 monkey_wrench = random.choice(trash)
 print(ft.parse_string(monkey_wrench), '\n')
 else:
 func, num1, num2 = ft.parse_string(num1 + term + num2)
 print(func, num1, term, num2)
 print('result:',func(num1, num2), '\n')





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


Re: [Tutor] How to use Git from Windows PC for files on Solaris machine where Git cannot be installed?

2015-04-29 Thread Cameron Simpson

On 29Apr2015 22:10, boB Stepp  wrote:

On Wed, Apr 29, 2015 at 9:40 PM, Cameron Simpson  wrote:

On 29Apr2015 12:12, boB Stepp  wrote:

... (3) install git if needed ...


It seems Git is needed, but I am not allowed to install it on the
Solaris workstation. So is there a way around this?


What do you mean by "install"? Bear in mind that while you may be forbidden
from installing git in the main areas (/usr, /usr/local, whatever), you may
be free to install it in your own home directory. It is just an
executable...


On the smart enterprise where we (now) do our clinical planning they
are very strict: no installing any external software; no accessing the
Internet; no email; etc. Not all centers adhere to this level of
strictness, but ours does. [...] But I am reluctant to do
anything that I am not allowed to replicate on smart enterprise. I am
trying to keep it as close to identical to the actual clinical
environment as I can.


And fair enough too. I frequently wish our developers' dev environments more 
rigorously modelled the target environment.



Perhaps this is misguided on my part?


Not necessarily.

But I would be inclined to distinguish your working tools from the target 
environment.


For example, I commend you making your dev environment as close to identical to 
the actual clinical environment as you can. But I wouldn't deprive yourself of 
tools that enhance your code management practices without affecting that 
environment.


For example, there is much to be said for tracking your changes with a tool 
like git or hg. It encourages your to annotate your changes, and lets you 
review history to see when and why some change occurred, especially if a new 
bug has arisen. Distributed version control systems like git and hg also make 
it easier to work on distinct changes to the same code as separate work 
processes; of course the price for such a workflow is that you need to merge 
the two things later and ensure that they do not interact badly.


If you're serious about keeping the two environments very similar, you could 
always do your _coding_ on a third platform (a laptop or whatever) using your 
desired tools and _deploy_ the code to the dev (and later, prod) environments 
from there, keeping the dev environment pristine. By "deploy", that can be as 
simple as copying the code to the target.


Just thoughts; of course you must choose practices that suit your needs and 
plans.


Cheers,
Cameron Simpson 

Nothing is impossible for the man who doesn't have to do it.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there a way to store and later use comparison operators (<, <=, =, >=, >) ?

2015-04-29 Thread boB Stepp
On Wed, Apr 29, 2015 at 5:49 PM, Peter Otten <__pete...@web.de> wrote:
> boB Stepp wrote:

>> So I have stumbled (With your gracious help!) into a legitimate use of
>> eval()?
>
> No. To expand on Marks hint here's how to do it without evil eval().
>
> import operator
>
> comps = {
> "=": operator.eq,
> "<": operator.lt,
> ">": operator.gt,
> # ...
> }
>
> def choose_compare(operator, value0, value1, pass_color, fail_color):
> op = comps[operator]
> if op(value0, value1):
> return pass_color, True
> else:
> return fail_color, False
>
> print(choose_compare("=", 1, 1, "red", "blue"))
> print(choose_compare("<", 1, 2, "red", "blue"))
> print(choose_compare("<", 2, 1, "red", "blue"))
>
> Rule of thumb: when you think you need eval() you're wrong.

Thanks, Peter! The lure of eval() once more avoided...


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


Re: [Tutor] Is there a way to store and later use comparison operators (<, <=, =, >=, >) ?

2015-04-29 Thread boB Stepp
On Wed, Apr 29, 2015 at 4:42 PM, Mark Lawrence  wrote:

> This isn't a job for Bicycle Repair Man!!!

 Not even if we only use the latest, greatest,
computer-aided bicycle repair technology???

> ... It smacks to me of dictionaries
> and the operator module but I'm too bone idle to look it up myself, so try
> here https://docs.python.org/3/library/operator.html
> D'oh :)

So little time, so much Python standard library! I *do* search and
search and ... search before I ask, but my Google-fu is often weak,
especially when I am searching for hints as to how to solve a problem
where I am unsure of the correct technical terminology to use in the
search. OTH, I have sometimes spent hours searching, both online and
in what books I have, and thus spared y'all many, ... , many other
questions that I might have otherwise asked!

One problem I have with searching the Python documentation is this:
https://docs.python.org/release/2.4.4/lib/lib.html
I never would have guessed beforehand that I would be needing to look
under: "3. Python Runtime Services! I spend most of my time on this
page as this is my most limiting version of Python that I must deal
with.

This page is *not* well-formatted and it all runs together. Even when
I *know* something is there, I find myself having to Ctrl-F and
entering the term I am looking for. And when I am not sure what I am
looking for, I don't usually come up with the correct term. The later
Python docs are much easier on the eyes, I do say!

Anyway, Mark, thanks for the link! This looks quite straightforward
and I will be able to side-step the evils of eval() once again.

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


Re: [Tutor] Fwd: circular movement in pygame

2015-04-29 Thread Dave Angel

On 04/29/2015 02:37 PM, diliup gabadamudalige wrote:

I do not understand how Alan does not get the code that is in this thread.


There are at least 3 ways of posting to "this thread":
   A) email
   B) newsgroup
   C) googlegroups

and at least 5 ways of looking at "this thread"
   A) email
   B) email digest
   C) newsgroup
   D) googlegroups
   E) various archives

To get messages from one region to another involves going through a 
gateway, and most of them damage some of the messages going through.  To 
minimize the likelihood that what looks good on your screen will be 
missing or different on mine or on Alan's, follow a few rules:


   1) avoid html
   2) avoid attachments

There are others, but those seem to be the biggies.

Many other guidelines will help readability and consistency, like not 
top-posting, using proper quoting and attribution, giving enough 
information but not too much, specifying the whole environment in the 
FIRST message of a thread, etc.


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


Re: [Tutor] How to use Git from Windows PC for files on Solaris machine where Git cannot be installed?

2015-04-29 Thread boB Stepp
On Wed, Apr 29, 2015 at 9:40 PM, Cameron Simpson  wrote:
> On 29Apr2015 12:12, boB Stepp  wrote:
>>>
>>> ... (3) install git if needed ...
>>
>>
>> It seems Git is needed, but I am not allowed to install it on the
>> Solaris workstation. So is there a way around this?
>
>
> What do you mean by "install"? Bear in mind that while you may be forbidden
> from installing git in the main areas (/usr, /usr/local, whatever), you may
> be free to install it in your own home directory. It is just an
> executable...

On the smart enterprise where we (now) do our clinical planning they
are very strict: no installing any external software; no accessing the
Internet; no email; etc. Not all centers adhere to this level of
strictness, but ours does. To be honest, I am surprised they allow me
to do the programming I do, but so far it has been all pluses and no
minuses, and for those dosimetrists who choose to use the tools I have
developed, they are more productive than they would be doing things by
hand.

Now the 810X Solaris workstation that was retired when we went to
smart enterprise is *mine* and they really don't care anymore what I
do with it. When it was being used for actual clinical planning, it
had its Internet access disabled, etc. I have since restored it, so I
could install software now, including Git. But I am reluctant to do
anything that I am not allowed to replicate on smart enterprise. I am
trying to keep it as close to identical to the actual clinical
environment as I can. Perhaps this is misguided on my part? As always,
I welcome your thoughts. It could be I am being unnecessarily cautious
in regards to the 810X, but as has been pointed out there is much I do
not know, so my motto is to first ensure I do no harm...

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


Re: [Tutor] Fwd: Function works one time then subsequently fails

2015-04-29 Thread Cameron Simpson

On 29Apr2015 08:34, Jim Mooney Py3.4.3winXP  wrote:

On 28 April 2015 at 22:40, Cameron Simpson  wrote:

We can pick over your code as well if you like. Should we?


Sure, but let me include the full working program after fixup. Although I
still have to write another program to feed it random problems to work it
out. It's a bit spacey, but I ran it through the pep8 program and it
suggested that. I think two spaces between such tiny functions is overkill,
though.

"""
Takes the name of a binary math operation and two numbers from input,
repeatedly, and displays the results until done
"""

def add(a, b):
   return a + b


def subtract(a, b):
   return b - a


def minus(a, b):
   return a - b


These could all do with docstrings. add() is pretty obvious, but the 
distinction between minus() and subtract() could do with elaboration.


Also, I would be inclined to define minus() in terms of subtract(), not because 
it is faster but because it establishes an equivalence.



def multiply(a, b):
   return a * b


def divide(a, b):
   return a / b


operations = {'add': add, '+': add, 'plus': add, 'subtract': subtract,
'subtracted': subtract,
 '-': minus, 'minus': minus, 'multiply': multiply, '*':
multiply, 'multiplied': multiply,
 'times': multiply, 'divide': divide, '/': divide, 'divided':
divide}


I'd make this much more vertical, like this:

 operations = {'add': add,
   '+': add,
   'plus': add,
   'subtract': subtract,
   'subtracted': subtract,

Easier to maintain, easier to read, easier to modify, and if you use version 
control you will get much more meaningful diff output with changes, which aids 
code review (which more or less equates to readability and maintainability).



def test_number(astring):
   """
   Input: A string that should represent a valid int or float. Output:
   An int or float on success. None on failure.
   """
   for make_type in (int, float):
   try:
   return make_type(astring)
   except ValueError:
   pass
   return None


If this is a test function, it should return True or False.

Other have already remarked on this in other threads: the Pythonic way to do 
this is usually to attempt the conversion and let an exception get out:


 def numberify(astring):
 return float(astring)

Consider the calling code. What are you going to do with it. I see you probe 
first, which makes some sense in lexical analysis:



def parse_string(math_string):
   """Input: A math string with a verbal or mathematical operation
   and two valid numbers to operate on. Extra numbers and operations
   are ignored. Output: A tuple containing a function corresponding
   to the operation and the two numbers. Returns None on failure.
   """
   operation = None
   tokens = math_string.split()
   numbers = []
   for token in tokens:
   if token in operations:
   operation = operations[token]
   elif test_number(token) != None:
   numbers.append(test_number(token))
   if len(numbers) > 1:
   break
   if operation is None or len(numbers) < 2:
   return None
   else:
   return operation, numbers[0], numbers[1]


As a lexical exercise probing (test then act) is pretty common and normal.  

However, an alternative way to structure this is the "ask for forgiveness" 
approach:


 try:
   operation = operations[token]
 except KeyError:
   value = numberify(token)
   numbers.append(value)

This will raise ValueError if it is neither an operation nor a number.

The practice of raising an exception permits a mode of programming where both 
your code and the caller can broadly write the code as though values are 
generally valid, and avoids a lot error catching verbiage that obscures the 
core logic.


In that vein, you would also modify the function to raise an exception 
(typically ValueError) for other invalid math_strings. The advantage here is 
that the caller can use your function like this:


 operation, *arguments = parse_string(math_string)

and not perform any special testing for getting None back. Instead, the caller 
can plow on as though the math_string was valid as well. An exception can 
bubble up to a suitable catch point, such as the main loop which reads strings 
from the user.



instructions = '''Enter two numbers and one of the four basid math
operations,
either mathematical or verbal. i.e. 3 + 2, 12 divided by 14, 10 minus 4,
etc.
Enter done to quit.
'''
try:
   user_input = input(instructions)
   while True:
   if user_input == 'done':
   break


While most programs will accept a special token to exit, you can also just rely 
on seeing end of file. Most systems have a way of indicating this from the 
keyboard, often ^Z in Windows and ^D on UNIX terminals. So since input() is 
documented as raising EOFError in this circumstance you could add that to your 
catch below:


 except EOFError:
 print("End of input from user.")

Then, if parse_string

Re: [Tutor] How to use Git from Windows PC for files on Solaris machine where Git cannot be installed?

2015-04-29 Thread Cameron Simpson

On 29Apr2015 12:12, boB Stepp  wrote:

... (3) install git if needed ...


It seems Git is needed, but I am not allowed to install it on the
Solaris workstation. So is there a way around this?


What do you mean by "install"? Bear in mind that while you may be forbidden 
from installing git in the main areas (/usr, /usr/local, whatever), you may be 
free to install it in your own home directory. It is just an executable...


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


Re: [Tutor] subprocess.Popen(..., cwd) and UNC paths

2015-04-29 Thread eryksun
On Wed, Apr 29, 2015 at 8:28 PM, eryksun  wrote:
> After disabling the check, my previous example should work fine:

Except it doesn't accept paths relative to a UNC working directory:

(test) \\127.0.0.1\C$>cd Temp
The system cannot find the path specified.

And the cd command appears to ignore the registry setting:

(test) \\127.0.0.1\C$>cd \\127.0.0.1\C$\Temp
'\\127.0.0.1\C$\Temp'
CMD does not support UNC paths as current directories.

Otherwise it works fine. ;-)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] subprocess.Popen(..., cwd) and UNC paths

2015-04-29 Thread eryksun
On Wed, Apr 29, 2015 at 7:48 PM, eryksun  wrote:
> cmd.exe was developed for OS/2 (1987) to replace COMMAND.COM (1981).

Actually, I stand corrected about the reason being cmd's 1980s
crustiness. Per [KB156276][1] this check was added to NT 4.0 (1996) to
address a vaguely described problem ("a UNC name may cause problems
with child processes launched from such a console when that console is
exited or halted"), which may not even be a problem nowadays (Windows
7+) since the console was moved out of CSRSS.EXE (the Windows session
server) into instances of conhost.exe that run in the security context
of the client. Try adding the registry setting to disable this check.
Probably nothing bad will happen. Here's a reg.exe command to disable
the check for the current user:

reg add "HKCU\Software\Microsoft\Command Processor"
/v DisableUNCCheck /t REG_DWORD /d 1

After disabling the check, my previous example should work fine:

(test) C:\Temp>python
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct  6 2014, 22:16:31) [MSC
v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os, subprocess
>>> os.chdir(r'\\127.0.0.1\C$')
>>> subprocess.call('cmd')
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

(test) \\127.0.0.1\C$>

[1]: https://support.microsoft.com/en-us/kb/156276
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] raise exception works as planned in program but not when imported into testing module

2015-04-29 Thread Jim Mooney Py3.4.3winXP
I raised an exception in the parse_string function in my math parser
program, function_tosser.py, and caught it in the calling routine, and that
worked fine. But when I imported function_tosser.py into a test program,
tester.py, it threw the exception in the parse_string function instead of
handling it in the try block in the calling routine. Why did it work in one
and not the other? The testing program works fine if I return None as I did
before, instead of raising the exception.

# function_tosser.py
"""
Takes the name of a binary math operation and two numbers from input,
repeatedly, and displays the results until done
"""


def add(a, b):
return a + b


def subtract(a, b):
return b - a

def minus(a, b):
return a - b


def multiply(a, b):
return a * b


def divide(a, b):
return a / b


operations = {'add': add, '+': add, 'plus': add, 'subtract': subtract,
'subtracted': subtract,
  '-': minus, 'minus': minus, 'multiply': multiply, '*':
multiply, 'multiplied': multiply,
  'times': multiply, 'divide': divide, '/': divide, 'divided':
divide}

def test_number(astring):
"""
Input: A string that should represent a valid int or float. Output:
An int or float on success. None on failure.
"""
for make_type in (int, float):
try:
return make_type(astring)
except ValueError: # Previously returned None, which worked. This
works fine here but when imported into the test program
pass   # it doesn't wait for the try block in the
calling routine.
return None


def parse_string(math_string):
"""Input: A math string with a verbal or mathematical operation
and two valid numbers to operate on. Extra numbers and operations
are ignored. Output: A tuple containing a function corresponding
to the operation and the two numbers. Returns None on failure.
"""
operation = None
tokens = math_string.split()
numbers = []
for token in tokens:
if token in operations:
operation = operations[token]
elif test_number(token) != None:
numbers.append(test_number(token))
if len(numbers) > 1:
break
if operation is None or len(numbers) < 2:
raise ValueError
else:
return operation, numbers[0], numbers[1]

if __name__ == "__main__":
instructions = '''Enter two numbers and one of the four basid math
operations,
either mathematical or verbal. i.e. 3 + 2, 12 divided by 14, 10 minus
4, etc.
Enter done to quit.
'''
try:
user_input = input(instructions)
while True:
if user_input == 'done':
break
try:
result = parse_string(user_input)
except ValueError:
print("Not a valid math operation.")
else:
func, num1, num2 = result
print(func(num1, num2))
user_input = input()
except KeyboardInterrupt:
print("Program terminated by user")

# tester.py

'''Test function_tosser.py mainlogic against random operators, operands,
and bad input'''
import random
import function_tosser as ft
valid_terms = list(ft.operations.keys())
def eval_test():
pass

trash = ['1 +', 'blah', '3-4', 'gargle', 'Newt Gingrich',
",", '{+=-33.44 minus12 3 times blarg 1445641654644555455']

for ctr in range(50):
term = ' ' + random.choice(valid_terms) + ' '
num1 = str(random.randint(1,1000))
num2 = str(random.randint(1,1000))
if term == ' subtract ' or term == ' subtracted ': term = ' subtracted
from '
if ctr % 10 == 0: # stress testing for a None failure
monkey_wrench = random.choice(trash)
print(ft.parse_string(monkey_wrench), '\n')
else:
func, num1, num2 = ft.parse_string(num1 + term + num2)
print(func, num1, term, num2)
print('result:',func(num1, num2), '\n')


-- 
Jim

"What a rotten, failed experiment. I'll start over. Maybe dogs instead of
monkeys this time." --God
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] subprocess.Popen(..., cwd) and UNC paths

2015-04-29 Thread eryksun
On Wed, Apr 29, 2015 at 7:08 PM, Alan Gauld  wrote:
> On 30/04/15 00:12, eryksun wrote:
>
>> the working directory, but the cmd.exe shell (being a crusty relic of
>> the 1980s) does not.
>
> Actually cmd.exe is fine with UNC paths. It's only when you
> combine them with Windows /option style that it has issues
> but even then putting the path in quotes will usually do
> the trick.
>
> It's the old MS-DOS COMMAND.COM that can't cope.

cmd.exe was developed for OS/2 (1987) to replace COMMAND.COM (1981).

cmd.exe cannot use a UNC path as the current directory. What it can do
is `pushd` a UNC path, which mounts it as a drive letter. If you do
try to start cmd.exe with a UNC path as the working directory, it
instead sets the working directory to the Windows directory. For
example:

(test) C:\Temp>python
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct  6 2014, 22:16:31)
[MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os, subprocess
>>> os.chdir(r'\\127.0.0.1\C$')
>>> subprocess.call('cmd')
'\\127.0.0.1\C$'
CMD.EXE was started with the above path as the current directory.
UNC paths are not supported.  Defaulting to Windows directory.
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

(test) C:\Windows>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] subprocess.Popen(..., cwd) and UNC paths

2015-04-29 Thread Alan Gauld

On 30/04/15 00:12, eryksun wrote:


the working directory, but the cmd.exe shell (being a crusty relic of
the 1980s) does not.


Actually cmd.exe is fine with UNC paths. It's only when you
combine them with Windows /option style that it has issues
but even then putting the path in quotes will usually do
the trick.

It's the old MS-DOS COMMAND.COM that can't cope.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
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] Is there a way to store and later use comparison operators (<, <=, =, >=, >) ?

2015-04-29 Thread Danny Yoo
Hi Bob,

By the way, it sounds like you're starting to learn about how to write
interpreters.  If that's the case, you might find PLAI helpful:

http://cs.brown.edu/~sk/Publications/Books/ProgLangs/

helpful.  (Full disclosure: the author was my external advisor.  :P)


Another good book is EoPL:


http://www.amazon.com/Essentials-Programming-Languages-Daniel-Friedman/dp/0262062798


I have fond memories of those two books.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] subprocess.Popen(..., cwd) and UNC paths

2015-04-29 Thread eryksun
On Wed, Apr 29, 2015 at 11:54 AM, Albert-Jan Roskam
 wrote:
> Hmmm, that sounds pretty convincing indeed (makes it even stranger that CD 
> works the way it works).
> I believe it threw a WindowsError, indicating that the file(s) could not be 
> found, because the dir was
> not changed. I actually first ran into this problem with this script, so with 
> my current script I
> immediately refrained from using cwd:
> http://code.activestate.com/recipes/578883-git-pre-commit-hook-to-reject-large-files-using-py/
> Git gave a fatal error in windows and the pushd/popd fixed it.

I don't see why you'd need shell=True. Windows supports UNC paths in
the working directory, but the cmd.exe shell (being a crusty relic of
the 1980s) does not. So just use the default value, shell=False.
(However, on POSIX systems, unlike Windows, using shell=False requires
`cmd` to be a list.) BTW, there's no need to explicitly pass
cwd=os.getcwd(). The default behavior is to inherit the working
directory of the current process.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Good Taste Question: Using SQLite3 in Python

2015-04-29 Thread Alan Gauld

On 29/04/15 22:11, Roel Schroeven wrote:

Alan Gauld schreef op 2015-04-29 18:43:

On 29/04/15 17:03, Jugurtha Hadjar wrote:

http://docs.python-guide.org/en/latest/writing/style/#create-an-ignored-variable



I've seen this before and strongly disagree with it.


I disagree with your disagreement. I'll try to explain.


They are ambiguous, difficult to remember, easy to overlook


I'm not sure what exactly you mean by that.


If something exists in a function, over time somebody will use it.
Especially during debugging, priont is a dangerous tool in these cases.
Simple fact of life. If it exists it should be visible (not too
short or incongruous) Trying to visually scan for _ or even
__ is hard. Also different fonts make _ and __ hard to
distinguish.


and if you change your mind and decide you need to use it later

 > it's a whole new name to go back and introduce

True, but I don't see how that is a problem. At that point the variable
is only used at one point, so you only have to rename it at that one place.


It is if its only used once - see below.
Renaming the wrong variable (especially ising search./replace
in the editor) is a very common way to introduce new bugs into
working code! Having spent nearly 10 years running 3 different 
maintenance teams I know how easy it is for new programmers(*)

to start changing things they don;t understand, especially
when under time pressure.

(*)And maintenance teams are almost always comprised of a
combination of new or very old (read jaded) programmers.
The top players are reserved for the exciting new stuff!


(or worse be tempted to use the  meaningless symbol).


That would be bad indeed, but I think a very minimal amount of
discipline is enough to avoid that.


Its almost impossible,  A maintenance team is usually working
on a ratio of 10-50,000 lines of code per programmer per project
and typically 3-5 projects. So if you have to hold 50-150,000
lines of code in mind its very easy to slip something in as
a 'quick fix' intending to fix it next time then forget about
it. Especially if you have to check in two bug fixes before
you get to go home tonight

Maintenance programmers are rarely the people who wrote the
code, and they rarely have much personal pride invested in
the code they have to fix. Even if they are the original
developer they will have moved on to new projects and
fixing 5 year old code is a low priority. Its all about
human nature.



The whole point of ignored variables is that you don't use them.


That's the point when they are created, but too often a
use is found for these things. The original author is never in a 
position to say 'this will never be used in the future'

that's just too idealistic. And the original author is
very unlikely to be the long tem maintainer. Even in
open-source where people tend to stick with projects
for a few years its not true. In commercial code the
author probably leaves the company within 6 months of
writing the code. He may never even see it go into
production...


use them, they're not exactly ignored variables. It doesn't matter if
you use __ once or twice or many times more; all of them are to be ignored.


Absolutely. nothing can be guaranteed to be ignored over
time, to start out with tat asumption is tom lay the seeds
of chaos later.


 > (looking different is good - you can
 > detect it easily, looking similar is very, very, bad!)...
 > its just a horror story waiting to trip you up.

I'm not sure in what way __ can lead to horror stories. Do you have an
example to fuel my imagination?


None in Python - I've never run a Python maintenance squad,
but I have led assembler, C/C++, SQL, Perl and COBOL: teams.
In every case there have been attempts to use variables that
had been intended to be unused - in some cases randomly 
initialized/unassigned, reassigned etc. I once saw a C

function with the same dummy variable use 4 times - although
that did have a name, but it was a placeholder like x.

But in Perl I've seen the infamous $_ abused many times
(although that's slightly different since it magically takes
on certain values, implicit rather than explicit) Python tries
to avoid these things but the whole _/__ variable scheme is
IMHO one of its worst features.


 > It's far better to have a short meaningful name that is never
 > used than a bland, meaningless, generic symbol.

By 'short meaningful name', do you mean something like 'dummy' or
'ignorethis' as in

basename, dummy, ext = filename.rpartition('.')

or rather something like

basename, separator, ext = filename.rpartition('.')



The latter. or even 'sep' as shorter than 'separator'. At least
it gives some clue to its meaning and can be used later
if needed. Because its not expected to be used typing the
few extra characters once doesn't hurt. But it makes
scaffold code, debug code and extension code much easier
to write.


In the first case, I prefer __ over dummy exactly because to me it's
clearer at a glance that the name is one-u

Re: [Tutor] Is there a way to store and later use comparison operators (<, <=, =, >=, >) ?

2015-04-29 Thread Peter Otten
boB Stepp wrote:

> On Wed, Apr 29, 2015 at 3:46 PM, Marc Tompkins 
> wrote:
>> On Wed, Apr 29, 2015 at 1:10 PM, boB Stepp 
>> wrote:
>>>
>>> Python 2.4.4, Solaris 10.
>>>
>>> I have some functions that I believe I could collapse into a single
>>> function if I only knew how:
>>>
>>> def choose_compare(operator, value0, value1, pass_color, fail_color):
>>> """
>>> Perform the comparison indicated by operator. Return pass_color if
>>> true, fail_color if false.
>>> """
>>> if operator == '<':
>>> return less_than(value0, value1, pass_color, fail_color)
>>> elif operator == '<=':
>>> return less_than_or_equal(value0, value1, pass_color,
>>> fail_color)
>>> elif operator == '=':
>>> return equal(value0, value1, pass_color, fail_color)
>>> elif operator == '>':
>>> return greater_than(value0, value1, pass_color, fail_color)
>>> elif operator == '>=':
>>> return greater_than_or_equal(value0, value1, pass_color,
>>> fail_color)
>>> else:
>>> print 'WarningMessage = "Invalid comparison operator in
>>> function, choose_compare().@Please contact script administrator for
>>> assistance.";'
>>>
>>> def less_than(value0, value1, pass_color, fail_color):
>>> """
>>> See if value0 is less than value1. If true, return pass_color. If
>>> false, return fail_color.
>>> """
>>> if value0 < value1:
>>> return pass_color, True
>>> else:
>>> return fail_color, False
>>>
>>> def less_than_or_equal(value0, value1, pass_color, fail_color):
>>> """
>>> See if value0 is less than or equal to value1. If true, return
>>> pass_color. If false, return fail_color.
>>> """
>>> if value0 <= value1:
>>> return pass_color, True
>>> else:
>>> return fail_color, False
>>>
>>> ... 3 more functions ...
>>>
>>> I won't give the remaining functions for the other comparison
>>> operators. The string variable, operator, is originally populated from
>>> a data file, which tells what type of comparison needs to be made. The
>>> last two functions I gave (and the ones I omitted giving) all follow
>>> the same exact pattern. I know there has to be some way to replace
>>> these 5 functions with 1, but what experimentation I have done to date
>>> has not worked.
>>>
>>> Also, what about the first function above? I could use 2 dictionaries,
>>> 1 for calling the 5 functions and one to pass the arguments, but is it
>>> worth doing this? Or, I would not be surprised if there is a much
>>> better way! ~(:>))
>>>
>>> Thanks!
>>
>>
>> Here's what I came up with:
>>
>> def choose_compare(operator, value0, value1, pass_color, fail_color):
>> comps = {"=":"==", "<":"<", ">":">", "<=":"<=", ">=":">="}
>> if operator in comps.keys():
>> operator = comps[operator]
>> if eval("{} {} {}".format(value0, operator, value1)):
>> return pass_color, True
>> else:
>> return fail_color, False
>> else:
>> print('WarningMessage')
>>
>> I would ordinarily avoid eval() like the plague, but I think that this
>> sanitizes the input pretty effectively.  I had to make comps a dict
>> instead of a list because (in your example, anyway) you're using a single
>> equals
>> sign to check for equality, which throws a Syntax Error (e.g.  "if 1 = 2"
>> instead of "if 1 == 2").
> 
> I could deal with the "=" issue by either reformatting my data file to
> use "==" in place of "=", or when I parse the data file, do the
> replacement there. A list instead of the dictionary looks a little
> easier on my eyes.
> 
> The list has me so leery of eval and exec that I totally forgot about
> this possibility! There are only two places in my program where I read
> information directly into my program: 1) The data file, or 2) how the
> user of the planning software names his regions of interest (ROI) in
> the planning system software. I will reexamine my checks of (1). For
> (2) the planning software already has its own checks, which would
> filter out a lot. And I am checking the ROIs to see if they are
> present in the data file *exactly* as given in the data file;
> otherwise, I reject them.
> 
> So I have stumbled (With your gracious help!) into a legitimate use of
> eval()?

No. To expand on Marks hint here's how to do it without evil eval().

import operator

comps = {
"=": operator.eq,
"<": operator.lt,
">": operator.gt,
# ...
}

def choose_compare(operator, value0, value1, pass_color, fail_color):
op = comps[operator]
if op(value0, value1):
return pass_color, True
else:
return fail_color, False

print(choose_compare("=", 1, 1, "red", "blue"))
print(choose_compare("<", 1, 2, "red", "blue"))
print(choose_compare("<", 2, 1, "red", "blue"))

Rule of thumb: when you think you need eval() you're wrong.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription option

[Tutor] Good name(s) for to-be-ignored variables, was Re: Good Taste Question: Using SQLite3 in Python

2015-04-29 Thread Peter Otten
Roel Schroeven wrote:

> Alan Gauld schreef op 2015-04-29 18:43:
>> On 29/04/15 17:03, Jugurtha Hadjar wrote:
>>> http://docs.python-guide.org/en/latest/writing/style/#create-an-ignored-variable
>> 
>> I've seen this before and strongly disagree with it.
> 
> I disagree with your disagreement. I'll try to explain.
> 
>> They are ambiguous, difficult to remember, easy to overlook
> 
> I'm not sure what exactly you mean by that.
> 
>> and if you change your mind and decide you need to use it later
>  > it's a whole new name to go back and introduce
> 
> True, but I don't see how that is a problem. At that point the variable
> is only used at one point, so you only have to rename it at that one
> place.
> 
>> (or worse be tempted to use the  meaningless symbol).
> 
> That would be bad indeed, but I think a very minimal amount of
> discipline is enough to avoid that.
> 
>> And if you need another 'throw-away' name later you use the same one,
>> then forget
>  > here are two uses and try to use it anyway (even in debugging) and get
>> completely wrong values, that may or may not look different
>> to what you expect.
> 
> The whole point of ignored variables is that you don't use them. If you
> use them, they're not exactly ignored variables. It doesn't matter if
> you use __ once or twice or many times more; all of them are to be
> ignored.
> 
>  > (looking different is good - you can
>  > detect it easily, looking similar is very, very, bad!)...
>  > its just a horror story waiting to trip you up.
> 
> I'm not sure in what way __ can lead to horror stories. Do you have an
> example to fuel my imagination?
> 
>  > It's far better to have a short meaningful name that is never
>  > used than a bland, meaningless, generic symbol.
> 
> By 'short meaningful name', do you mean something like 'dummy' or
> 'ignorethis' as in
> 
> basename, dummy, ext = filename.rpartition('.')
> 
> or rather something like
> 
> basename, separator, ext = filename.rpartition('.')
> 
> In the first case, I prefer __ over dummy exactly because to me it's
> clearer at a glance that the name is one-use only and the value is to be
> ignored.
> In the second case, using a 'real' name like 'separator' means I now
> have to mentally keep track of it since as far as I can see at that
> point it might be used later in the code.
> 
> 
> To me, using _ or __ decreases the cognitive load because they tell me I
> don't have to remember anything about them, since they're not going to
> be used later. Read and forget.

Inside a function there's a middle ground, a leading underscore:

def whatever():
...
basename, _extsep, ext = filename.rpartition(os.extsep)
...

The name makes it clear what _extsep is supposed to contain, and the 
underscore indicates that you are not using the name.

You can later question the decision that you are not interested in _extsep 
-- in the example you may decide that you want to discriminate between

"somefile." and "somefile"

Even if you stick with the original design I find it more readable to state 
explicitly what you are throwing away. 

My whatever() function is an example where the name of the to-be-ignored 
variable led to a change in the code: I started with _separator and then 
remembered that the separator need not be a dot.

Admittedly I don't expect to use an OS where os.extsep != "." anytime soon, 
but you get the idea...

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


Re: [Tutor] Fwd: circular movement in pygame

2015-04-29 Thread Alan Gauld

On 29/04/15 21:19, diliup gabadamudalige wrote:


It is partly due to curiosity but I also wanted to have a common update
method. And as I almost always use the x+= some code, y+=some code for
animation stuff I wanted to know how it could be done using this method
rather than finding each position separately and assigning with x= some
code, y = some code (new position).


OK, Curiosity is good.
But the conversion is mainly a math challenge rather than a
programming one. And its a very seductive but dangerous mind
set to try to force a problem into a pattern that fits how
you usually do it. Especially if the transformed code looks
less intuitive than the original.

When I started in Python it didn't even have the += style
of augmented assignment, it was mainly introduced to save
some typing, nothing more.

Remember that += is still an assignment to x. It is not
significantly different or in any way 'better' than
the standard assignment. In languages like C '+='  (and
even more so '++' which doesn't exist in Python) used to
result in performance improvements but optimising
compilers have removed even that reason for using it.
Now it should just be considered a typing shortcut.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
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] Fwd: circular movement in pygame

2015-04-29 Thread Danny Yoo
On Wed, Apr 29, 2015 at 11:37 AM, diliup gabadamudalige
 wrote:
> I do not understand how Alan does not get the code that is in this thread.

Hi Dilliup,

Please try to avoid using the phrase, "I don't understand how  does
not get ...".


You might not realize it, but it's radioactive: it's has a very
negative connotation that is toxic to collaborative communities.

For more information on this, there's a very good book called Team
Geek that talks about these issues:

https://books.google.com/books/about/Team_Geek.html?id=Iwk_pKeBc9gC&hl=en

Also see Hacker School's Social Rules:

https://www.recurse.com/manual#sub-sec-social-rules


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


Re: [Tutor] Fwd: circular movement in pygame

2015-04-29 Thread diliup gabadamudalige
Thanks Alan.

It is partly due to curiosity but I also wanted to have a common update
method. And as I almost always use the x+= some code, y+=some code for
animation stuff I wanted to know how it could be done using this method
rather than finding each position separately and assigning with x= some
code, y = some code (new position).

But here is STILL something curious in this whole matter.

If I update the rect positions with

obj.rect.x+ = some code
obj.rect.y+ = some code

then the rotation are NOT circular.
BUT
if I use

obj.x += some code
obj.y += some code

and then do

obj.rect.x, obj.rect.y = obj.x, obj.y

then the rotation works correct!!
This is really weird and I have no explanation as to why this happens!!!
Can you or anyone else explain this strange behaviour? After all a position
is a position.(at least that;s how I understand as long as you stick with
the same coordinate through out.)
The code is below.

import sys, os, pygame, itertools
from math import sin,cos,pi
from pygame.locals import *
SCREENW = 800
SCREENH = 700
class object_factory(pygame.sprite.Sprite):
def __init__(self, image, xpos = 0, ypos = 0):
"""Constructor"""
pygame.sprite.Sprite.__init__(self)
self.image = image
self.mask = pygame.mask.from_surface(self.image) # pixelmask
self.rect = self.image.get_rect()
self.rect.x = xpos
self.rect.y = ypos
self.x=xpos
self.y=ypos
pygame.init()
clock = pygame.time.Clock()
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (50,50) #Set window position
SCREEN = pygame.display.set_mode((SCREENW, SCREENH))
clock = pygame.time.Clock()
pygame.display.set_caption('rotating object')
ball = pygame.image.load("ball.jpg")
pin=pygame.image.load("center.jpg");
platforms = pygame.sprite.Group()
center_x = SCREENW/2
center_y = SCREENH/2
radius = 200
angle = pi/4 # starting angle 45 degrees
omega = 0.1 #Angular velocity
for _ in itertools.repeat(None, 6):
xpos = center_x + radius * cos(angle) #Starting position x
ypos = center_y - radius * sin(angle) #Startinh position y
obj = object_factory(ball, xpos, ypos)
obj.angle = angle
obj.omega = omega  #angula velocity
obj.radius = radius
platforms.add(obj)
angle += pi/.5
#--
while True:
clock.tick(24)
pygame.event.pump()
keys = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key ==
K_ESCAPE):
pygame.quit()
sys.exit()
SCREEN.fill((0, 0, 0))
SCREEN.blit(pin,(center_x - pin.get_width() / 2, center_y -
pin.get_height() / 2))
pygame.draw.circle(SCREEN, (0, 0, 255), (center_x, center_y), radius, 2)

for b in platforms:
b.angle+=b.omega
#Rect Base Rotation
#b.rect.x += b.radius * b.omega * cos(b.angle + pi / 2)
#b.rect.y -= b.radius * b.omega * sin(b.angle + pi / 2)
#SCREEN.blit(ball,(b.rect.x,b.rect.y))
#Normal Rotation
b.x+= b.radius * b.omega * cos(b.angle + pi / 2)
b.y-= b.radius * b.omega * sin(b.angle + pi / 2)

b.rect.x, b.rect.y = b.x - b.rect.width / 2, b.y - b.rect.height / 2

#SCREEN.blit(ball,(b.x,b.y)) # this and the line below gives the
same result
#SCREEN.blit(ball, (b.rect.x, b.rect.y))

platforms.update()
platforms.draw(SCREEN)

pygame.time.wait(100)
pygame.display.update()



On Thu, Apr 30, 2015 at 12:25 AM, Alan Gauld 
wrote:

> On 29/04/15 19:37, diliup gabadamudalige wrote:
>
>> I do not understand how Alan does not get the code
>>
>
>
> Replying off list.
>
> I don't get it because text based email systems often strip out attachments
> since they are a security risk. As the name says they are *text* based.
>
> However, now that I've seen it and I see your solution I can better
> understand
> what you were trying to ask, which was the solution to a very specific
> scenario.
>
> I'm still not sure why you wanted to use augmented assignment, other
> than curiosity perhaps, but at least I now see what you were trying to do.
> Thanks for posting the solution.
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>


-- 
Diliup Gabadamudalige

http://www.diliupg.com
http://soft.diliupg.com/

**
This e-mail is confidential. It may also be legally privileged. If you are
not the intended recipient or have received it in error, please delete it
and all copies from your system and notify the sender immediately by return
e-mail. Any unauthorized reading, reproducing, printing or further
dissemination of this e-mail or its contents is strictly prohibited and may
be unlawful. Internet communications cannot 

Re: [Tutor] Is there a way to store and later use comparison operators (<, <=, =, >=, >) ?

2015-04-29 Thread Laura Creighton
I forget.  You are writing these things as functions rather than
methods of a class, because you don't know how to use classes yet?

Because you are absolutely correct that there are ways to simplify this,
but if you don't know how to use classes yet, put this on hold until
you do.  And this particular thing you want to do is not the optimal
place to start learning about how to use classes.

Laura

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


Re: [Tutor] Good Taste Question: Using SQLite3 in Python

2015-04-29 Thread Jugurtha Hadjar

On 04/29/2015 09:50 AM, Peter Otten wrote:


My random observations:

(1) find() and create() look very similar. Try hard to factor out common
code. You might even combine it into a single method ensure_balance(phone).



I'll think about it. I can't see for now how I would combine the two 
(each are triggered by different sets of conditions), but there's 
probably a better way.



(2) According to

https://docs.python.org/dev/library/sqlite3.html#using-the-connection-as-a-context-manager

- the context manager automatically commits
- you can run sql directly on the connection



I read that but I can't recall for the life of me why I didn't use it 
that way. Maybe I didn't understand it well or something broke, etc. 
I'll look into it.



It might by a good idea to refactor init_db() to just return the connection
and then use it as

 with self.init_db() as conn:
 return conn.execute(
 self.QUERIES['FIND_PHONE'],
 (self.phone,)).fetchone() is not None

If you need a cursor you can easily get one from the connection. If you want
more complex handling later you can always turn init_db() into a
contextmanager (see

).



Yes, that's the way it was but I didn't like conn.cursor and I didn't 
know how to use context managers (still don't). So I wanted to have 
something working first, and then improving it now.




(3) Catching Exception is overly broad. You will also catch a typo like

cursor.execute(
 self.QUERIES['CERATE'],
 (self.phone, seed_balance)
)

where the proper fix is to modify the script. Only catch exceptions that you
can actually handle. Example: a table doesn't exist, and you want to create
it lazily on first access. Let all other exceptions just bubble up. It may
seem lazy, but a complete traceback is invaluable for identifying and fixing
a bug.



Right. This was also pointed by Alan so it must be really shabby. I'll 
look into it.



(4) self.ERROR.format(e.args[0])

is probably a string with len() > 0, and thus True in a boolean context.
 From that follows an exception in the find() method in


 self.known = self.find()


causes the following if-suite to be run


 if self.known:
 self.balance = self.get_balance()


and if get_balance() has a same idea of proper exception handling

self.balance will end up containing an error message.


Nice, really nice :)



(5) From point (4) I conclude that you don't have unit tests that cover your
code. You should really write some of these before pondering about stylistic
issues. Unit tests

- help avoid errors
- make changes in the code less of a gamble because if the tests succeed
after the change you can be confident the change didn't introduce an error
- what you might not expect: how drastically tests affect the style of your
code. You'll see yourself thinking "How can I test that?" with every line of
code that you write, and that alone will improve the quality of your code.



I have simple scripts that test for specific things, but it's not really 
professional neither does it follow any structure, etc.


I'll improve the code following the recommendations on this thread..

Thanks, Peter.

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


Re: [Tutor] Is there a way to store and later use comparison operators (<, <=, =, >=, >) ?

2015-04-29 Thread Mark Lawrence

On 29/04/2015 21:10, boB Stepp wrote:

Python 2.4.4, Solaris 10.

I have some functions that I believe I could collapse into a single
function if I only knew how:

def choose_compare(operator, value0, value1, pass_color, fail_color):
 """
 Perform the comparison indicated by operator. Return pass_color if
true, fail_color if false.
 """
 if operator == '<':
 return less_than(value0, value1, pass_color, fail_color)
 elif operator == '<=':
 return less_than_or_equal(value0, value1, pass_color, fail_color)
 elif operator == '=':
 return equal(value0, value1, pass_color, fail_color)
 elif operator == '>':
 return greater_than(value0, value1, pass_color, fail_color)
 elif operator == '>=':
 return greater_than_or_equal(value0, value1, pass_color, fail_color)
 else:
 print 'WarningMessage = "Invalid comparison operator in
function, choose_compare().@Please contact script administrator for
assistance.";'

def less_than(value0, value1, pass_color, fail_color):
 """
 See if value0 is less than value1. If true, return pass_color. If
false, return fail_color.
 """
 if value0 < value1:
 return pass_color, True
 else:
 return fail_color, False

def less_than_or_equal(value0, value1, pass_color, fail_color):
 """
 See if value0 is less than or equal to value1. If true, return
pass_color. If false, return fail_color.
 """
 if value0 <= value1:
 return pass_color, True
 else:
 return fail_color, False

... 3 more functions ...

I won't give the remaining functions for the other comparison
operators. The string variable, operator, is originally populated from
a data file, which tells what type of comparison needs to be made. The
last two functions I gave (and the ones I omitted giving) all follow
the same exact pattern. I know there has to be some way to replace
these 5 functions with 1, but what experimentation I have done to date
has not worked.

Also, what about the first function above? I could use 2 dictionaries,
1 for calling the 5 functions and one to pass the arguments, but is it
worth doing this? Or, I would not be surprised if there is a much
better way! ~(:>))

Thanks!



This isn't a job for Bicycle Repair Man!!!  It smacks to me of 
dictionaries and the operator module but I'm too bone idle to look it up 
myself, so try here https://docs.python.org/3/library/operator.html

D'oh :)

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

Mark Lawrence

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


Re: [Tutor] Is there a way to store and later use comparison operators (<, <=, =, >=, >) ?

2015-04-29 Thread boB Stepp
On Wed, Apr 29, 2015 at 3:50 PM, Laura Creighton  wrote:
> I forget.  You are writing these things as functions rather than
> methods of a class, because you don't know how to use classes yet?

You forget nothing! ~(:>))

> Because you are absolutely correct that there are ways to simplify this,
> but if you don't know how to use classes yet, put this on hold until
> you do.  And this particular thing you want to do is not the optimal
> place to start learning about how to use classes.

Since the unittest module creating test classes, I have commenced
formal studying of this topic. But as you point out, not ready for it
yet!


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


Re: [Tutor] Is there a way to store and later use comparison operators (<, <=, =, >=, >) ?

2015-04-29 Thread boB Stepp
On Wed, Apr 29, 2015 at 3:46 PM, Marc Tompkins  wrote:
> On Wed, Apr 29, 2015 at 1:10 PM, boB Stepp  wrote:
>>
>> Python 2.4.4, Solaris 10.
>>
>> I have some functions that I believe I could collapse into a single
>> function if I only knew how:
>>
>> def choose_compare(operator, value0, value1, pass_color, fail_color):
>> """
>> Perform the comparison indicated by operator. Return pass_color if
>> true, fail_color if false.
>> """
>> if operator == '<':
>> return less_than(value0, value1, pass_color, fail_color)
>> elif operator == '<=':
>> return less_than_or_equal(value0, value1, pass_color, fail_color)
>> elif operator == '=':
>> return equal(value0, value1, pass_color, fail_color)
>> elif operator == '>':
>> return greater_than(value0, value1, pass_color, fail_color)
>> elif operator == '>=':
>> return greater_than_or_equal(value0, value1, pass_color,
>> fail_color)
>> else:
>> print 'WarningMessage = "Invalid comparison operator in
>> function, choose_compare().@Please contact script administrator for
>> assistance.";'
>>
>> def less_than(value0, value1, pass_color, fail_color):
>> """
>> See if value0 is less than value1. If true, return pass_color. If
>> false, return fail_color.
>> """
>> if value0 < value1:
>> return pass_color, True
>> else:
>> return fail_color, False
>>
>> def less_than_or_equal(value0, value1, pass_color, fail_color):
>> """
>> See if value0 is less than or equal to value1. If true, return
>> pass_color. If false, return fail_color.
>> """
>> if value0 <= value1:
>> return pass_color, True
>> else:
>> return fail_color, False
>>
>> ... 3 more functions ...
>>
>> I won't give the remaining functions for the other comparison
>> operators. The string variable, operator, is originally populated from
>> a data file, which tells what type of comparison needs to be made. The
>> last two functions I gave (and the ones I omitted giving) all follow
>> the same exact pattern. I know there has to be some way to replace
>> these 5 functions with 1, but what experimentation I have done to date
>> has not worked.
>>
>> Also, what about the first function above? I could use 2 dictionaries,
>> 1 for calling the 5 functions and one to pass the arguments, but is it
>> worth doing this? Or, I would not be surprised if there is a much
>> better way! ~(:>))
>>
>> Thanks!
>
>
> Here's what I came up with:
>
> def choose_compare(operator, value0, value1, pass_color, fail_color):
> comps = {"=":"==", "<":"<", ">":">", "<=":"<=", ">=":">="}
> if operator in comps.keys():
> operator = comps[operator]
> if eval("{} {} {}".format(value0, operator, value1)):
> return pass_color, True
> else:
> return fail_color, False
> else:
> print('WarningMessage')
>
> I would ordinarily avoid eval() like the plague, but I think that this
> sanitizes the input pretty effectively.  I had to make comps a dict instead
> of a list because (in your example, anyway) you're using a single equals
> sign to check for equality, which throws a Syntax Error (e.g.  "if 1 = 2"
> instead of "if 1 == 2").

I could deal with the "=" issue by either reformatting my data file to
use "==" in place of "=", or when I parse the data file, do the
replacement there. A list instead of the dictionary looks a little
easier on my eyes.

The list has me so leery of eval and exec that I totally forgot about
this possibility! There are only two places in my program where I read
information directly into my program: 1) The data file, or 2) how the
user of the planning software names his regions of interest (ROI) in
the planning system software. I will reexamine my checks of (1). For
(2) the planning software already has its own checks, which would
filter out a lot. And I am checking the ROIs to see if they are
present in the data file *exactly* as given in the data file;
otherwise, I reject them.

So I have stumbled (With your gracious help!) into a legitimate use of eval()?

Many thanks, again!

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


Re: [Tutor] Good Taste Question: Using SQLite3 in Python

2015-04-29 Thread Roel Schroeven

Alan Gauld schreef op 2015-04-29 18:43:

On 29/04/15 17:03, Jugurtha Hadjar wrote:

http://docs.python-guide.org/en/latest/writing/style/#create-an-ignored-variable


I've seen this before and strongly disagree with it.


I disagree with your disagreement. I'll try to explain.


They are ambiguous, difficult to remember, easy to overlook


I'm not sure what exactly you mean by that.


and if you change your mind and decide you need to use it later

> it's a whole new name to go back and introduce

True, but I don't see how that is a problem. At that point the variable 
is only used at one point, so you only have to rename it at that one place.


(or worse be tempted to use the  meaningless symbol). 


That would be bad indeed, but I think a very minimal amount of 
discipline is enough to avoid that.



And if you need another 'throw-away' name later you use the same one, then 
forget

> here are two uses and try to use it anyway (even in debugging) and get

completely wrong values, that may or may not look different
to what you expect.


The whole point of ignored variables is that you don't use them. If you 
use them, they're not exactly ignored variables. It doesn't matter if 
you use __ once or twice or many times more; all of them are to be ignored.


> (looking different is good - you can
> detect it easily, looking similar is very, very, bad!)...
> its just a horror story waiting to trip you up.

I'm not sure in what way __ can lead to horror stories. Do you have an 
example to fuel my imagination?


> It's far better to have a short meaningful name that is never
> used than a bland, meaningless, generic symbol.

By 'short meaningful name', do you mean something like 'dummy' or 
'ignorethis' as in


basename, dummy, ext = filename.rpartition('.')

or rather something like

basename, separator, ext = filename.rpartition('.')

In the first case, I prefer __ over dummy exactly because to me it's 
clearer at a glance that the name is one-use only and the value is to be 
ignored.
In the second case, using a 'real' name like 'separator' means I now 
have to mentally keep track of it since as far as I can see at that 
point it might be used later in the code.



To me, using _ or __ decreases the cognitive load because they tell me I 
don't have to remember anything about them, since they're not going to 
be used later. Read and forget.




Best regards,
Roel

--
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
  -- Isaac Asimov

Roel Schroeven

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


Re: [Tutor] Is there a way to store and later use comparison operators (<, <=, =, >=, >) ?

2015-04-29 Thread Marc Tompkins
On Wed, Apr 29, 2015 at 1:10 PM, boB Stepp  wrote:

> Python 2.4.4, Solaris 10.
>
> I have some functions that I believe I could collapse into a single
> function if I only knew how:
>
> def choose_compare(operator, value0, value1, pass_color, fail_color):
> """
> Perform the comparison indicated by operator. Return pass_color if
> true, fail_color if false.
> """
> if operator == '<':
> return less_than(value0, value1, pass_color, fail_color)
> elif operator == '<=':
> return less_than_or_equal(value0, value1, pass_color, fail_color)
> elif operator == '=':
> return equal(value0, value1, pass_color, fail_color)
> elif operator == '>':
> return greater_than(value0, value1, pass_color, fail_color)
> elif operator == '>=':
> return greater_than_or_equal(value0, value1, pass_color,
> fail_color)
> else:
> print 'WarningMessage = "Invalid comparison operator in
> function, choose_compare().@Please contact script administrator for
> assistance.";'
>
> def less_than(value0, value1, pass_color, fail_color):
> """
> See if value0 is less than value1. If true, return pass_color. If
> false, return fail_color.
> """
> if value0 < value1:
> return pass_color, True
> else:
> return fail_color, False
>
> def less_than_or_equal(value0, value1, pass_color, fail_color):
> """
> See if value0 is less than or equal to value1. If true, return
> pass_color. If false, return fail_color.
> """
> if value0 <= value1:
> return pass_color, True
> else:
> return fail_color, False
>
> ... 3 more functions ...
>
> I won't give the remaining functions for the other comparison
> operators. The string variable, operator, is originally populated from
> a data file, which tells what type of comparison needs to be made. The
> last two functions I gave (and the ones I omitted giving) all follow
> the same exact pattern. I know there has to be some way to replace
> these 5 functions with 1, but what experimentation I have done to date
> has not worked.
>
> Also, what about the first function above? I could use 2 dictionaries,
> 1 for calling the 5 functions and one to pass the arguments, but is it
> worth doing this? Or, I would not be surprised if there is a much
> better way! ~(:>))
>
> Thanks!
>

Here's what I came up with:

def choose_compare(operator, value0, value1, pass_color, fail_color):
comps = {"=":"==", "<":"<", ">":">", "<=":"<=", ">=":">="}
if operator in comps.keys():
operator = comps[operator]
if eval("{} {} {}".format(value0, operator, value1)):
return pass_color, True
else:
return fail_color, False
else:
print('WarningMessage')

I would ordinarily avoid eval() like the plague, but I think that this
sanitizes the input pretty effectively.  I had to make comps a dict instead
of a list because (in your example, anyway) you're using a single equals
sign to check for equality, which throws a Syntax Error (e.g.  "if 1 = 2"
instead of "if 1 == 2").
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Is there a way to store and later use comparison operators (<, <=, =, >=, >) ?

2015-04-29 Thread boB Stepp
Python 2.4.4, Solaris 10.

I have some functions that I believe I could collapse into a single
function if I only knew how:

def choose_compare(operator, value0, value1, pass_color, fail_color):
"""
Perform the comparison indicated by operator. Return pass_color if
true, fail_color if false.
"""
if operator == '<':
return less_than(value0, value1, pass_color, fail_color)
elif operator == '<=':
return less_than_or_equal(value0, value1, pass_color, fail_color)
elif operator == '=':
return equal(value0, value1, pass_color, fail_color)
elif operator == '>':
return greater_than(value0, value1, pass_color, fail_color)
elif operator == '>=':
return greater_than_or_equal(value0, value1, pass_color, fail_color)
else:
print 'WarningMessage = "Invalid comparison operator in
function, choose_compare().@Please contact script administrator for
assistance.";'

def less_than(value0, value1, pass_color, fail_color):
"""
See if value0 is less than value1. If true, return pass_color. If
false, return fail_color.
"""
if value0 < value1:
return pass_color, True
else:
return fail_color, False

def less_than_or_equal(value0, value1, pass_color, fail_color):
"""
See if value0 is less than or equal to value1. If true, return
pass_color. If false, return fail_color.
"""
if value0 <= value1:
return pass_color, True
else:
return fail_color, False

... 3 more functions ...

I won't give the remaining functions for the other comparison
operators. The string variable, operator, is originally populated from
a data file, which tells what type of comparison needs to be made. The
last two functions I gave (and the ones I omitted giving) all follow
the same exact pattern. I know there has to be some way to replace
these 5 functions with 1, but what experimentation I have done to date
has not worked.

Also, what about the first function above? I could use 2 dictionaries,
1 for calling the 5 functions and one to pass the arguments, but is it
worth doing this? Or, I would not be surprised if there is a much
better way! ~(:>))

Thanks!

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


Re: [Tutor] Fwd: circular movement in pygame

2015-04-29 Thread diliup gabadamudalige
I do not understand how Alan does not get the code that is in this thread.
Anyway I can conclude by saying that a friend of mine who is not in this
thread solved the problem and I would like to share it with you. He has
changed only a very smal portion in the original code that i posted in this
thread. and it works perfectly. Apparently the problem is in the way the
rect assignment is done in the Python/Pygame rect class. So as conclusion
the code below works perfectly. No drifting. Class implemented. I hope
everyone gets updated. Thanks for your time.


import sys, os, pygame, itertools
from math import sin,cos,pi
from pygame.locals import *
SCREENW = 800
SCREENH = 700
class object_factory(pygame.sprite.Sprite):
def __init__(self, image, xpos = 0, ypos = 0):
"""Constructor"""
pygame.sprite.Sprite.__init__(self)
self.image = image
self.mask = pygame.mask.from_surface(self.image) # pixelmask
self.rect = self.image.get_rect()
self.rect.x = xpos
self.rect.y = ypos
self.x=xpos
self.y=ypos
pygame.init()
clock = pygame.time.Clock()
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (50,50) #Set window position
SCREEN = pygame.display.set_mode((SCREENW, SCREENH))
clock = pygame.time.Clock()
pygame.display.set_caption('rotating object')
ball = pygame.image.load("ball.jpg")
pin=pygame.image.load("center.jpg");
platforms = pygame.sprite.Group()
center_x = SCREENW/2
center_y = SCREENH/2
radius = 200
angle = pi/4 # starting angle 45 degrees
omega = 0.1 #Angular velocity

#---
for _ in itertools.repeat(None, 6):
xpos = center_x + radius * cos(angle) #Starting position x
ypos = center_y - radius * sin(angle) #Startinh position y
obj = object_factory(ball, xpos, ypos)
obj.angle = angle
obj.omega = omega  #angula velocity
obj.radius = radius
platforms.add(obj)
angle += pi/3
#--
while True:
clock.tick(24)
pygame.event.pump()
keys = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key ==
K_ESCAPE):
pygame.quit()
sys.exit()
SCREEN.fill((255,255,255))
SCREEN.blit(pin,(center_x, center_y))

#Class
implementation--
for b in platforms:
b.angle+=b.omega
#Rect Base Rotation
#b.rect.x += b.radius * b.omega * cos(b.angle + pi / 2)
#b.rect.y -= b.radius * b.omega * sin(b.angle + pi / 2)
#SCREEN.blit(ball,(b.rect.x,b.rect.y))

# Normal
Rotation-
b.x+=b.radius * b.omega * cos(b.angle + pi / 2)
b.y-= b.radius * b.omega * sin(b.angle + pi / 2)
SCREEN.blit(ball,(b.x,b.y))
pygame.display.update()


On Wed, Apr 29, 2015 at 10:00 PM, Alan Gauld 
wrote:

> On 29/04/15 10:15, diliup gabadamudalige wrote:
>
>> x=42 good
>> x += 42 -x ?
>>
>> That does not go by a mile of what I asked.
>>
>
> You've asked three different things:
>
> 1) Why the += form gives different results from the assignment form,
> 2) Why some code you apparently wriotre worked outside a class
>but not in a class
> 3) A specific question about some code for moving an object
>in PyGame around in a circle
>
> Number 1 is the only one I can comment on as I can't see your attachments.
> That is what I (and several others) have answered.
> They are fundamentally different. There is no general way
> to make an augmented assignment such that
>
> x = f(y) and
> x += f(y)  (or even g(y))
>
> produce the same result except by the trivial
>
> x += g(y) - x
>
>  Alan, are you telling me that there is no way that one can arrive at X2
>> which is the NEXT place that X1 will be after "some increment"?
>> old x position = X1
>>
>
> No, that is a completely separate question and has nothing
> to do with using augmented assignment. But it does depend
> on the specifics of the situation and is mainly a mathematical
> problem rather than a Python one..
>
>  new x position= X1 + some increment value
>> which can be written as :new X = oldX + some increment value
>>
>> which can be simplified to X += some increment value?
>>
>
> That may or may not be possible, it depends on what the
> original equation in the pure assignment model is.
>
>  my orginal question was
>>
>> *Why does the object NOT move in a circle when implemented as a class?*
>>
>
> Your original question was:
>
> is there a way to do
> self.rect.x +*= some value*
> self.rect.y += some value
>
> rather than
>
> self.rect.x = self.radius * math.sin(self.angle) + self.center_x
> self.rect.y = self.radius * math.cos(self.angle) + self.center_y
>
> Which is about th

Re: [Tutor] How to use Git from Windows PC for files on Solaris machine where Git cannot be installed?

2015-04-29 Thread Albert-Jan Roskam


- Original Message -

> From: boB Stepp 
> To: tutor 
> Cc: 
> Sent: Wednesday, April 29, 2015 7:12 PM
> Subject: Re: [Tutor] How to use Git from Windows PC for files on Solaris 
> machine where Git cannot be installed?
> 
> On Wed, Apr 29, 2015 at 12:04 PM, Albert-Jan Roskam  
> wrote:
>> 
>>  --
>>  On Wed, Apr 29, 2015 4:21 PM CEST boB Stepp wrote:
>> 
>>> I now have Git installed on my Windows 7 PC at work. The files that I
>>> wish to put under Git version control exist on a Solaris 10
>>> workstation. In the Git bash provided, I can ssh into the Solaris 10
>>> machine. I also can the CuteFTP program on my Windows PC to
>>> move/copy/etc. files between the two machines. How can I put these
>>> Solaris files under version control under these circumstances? I
>>> thought I had conceptually seen how to accomplish this via ssh, but if
>>> it is doable, my limited knowledge of Git and ssh is insufficient to
>>> find the path of success.
>> 
>> 
>>  ... (3) install git if needed ...
> 
> It seems Git is needed, but I am not allowed to install it on the
> Solaris workstation. So is there a way around this?


Ouch, that sucks. When I said "if needed", I meant "if not already there". 
Maybe somebody knows a smart solution with rsync or with ftp. Still, then you'd 
run your tests on Windows, but the code is for Solaris.

 >>  But uhhm, this is not Python at all ;-)
> 
> I was hoping for clemency on this point due to the earlier thread(s) I
> started (Which included Python's unittest module.).


I *love* Git (well, that sounds *very* geeky!) so I don't mind at all.
Once you've got it running, you could install a commit hook that runs nosetests 
(or even tox).
That's just two lines (a shebang and a call to once of those scripts) and then 
your unittests will be run automatically every time you do a git commit. Nice! 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to use Git from Windows PC for files on Solaris machine where Git cannot be installed?

2015-04-29 Thread Laura Creighton
Glad things are going better.
Next step.  Can you get git running on your solaris machines?  Easiest is
if it is already installed  or if the powers that be will install it
for you.

But if not, you ought to be able to build your own git from source
and run it on your Solaris machines.

This link

http://joemaller.com/908/how-to-install-git-on-a-shared-host/

is a discription of how somebody did it for Fedora linux.  However, if
you run into trouble trying to do this, you need to talk to somebody
who knows how gcc works on solaris, and where all the dependencies
are, and what whatever error messages you are getting mean.  Ideally
you would have somebody who knows about git, too.  That person
isn't me.  And I don't think that the python-tutor mailing list is the
optimal place to look for such a person.  I'd try some solaris list.
Make sure that whoever you talk to knows that you don't have root access
which is why you are building git from source in the first place, and
gets a copy of exactly what you typed when you tried to build it, and
exactly what you got back in terms of error messages, and output, pasted
in, and not a summary of what you think that those error messages meant.

Best of luck,
Laura

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


Re: [Tutor] How to use Git from Windows PC for files on Solaris machine where Git cannot be installed?

2015-04-29 Thread Alan Gauld

On 29/04/15 18:12, boB Stepp wrote:


But uhhm, this is not Python at all ;-)


I was hoping for clemency on this point due to the earlier thread(s) I
started (Which included Python's unittest module.).


I've been blurring the lines on this one because version control
is something everyone should do whether using Python or not and
as a "beginners" list it seems fair to cover generic VC principles
even in a specific thread on Git.

But to be fair your specific set up is very unusual and it might
be better to take it to a git specific forum for detailed
resolution.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
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] How to use Git from Windows PC for files on Solaris machine where Git cannot be installed?

2015-04-29 Thread boB Stepp
On Wed, Apr 29, 2015 at 12:04 PM, Albert-Jan Roskam  wrote:
>
> --
> On Wed, Apr 29, 2015 4:21 PM CEST boB Stepp wrote:
>
>>I now have Git installed on my Windows 7 PC at work. The files that I
>>wish to put under Git version control exist on a Solaris 10
>>workstation. In the Git bash provided, I can ssh into the Solaris 10
>>machine. I also can the CuteFTP program on my Windows PC to
>>move/copy/etc. files between the two machines. How can I put these
>>Solaris files under version control under these circumstances? I
>>thought I had conceptually seen how to accomplish this via ssh, but if
>>it is doable, my limited knowledge of Git and ssh is insufficient to
>>find the path of success.
>
>
> ... (3) install git if needed ...

It seems Git is needed, but I am not allowed to install it on the
Solaris workstation. So is there a way around this?

>
> But uhhm, this is not Python at all ;-)

I was hoping for clemency on this point due to the earlier thread(s) I
started (Which included Python's unittest module.).



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


Re: [Tutor] How to use Git from Windows PC for files on Solaris machine where Git cannot be installed?

2015-04-29 Thread Albert-Jan Roskam

--
On Wed, Apr 29, 2015 4:21 PM CEST boB Stepp wrote:

>I now have Git installed on my Windows 7 PC at work. The files that I
>wish to put under Git version control exist on a Solaris 10
>workstation. In the Git bash provided, I can ssh into the Solaris 10
>machine. I also can the CuteFTP program on my Windows PC to
>move/copy/etc. files between the two machines. How can I put these
>Solaris files under version control under these circumstances? I
>thought I had conceptually seen how to accomplish this via ssh, but if
>it is doable, my limited knowledge of Git and ssh is insufficient to
>find the path of success.


Uhmm, I'd (1) open a Github or Bitbucket account (2) ssh to the solaris machine 
(3) install git if needed (4) clone your repo (which has just the readme file 
at this point) (5) fill the local files, git add what you want to track, the 
git commit and git push. (6) in windows you can use msysgit to connect to your 
remote repo.

But uhhm, this is not Python at all ;-)

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


Re: [Tutor] subprocess.Popen(..., cwd) and UNC paths

2015-04-29 Thread Albert-Jan Roskam

-
On Wed, Apr 29, 2015 4:11 PM CEST Peter Otten wrote:

>Albert-Jan Roskam wrote:
>
>> Hello,
>> 
>> Windows has the 'feature' that the CD command does not work with UNC
>> paths. So in the code below, I cannot use the 'cwd' parameter of
>> subprocess.Popen. Therefore I use pushd/popd to accomplish the same
>> effect. Is there a better way to do this? (other than using full path
>> names everywhere, or os.chdir). Would it be a useful improvement of Python
>> itself if cwd also works with UNC path?
>
>What is the error you get? I don't have Windows to verify, but a quick look 
>into the subprocess source suggests that it uses CreateProcess().
>Googling for that finds
>
>
>
>which states
>
>""
>lpCurrentDirectory [in, optional]
>The full path to the current directory for the process. The string can also 
>specify a UNC path.
>""

Hmmm, that sounds pretty convincing indeed (makes it even stranger that CD 
works the way it works). I believe it threw a WindowsError, indicating that the 
file(s) could not be found, because the dir was not changed. I actually first 
ran into this problem with this script, so with my current script I immediately 
refrained from using cwd: 
http://code.activestate.com/recipes/578883-git-pre-commit-hook-to-reject-large-files-using-py/
Git gave a fatal error in windows and the pushd/popd fixed it.

>> import sys
>> import os
>> import getpass
>> import subprocess
>> 
>> path = r'\\server\share\possibly with\space'
>> executable = 'blah.exe'
>> username = os.getenv("USERNAME")
>> password = getpass.getpass("Enter password: ")
>> infile =  sys.argv[1]
>> outfile = sys.argv[2]
>> cmds = ['pushd "%s" &&' % path, executable, username, password, infile,
>> outfile, "&& popd"]
>> 
>> result = subprocess.Popen(" ".join(cmds), shell=True)
>> error = result.stderr
>> if error:
>> raise RuntimeError(error.read())
>> 
>> Regards,
>> 
>> Albert-Jan
>> 
>> PS: Python 2.7 on Windows 7 32

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


Re: [Tutor] Good Taste Question: Using SQLite3 in Python

2015-04-29 Thread Alan Gauld

On 29/04/15 17:03, Jugurtha Hadjar wrote:


 (__, cursor) = self.init_db()


Don't use the __ 'variable' here, be explicit, it makes
maintenance much easier.



I actually searched specifically for something like this. In MATLAB,
there's the ~ that does this. I'm not trying to write Python in a MATLAB
style, but I was glad I found it here:

http://docs.python-guide.org/en/latest/writing/style/#create-an-ignored-variable


I've seen this before and strongly disagree with it.
I suspect the author has never had to run a major
maintenance project!

A single underscore is, I agree, far worse that a dunder symbol
but both are a maintenance nightmare. They are ambiguous,
difficult to remember, easy to overlook and if you change
your mind and decide you need to use it later it's a whole
new name to go back and introduce (or worse be tempted to use the 
meaningless symbol). And if you need another 'throw-away' name

later you use the same one, then forget there are two uses
and try to use it anyway (even in debugging) and get
completely wrong values, that may or may not look different
to what you expect. (looking different is good - you can
detect it easily, looking similar is very, very, bad!)...
its just a horror story waiting to trip you up.

It's far better to have a short meaningful name that is never
used than a bland, meaningless, generic symbol.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
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] Fwd: circular movement in pygame

2015-04-29 Thread Alan Gauld

On 29/04/15 10:15, diliup gabadamudalige wrote:

x=42 good
x += 42 -x ?

That does not go by a mile of what I asked.


You've asked three different things:

1) Why the += form gives different results from the assignment form,
2) Why some code you apparently wriotre worked outside a class
   but not in a class
3) A specific question about some code for moving an object
   in PyGame around in a circle

Number 1 is the only one I can comment on as I can't see your 
attachments. That is what I (and several others) have answered.

They are fundamentally different. There is no general way
to make an augmented assignment such that

x = f(y) and
x += f(y)  (or even g(y))

produce the same result except by the trivial

x += g(y) - x


Alan, are you telling me that there is no way that one can arrive at X2
which is the NEXT place that X1 will be after "some increment"?
old x position = X1


No, that is a completely separate question and has nothing
to do with using augmented assignment. But it does depend
on the specifics of the situation and is mainly a mathematical
problem rather than a Python one..


new x position= X1 + some increment value
which can be written as :new X = oldX + some increment value

which can be simplified to X += some increment value?


That may or may not be possible, it depends on what the
original equation in the pure assignment model is.


my orginal question was

*Why does the object NOT move in a circle when implemented as a class?*


Your original question was:

is there a way to do
self.rect.x +*= some value*
self.rect.y += some value

rather than

self.rect.x = self.radius * math.sin(self.angle) + self.center_x
self.rect.y = self.radius * math.cos(self.angle) + self.center_y

Which is about the use of augmented assignment.


All the code was provided.


No it wasn't. I have not seen any of your code because you persist
in sending it as attachments which (as you've been told) do not
work reliably in a text based mailing list. If you want
comments on the code either post it inline in your message
or as a link to a web site where we can all see it.


The above is  what I asked. (I hope this is clear enough)


Your class based code should work but without sight of it
I cannot begin to guess about that aspect of your problem.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
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] Fwd: circular movement in pygame

2015-04-29 Thread diliup gabadamudalige
x=42 good
x += 42 -x ?

That does not go by a mile of what I asked.
Alan, are you telling me that there is no way that one can arrive at X2
which is the NEXT place that X1 will be after "some increment"?
old x position = X1

new x position= X1 + some increment value
which can be written as :new X = oldX + some increment value

which can be simplified to X += some increment value?

my orginal question was

*Why does the object NOT move in a circle when implemented as a class?*

All the code was provided.


The above is  what I asked. (I hope this is clear enough)









On Wed, Apr 29, 2015 at 1:56 PM, Alan Gauld 
wrote:

> On 29/04/15 09:03, diliup gabadamudalige wrote:
>
>> Thank you Alan. Understood. I already knew that. My question is
>>
>> How to to do it the second way.
>> some code = what?
>>
>>  The point is you cannot do it.
> The second approach always uses the current value of x.
> The first approach may or may not use the current value
> of x. If it does not use x then the += style cannot be
> made to work (unless you tag a -x on at the end!
>
> x = 42
>
> x += 42-x
>
> Which is just stupid.
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>


-- 
Diliup Gabadamudalige

http://www.diliupg.com
http://soft.diliupg.com/

**
This e-mail is confidential. It may also be legally privileged. If you are
not the intended recipient or have received it in error, please delete it
and all copies from your system and notify the sender immediately by return
e-mail. Any unauthorized reading, reproducing, printing or further
dissemination of this e-mail or its contents is strictly prohibited and may
be unlawful. Internet communications cannot be guaranteed to be timely,
secure, error or virus-free. The sender does not accept liability for any
errors or omissions.
**
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: circular movement in pygame

2015-04-29 Thread diliup gabadamudalige
question to Lucas.

Not sure if this is what you're looking for, but I would also use cos for
the x coordinate as suggested.  If:

self.rect.x = self.radius * math.cos(self.angle) + self.center_x
self.rect.y = self.radius * math.sin(self.angle) + self.center_y

Take a derivative (assume:  angle += angular_vel * dt for every increment
in time dt), so that:

self.rect.x += -self.radius * math.sin(self.angle) * self.angular_vel * dt
self.rect.y += self.radius * math.cos(self.angle) * self.angular_vel * dt

what is dt?


On Wed, Apr 29, 2015 at 12:45 PM, diliup gabadamudalige 
wrote:

> Thanks all for the responses.
> Charles Cossé -  yes I can write a simple pygame program that makes a
> sprite move in a circle but it may not be the style and order that many may
> approve or accept. I consider myself a student. :)
> No one has pointed out why the object moves in a circle properly in the
> bit of code where it is addressed directly and why it does not when the
> same code is applied thru a class.
> I know that an object can be made to move around the circumference of a
> circle by constantly calculating the point and giving the x and y values
>
> 1. x = some code
>
> That is what I used and it worked. I was trying to find how we can do the
> same thing by updating the current position by doing
>
> 2. x += some code
>  Above 1 works. 2 does not. Why is that?
>
> Both the same code. The same variable is used with different names cause
> some others were confused when they were the same.
>
>  I hope this time I have answered correctly. No more attachments. (e mail
> or otherwise. :) )
>



-- 
Diliup Gabadamudalige

http://www.diliupg.com
http://soft.diliupg.com/

**
This e-mail is confidential. It may also be legally privileged. If you are
not the intended recipient or have received it in error, please delete it
and all copies from your system and notify the sender immediately by return
e-mail. Any unauthorized reading, reproducing, printing or further
dissemination of this e-mail or its contents is strictly prohibited and may
be unlawful. Internet communications cannot be guaranteed to be timely,
secure, error or virus-free. The sender does not accept liability for any
errors or omissions.
**
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: circular movement in pygame

2015-04-29 Thread diliup gabadamudalige
Thank you Alan. Understood. I already knew that. My question is

How to to do it the second way.
some code = what?
My question is, how does one arrive at the code to put in place of "some
code"? The code I used does not work correctly.
The code is in this chain of email.
I hope I am clear in what I am trying to do.



On Wed, Apr 29, 2015 at 1:18 PM, Alan Gauld 
wrote:

> On 29/04/15 08:15, diliup gabadamudalige wrote:
>
>  1. x = some code
>>
>> That is what I used and it worked. I was trying to find how we can do the
>> same thing by updating the current position by doing
>>
>> 2. x += some code
>>   Above 1 works. 2 does not. Why is that?
>>
>
>
> Because they do completely different things!
>
> 1 is simply
>
> x = some code
>
> 2 is
>
> x = x + some code
>
> In 2 you are adding x to some code.
>
> Of course they don't work the same.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Diliup Gabadamudalige

http://www.diliupg.com
http://soft.diliupg.com/

**
This e-mail is confidential. It may also be legally privileged. If you are
not the intended recipient or have received it in error, please delete it
and all copies from your system and notify the sender immediately by return
e-mail. Any unauthorized reading, reproducing, printing or further
dissemination of this e-mail or its contents is strictly prohibited and may
be unlawful. Internet communications cannot be guaranteed to be timely,
secure, error or virus-free. The sender does not accept liability for any
errors or omissions.
**
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Good Taste Question: Using SQLite3 in Python

2015-04-29 Thread Jugurtha Hadjar

On 04/29/2015 09:06 AM, Alan Gauld wrote:

In principle its an acceptable strategy. A close alternative
would be to name the queries as explicit class variables.
So for example you would use:

cur.execute(self.find_phone_query,())

Its less typing and less error prone in that you get a
syntax error on mistyping rather than a run time exception.



That's what I had initially but I used dictionaries for regexes I match 
the messages against to determine the type, I thought I'd organize stuff 
of the same nature together in a dictionary.


JUNK = 'JUNK'

RE_TYPE = {
'TYPE1'  : re.compile(r'xxx'),
'TYPE2'  : re.compile(r'yyy'),
  ...
'TYPEn'  : re.compile(r'aaa'),
}

Then to get the type of the message, I just have to do:

gen = (k for k in self.RE_TYPE if RE_TYPE[k].findall(msg_text))
msg_type = next(gen, self.JUNK)



- Methods closed the connection themselves, so I used `with` in
`init_db` instead of `try`, as it would close the connection
automatically and rollback (I hope I'm not making this up).


Try/except and with do different things but in this case
you can get away with it. The only loss is that your errors
here are not formatted in the same way as the other messages.


I wrote it to do one specific job that's to be followed by some other 
task that _would_ raise an exception.


Maybe it's lazy and am relying on the methods that call `init_db` to 
deal with the error. `init_db` just returns a connection and a cursor.. 
If the file didn't exist, it'd be created but without schema, the 
calling method (like `create` or `find` _will_, however produce an error 
as it tries to read/write.




Consider using docstrings rather than comments to describe the method
I see you do that below...


Roger that.


 (__, cursor) = self.init_db()


Don't use the __ 'variable' here, be explicit, it makes
maintenance much easier.



I actually searched specifically for something like this. In MATLAB, 
there's the ~ that does this. I'm not trying to write Python in a MATLAB 
style, but I was glad I found it here:


http://docs.python-guide.org/en/latest/writing/style/#create-an-ignored-variable

I was only interested in the cursor in that method. `init_db` returned 
only a connection in the beginning, but I didn't want to write 
conn.cursor every time.




 try:
 cursor.execute(
 self.QUERIES['FIND_PHONE'],
 (self.phone,)
 )
 found = cursor.fetchone()
 return True if found else False
 except Exception as e:
 return self.ERROR.format(e.args[0])


Don't catch Exception, it's too wide. Catch the
actual errors that might arise, be as specific as possible.


Thanks for bringing that to my attention.




 def create(self, seed_balance):
 ''' Create a database entry for the sender.'''

 conn, cursor = self.init_db()
 try:
 cursor.execute(
 self.QUERIES['CREATE'],
 (self.phone, seed_balance)
 )
 conn.commit()
 except Exception as e:
 return self.ERROR.format(e.args[0])



as above




Thank you for the feedback, Alan.


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


[Tutor] Fwd: Function works one time then subsequently fails

2015-04-29 Thread Jim Mooney Py3.4.3winXP
On 28 April 2015 at 22:40, Cameron Simpson  wrote:

>
> As with all things, sometimes that cannot be reasonably achieved, but it
> is usually so.
>
> We can pick over your code as well if you like. Should we?
>
> Cheers,
> Cameron Simpson 


Sure, but let me include the full working program after fixup. Although I
still have to write another program to feed it random problems to work it
out. It's a bit spacey, but I ran it through the pep8 program and it
suggested that. I think two spaces between such tiny functions is overkill,
though.

"""
Takes the name of a binary math operation and two numbers from input,
repeatedly, and displays the results until done
"""

def add(a, b):
return a + b


def subtract(a, b):
return b - a


def minus(a, b):
return a - b


def multiply(a, b):
return a * b


def divide(a, b):
return a / b


operations = {'add': add, '+': add, 'plus': add, 'subtract': subtract,
'subtracted': subtract,
  '-': minus, 'minus': minus, 'multiply': multiply, '*':
multiply, 'multiplied': multiply,
  'times': multiply, 'divide': divide, '/': divide, 'divided':
divide}

def test_number(astring):
"""
Input: A string that should represent a valid int or float. Output:
An int or float on success. None on failure.
"""
for make_type in (int, float):
try:
return make_type(astring)
except ValueError:
pass
return None


def parse_string(math_string):
"""Input: A math string with a verbal or mathematical operation
and two valid numbers to operate on. Extra numbers and operations
are ignored. Output: A tuple containing a function corresponding
to the operation and the two numbers. Returns None on failure.
"""
operation = None
tokens = math_string.split()
numbers = []
for token in tokens:
if token in operations:
operation = operations[token]
elif test_number(token) != None:
numbers.append(test_number(token))
if len(numbers) > 1:
break
if operation is None or len(numbers) < 2:
return None
else:
return operation, numbers[0], numbers[1]

instructions = '''Enter two numbers and one of the four basid math
operations,
either mathematical or verbal. i.e. 3 + 2, 12 divided by 14, 10 minus 4,
etc.
Enter done to quit.
'''
try:
user_input = input(instructions)
while True:
if user_input == 'done':
break
result = parse_string(user_input)
if result == None:
print("Not a valid math operation.")
else:
func, num1, num2 = result
print(func(num1, num2))
user_input = input()
except KeyboardInterrupt:
print("Program terminated by user")


-- 
Jim

If you only had one hour left to live, would you spend it on Facebook,
Twitter, or Google Plus?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] How to use Git from Windows PC for files on Solaris machine where Git cannot be installed?

2015-04-29 Thread boB Stepp
I now have Git installed on my Windows 7 PC at work. The files that I
wish to put under Git version control exist on a Solaris 10
workstation. In the Git bash provided, I can ssh into the Solaris 10
machine. I also can the CuteFTP program on my Windows PC to
move/copy/etc. files between the two machines. How can I put these
Solaris files under version control under these circumstances? I
thought I had conceptually seen how to accomplish this via ssh, but if
it is doable, my limited knowledge of Git and ssh is insufficient to
find the path of success.

In order to at least start putting these files under version control,
I have created a repository for these files on an intranet drive, used
CuteFTP to copy them into the repository from Solaris, and cloned this
repository to my Windows PC. My current workflow is very clunky
indeed: 1) Bring up file(s) to edit in my Windows editor from my local
project working directory. 2) Perform edits. 3) Save edits. 4) In Git
bash stage these. 5) Either CuteFTP or scp from Git bash the changed
files to Solaris. 6) Test files in Solaris. 7) Repeat. As needed do
Git commits and pushes.

This is better than what I had been doing. At least I *am* moving into
the version control world. But how can I make this (hopefully, lots)
better?

BTW, I have Git working well at home. As an update I am working on
learning how to use Python's unittest module at home. Once I am
successful there, I will implement this at work: after the fact on
existing projects and from the get-go on new ones.

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


Re: [Tutor] subprocess.Popen(..., cwd) and UNC paths

2015-04-29 Thread Peter Otten
Albert-Jan Roskam wrote:

> Hello,
> 
> Windows has the 'feature' that the CD command does not work with UNC
> paths. So in the code below, I cannot use the 'cwd' parameter of
> subprocess.Popen. Therefore I use pushd/popd to accomplish the same
> effect. Is there a better way to do this? (other than using full path
> names everywhere, or os.chdir). Would it be a useful improvement of Python
> itself if cwd also works with UNC path?

What is the error you get? I don't have Windows to verify, but a quick look 
into the subprocess source suggests that it uses CreateProcess().
Googling for that finds



which states

"""
lpCurrentDirectory [in, optional]
The full path to the current directory for the process. The string can also 
specify a UNC path.
"""

> import sys
> import os
> import getpass
> import subprocess
> 
> path = r'\\server\share\possibly with\space'
> executable = 'blah.exe'
> username = os.getenv("USERNAME")
> password = getpass.getpass("Enter password: ")
> infile =  sys.argv[1]
> outfile = sys.argv[2]
> cmds = ['pushd "%s" &&' % path, executable, username, password, infile,
> outfile, "&& popd"]
> 
> result = subprocess.Popen(" ".join(cmds), shell=True)
> error = result.stderr
> if error:
> raise RuntimeError(error.read())
> 
> Regards,
> 
> Albert-Jan
> 
> PS: Python 2.7 on Windows 7 32
> 
> 
> 
> ~~
> 
> All right, but apart from the sanitation, the medicine, education, wine,
> public order, irrigation, roads, a
> 
> fresh water system, and public health, what have the Romans ever done for
> us?
> 
> ~~
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor


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


Re: [Tutor] subprocess.Popen(..., cwd) and UNC paths

2015-04-29 Thread Dave Angel

On 04/29/2015 08:47 AM, Albert-Jan Roskam wrote:

Hello,

Windows has the 'feature' that the CD command does not work with UNC paths.
So in the code below, I cannot use the 'cwd' parameter of subprocess.Popen.
Therefore I use pushd/popd to accomplish the same effect. Is there a better way 
to do this?
(other than using full path names everywhere, or os.chdir). Would it be a 
useful improvement
of Python itself if cwd also works with UNC path?

import sys
import os
import getpass
import subprocess

path = r'\\server\share\possibly with\space'
executable = 'blah.exe'
username = os.getenv("USERNAME")
password = getpass.getpass("Enter password: ")
infile =  sys.argv[1]
outfile = sys.argv[2]
cmds = ['pushd "%s" &&' % path, executable, username, password, infile, outfile, "&& 
popd"]

result = subprocess.Popen(" ".join(cmds), shell=True)
error = result.stderr
if error:
 raise RuntimeError(error.read())

Regards,

Albert-Jan

PS: Python 2.7 on Windows 7 32



Just a comment about Windows.  There is a current directory for each 
lettered drive partition.  But a unc name is not necessarily on any 
known drive.


And if executable, infile and outfile might have spaces within them, you 
need to quote them as well.





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


[Tutor] subprocess.Popen(..., cwd) and UNC paths

2015-04-29 Thread Albert-Jan Roskam
Hello,

Windows has the 'feature' that the CD command does not work with UNC paths.
So in the code below, I cannot use the 'cwd' parameter of subprocess.Popen.
Therefore I use pushd/popd to accomplish the same effect. Is there a better way 
to do this?
(other than using full path names everywhere, or os.chdir). Would it be a 
useful improvement
of Python itself if cwd also works with UNC path? 

import sys
import os
import getpass
import subprocess

path = r'\\server\share\possibly with\space'
executable = 'blah.exe'
username = os.getenv("USERNAME")
password = getpass.getpass("Enter password: ")
infile =  sys.argv[1]
outfile = sys.argv[2]
cmds = ['pushd "%s" &&' % path, executable, username, password, infile, 
outfile, "&& popd"]

result = subprocess.Popen(" ".join(cmds), shell=True)
error = result.stderr
if error:
raise RuntimeError(error.read())

Regards,

Albert-Jan

PS: Python 2.7 on Windows 7 32



~~

All right, but apart from the sanitation, the medicine, education, wine, public 
order, irrigation, roads, a 

fresh water system, and public health, what have the Romans ever done for us?

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


Re: [Tutor] circular movement in pygame

2015-04-29 Thread Dave Angel

On 04/29/2015 03:15 AM, diliup gabadamudalige wrote:

Thanks all for the responses.
Charles Cossé -  yes I can write a simple pygame program that makes a
sprite move in a circle but it may not be the style and order that many may
approve or accept. I consider myself a student. :)
No one has pointed out why the object moves in a circle properly in the bit
of code where it is addressed directly and why it does not when the same
code is applied thru a class.
I know that an object can be made to move around the circumference of a
circle by constantly calculating the point and giving the x and y values

1. x = some code

That is what I used and it worked. I was trying to find how we can do the
same thing by updating the current position by doing

2. x += some code


2.  x +=  some different code


  Above 1 works. 2 does not. Why is that?


Because there is always some little error in the value you're adding to 
x, since it's a floating point value calculated using transcendentals. 
If you're going to loop thousands of times, those little errors add up.


Sometime try measuring a mile using two 12-inch rulers, placing each one 
before picking up the previous. By the time you're done, you'll probably 
be off a hundred feet.





Both the same code.


Not at all the same.


The same variable is used with different names cause
some others were confused when they were the same.

  I hope this time I have answered correctly. No more attachments. (e mail
or otherwise. :) )



I can't necessarily understand the code since you use pygame and I'm not 
familiar with pygame.  In your itertools loop, you always reset the 
angle back to 100 degrees.


In your while loop, you issue a call to draw.circle().  Perhaps that's 
the working code you're talking about.




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


Re: [Tutor] comparison on Types

2015-04-29 Thread Ian D
Ok thanks. I thought it would be better with just a while True loop; for simple 
clarity.


> Date: Wed, 29 Apr 2015 21:14:06 +1000
> From: st...@pearwood.info
> To: tutor@python.org
> Subject: Re: [Tutor] comparison on Types
>
> On Wed, Apr 29, 2015 at 09:44:28AM +, Ian D wrote:
>
>> I was looking at the example code below. I am using python 2.7.
>>
>> I am wondering why when I substitute the while n! = "guess" to while
>> n!= guess (<-- no quotes) I get a problem?
>
> Really? What sort of problem? It looks okay to me, although I haven't
> run it.
>
>
>> The Type string is used for the first conditional comparison in the
>> outer While loop, but afterwards the Type is an int.
>>
>> I would have expected the guess variable to be used as Type int as it
>> seems to be cast in the raw_input statement and would be comparable to
>> another int that's stored in variable n. Thanks
>
> I'm having difficulty understanding your question. It might help if you
> explain what you think the code should do, versus what it actually does.
> Do you get an error? Then post the full error traceback, starting from
> the line "Traceback" to the end.
>
> It also might help to understand that in Python, *variables* don't have
> types, but values do. Variables can take any value, and take on the type
> of that value until such time as they change to a different value:
>
> py> x = "Hello"
> py> type(x)
> 
> py> x = 23
> py> type(x)
> 
>
>
>
>
> Looking at your code, I can see only one obvious (to me) problem:
>
>> import random
>> n = random.randint(1, 99)
>> guess = int(raw_input("Enter an integer from 1 to 99: "))
>> while n != "guess":
>
> By using the string "guess", you guarantee that n is *never* equal on
> the first test. That means that the loop will be entered. If you remove
> the quotation marks, and compare n != guess (here guess is the variable,
> not the literal string) then if your guess happens to be correct on the
> first time, the while loop will not be entered and the program will just
> end.
>
> print
>> if guess < n:
>> print "guess is low"
>> guess = int(raw_input("Enter an integer from 1 to 99: "))
>> elif guess> n:
>> print "guess is high"
>> guess = int(raw_input("Enter an integer from 1 to 99: "))
>> else:
>> print "you guessed it!"
>> break
>> print
>
>
> Try this instead:
>
>
> import random
> n = random.randint(1, 99)
> guess = 0 # Guaranteed to not equal n.
> while n != guess:
> guess = int(raw_input("Enter an integer from 1 to 99: "))
> print
> if guess < n:
> print "guess is too low"
> elif guess> n:
> print "guess is too high"
> else:
> print "guessed correctly!"
>
>
>
>
> Does that help?
>
>
>
> --
> Steve
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>   
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] if then statements

2015-04-29 Thread Dave Angel

On 04/28/2015 09:24 PM, Jacqueline G Solis wrote:

hello,

I keep getting a syntax error. Could you please explain why that happens and 
how to correct it.


def main ():
 print( "Welcome to Gonzo Burger!")
 order= int(input("Enter 1 if you want a hamburger,\
 or 2 if you want a cheeseburger:" ))
 if order == 1 :
print("order: 1")
 else:
print("Order: 2")

 drink=int(input("Thank you! Next, enter a 1 if you want a Coke,\
 or a 2 if you want a Sprite:")
 if drink == 1 :


The line before this one has a missing right paren at the end.  you 
close the input() function, but not the int() function.  So the next 
thing would have to be a comma, not a reserved token "if"



   print("Order: 1")
 else:
   print("Order: 2")

 print("Thank you! You ordered:")
 if order == 1:
   print("- Hamburger")
 else:
   print("- Cheeseburger")
 if drink == 1 :
   print("- Coke")
 else:
   print("- Sprite")

main ()




-Jackie
p.s: the error happens in the second if statement.


That's a good hint.  Better would be to include the full traceback with 
the error message, instead of a one-word summary.  No matter in this 
caswe, but it's a good habit to get into.


Incidentally, for syntax errors, it's pretty common for the real problem 
to be in the line before, or even earlier.  I'd assume this error 
pointed at the 'if'.  So you're really only going back one token.





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


Re: [Tutor] if then statements

2015-04-29 Thread Steven D'Aprano
On Tue, Apr 28, 2015 at 08:24:57PM -0500, Jacqueline G Solis wrote:
> hello,
> 
> I keep getting a syntax error. Could you please explain why that 
> happens and how to correct it.

Syntax errors are sometimes a bit tricky. Usually, they tell you were 
the error is:


py> if (x + 1:
  File "", line 1
if (x + 1:
 ^
SyntaxError: invalid syntax


Notice the blank line immediately before "SyntaxError"? If you look 
carefully, you will see a caret ^ which points to the ":" colon in the 
line before. (In your email, it may not quite line up correctly, but in 
the Python interpreter and the console, they should like up.) That 
should make it obvious that I am missing a closing parenthesis before 
the colon.

But sometimes Python doesn't notice the syntax error until the line 
*after* the actual problem:


py> x = (y + 1
... if x:
  File "", line 2
if x:
^
SyntaxError: invalid syntax


The actual problem is that I am missing a round bracket in the previous 
line, but Python doesn't realise it until it gets to the colon.

Does that help?


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


Re: [Tutor] comparison on Types

2015-04-29 Thread Steven D'Aprano
On Wed, Apr 29, 2015 at 09:44:28AM +, Ian D wrote:

> I was looking at the example code below. I am using python 2.7.
> 
> I am wondering why when I substitute the while n! = "guess" to while 
> n!= guess (<-- no quotes) I get a problem?

Really? What sort of problem? It looks okay to me, although I haven't 
run it.


> The Type string is used for the first conditional comparison in the 
> outer While loop, but afterwards the Type is an int.
> 
> I would have expected the guess variable to be used as Type int as it 
> seems to be cast in the raw_input statement and would be comparable to 
> another int that's stored in variable n. Thanks

I'm having difficulty understanding your question. It might help if you 
explain what you think the code should do, versus what it actually does. 
Do you get an error? Then post the full error traceback, starting from 
the line "Traceback" to the end.

It also might help to understand that in Python, *variables* don't have 
types, but values do. Variables can take any value, and take on the type 
of that value until such time as they change to a different value:

py> x = "Hello"
py> type(x)

py> x = 23
py> type(x)





Looking at your code, I can see only one obvious (to me) problem:

> import random
> n = random.randint(1, 99)
> guess = int(raw_input("Enter an integer from 1 to 99: "))
> while n != "guess":

By using the string "guess", you guarantee that n is *never* equal on 
the first test. That means that the loop will be entered. If you remove 
the quotation marks, and compare n != guess (here guess is the variable, 
not the literal string) then if your guess happens to be correct on the 
first time, the while loop will not be entered and the program will just 
end.

 print
> if guess < n:
> print "guess is low"
> guess = int(raw_input("Enter an integer from 1 to 99: "))
> elif guess> n:
> print "guess is high"
> guess = int(raw_input("Enter an integer from 1 to 99: "))
> else:
> print "you guessed it!"
> break
> print   


Try this instead:


import random
n = random.randint(1, 99)
guess = 0  # Guaranteed to not equal n.
while n != guess:
guess = int(raw_input("Enter an integer from 1 to 99: "))
print
if guess < n:
print "guess is too low"
elif guess > n:
print "guess is too high"
else:
print "guessed correctly!"




Does that help?



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


Re: [Tutor] comparison on Types

2015-04-29 Thread Peter Otten
Ian D wrote:

> I was looking at the example code below. I am using python 2.7.
> 
> I am wondering why when I substitute the while n! = "guess" to while n!=
> guess (<-- no quotes) I get a problem?

What is that problem? The only thing I see is that the

> else:
> print "you guessed it!"
> break

branch is never executed. You remove it and instead put the 

> print "you guessed it!"

statement after the loop.
 
> The Type string is used for the first conditional comparison in the outer
> While loop, but afterwards the Type is an int.

Not even that. The guess name is bound to an integer before the loop is 
entered:

> guess = int(raw_input("Enter an integer from 1 to 99: "))
  while n != guess:
 ...

> I would have expected the guess variable to be used as Type int as it
> seems to be cast in the raw_input statement and would be comparable to
> another int that's stored in variable n. Thanks

You have that right.

> import random
> n = random.randint(1, 99)
> guess = int(raw_input("Enter an integer from 1 to 99: "))
> while n != "guess":
> print
> if guess < n:
> print "guess is low"
> guess = int(raw_input("Enter an integer from 1 to 99: "))
> elif guess> n:
> print "guess is high"
> guess = int(raw_input("Enter an integer from 1 to 99: "))
> else:
> print "you guessed it!"
> break
> print


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


[Tutor] comparison on Types

2015-04-29 Thread Ian D
I was looking at the example code below. I am using python 2.7.

I am wondering why when I substitute the while n! = "guess" to while n!= guess 
(<-- no quotes) I get a problem?

The Type string is used for the first conditional comparison in the outer While 
loop, but afterwards the Type is an int.

I would have expected the guess variable to be used as Type int as it seems to 
be cast in the raw_input statement and would be comparable to another int 
that's stored in variable n. Thanks


import random
n = random.randint(1, 99)
guess = int(raw_input("Enter an integer from 1 to 99: "))
while n != "guess":
print
if guess < n:
print "guess is low"
guess = int(raw_input("Enter an integer from 1 to 99: "))
elif guess> n:
print "guess is high"
guess = int(raw_input("Enter an integer from 1 to 99: "))
else:
print "you guessed it!"
break
print 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Good Taste Question: Using SQLite3 in Python

2015-04-29 Thread Peter Otten
Jugurtha Hadjar wrote:

> I have a class with methods that access a database (SQLite3). I have 
> included an excerpt showin reading and writing and would like to know if 
> I'm doing it right. (i.e: Is it bad code and what to improve).
> 
> Here are some improvements and my rationale (check my thinking):
> 
> - Initially, each method had its SQL statement(s) inside, but I grouped 
> all statements in a dictionary, with operations as keys, as a class 
> 'constant' as per previous advice on this mailing list.
> 
> - Each method used sqlite3 module on its own, but it was repetitive so I 
> put that part in its own method `init_db` that returns a tuple 
> consisting in a connection and a cursor.
> 
> - Sometimes there was an exception raised, so I used `try` in `init_db`.
> 
> - Methods closed the connection themselves, so I used `with` in 
> `init_db` instead of `try`, as it would close the connection 
> automatically and rollback (I hope I'm not making this up).
> 
> Here's the excerpt (`DB_FILES` and `QUERIES` are not included here for 
> more clarity).
> 
> Thank you.
> 
> 
> 
> def __init__(self, phone):
> 
> # Get preliminary information on user and make them
> # available.
> 
> self.phone = phone
> self.known = self.find()
> 
> if self.known:
> self.balance = self.get_balance()
> else:
>> self.balance = None
> 
> def init_db(self):
> with sqlite3.connect(self.DB_FILE) as conn:
> return conn, conn.cursor()
> 
> def find(self):
> '''Find the phone in the users database.'''
> 
> (__, cursor) = self.init_db()
> try:
> cursor.execute(
> self.QUERIES['FIND_PHONE'],
> (self.phone,)
> )
> found = cursor.fetchone()
> return True if found else False
> except Exception as e:
> return self.ERROR.format(e.args[0])
> 
> def create(self, seed_balance):
> ''' Create a database entry for the sender.'''
> 
> conn, cursor = self.init_db()
> try:
> cursor.execute(
> self.QUERIES['CREATE'],
> (self.phone, seed_balan>ce)
> )
> conn.commit()
> except Exception as e:
> return self.ERROR.format(e.args[0])

My random observations:

(1) find() and create() look very similar. Try hard to factor out common 
code. You might even combine it into a single method ensure_balance(phone).

(2) According to

https://docs.python.org/dev/library/sqlite3.html#using-the-connection-as-a-context-manager

- the context manager automatically commits
- you can run sql directly on the connection

It might by a good idea to refactor init_db() to just return the connection 
and then use it as

with self.init_db() as conn:
return conn.execute(
self.QUERIES['FIND_PHONE'], 
(self.phone,)).fetchone() is not None

If you need a cursor you can easily get one from the connection. If you want 
more complex handling later you can always turn init_db() into a 
contextmanager (see
 
). 

(3) Catching Exception is overly broad. You will also catch a typo like

cursor.execute(
self.QUERIES['CERATE'],
(self.phone, seed_balance)
)

where the proper fix is to modify the script. Only catch exceptions that you 
can actually handle. Example: a table doesn't exist, and you want to create 
it lazily on first access. Let all other exceptions just bubble up. It may 
seem lazy, but a complete traceback is invaluable for identifying and fixing 
a bug.

(4) self.ERROR.format(e.args[0])

is probably a string with len() > 0, and thus True in a boolean context. 
>From that follows an exception in the find() method in

> self.known = self.find()

causes the following if-suite to be run

> if self.known:
> self.balance = self.get_balance()

and if get_balance() has a same idea of proper exception handling

self.balance will end up containing an error message.

(5) From point (4) I conclude that you don't have unit tests that cover your 
code. You should really write some of these before pondering about stylistic 
issues. Unit tests 

- help avoid errors
- make changes in the code less of a gamble because if the tests succeed 
after the change you can be confident the change didn't introduce an error
- what you might not expect: how drastically tests affect the style of your 
code. You'll see yoursel

Re: [Tutor] Fwd: circular movement in pygame

2015-04-29 Thread Alan Gauld

On 29/04/15 09:03, diliup gabadamudalige wrote:

Thank you Alan. Understood. I already knew that. My question is

How to to do it the second way.
some code = what?


The point is you cannot do it.
The second approach always uses the current value of x.
The first approach may or may not use the current value
of x. If it does not use x then the += style cannot be
made to work (unless you tag a -x on at the end!

x = 42

x += 42-x

Which is just stupid.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
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] Function works one time then subsequently fails

2015-04-29 Thread Alan Gauld

On 29/04/15 04:58, Jim Mooney Py3winXP wrote:


numbers = []


Note that you chose to make this global.


def parse_string(math_string):
 """Input: A math string with a verbal or mathematical operation
 and two valid numbers to operate on. Extra numbers and operations
 are ignored. Output: A tuple containing a function corresponding
 to the operation and the two numbers. Returns None on failure.
 """


General comment. returning a mixture of None and valid data
is a recipe for confusion later. Its better to fail by
raising an exception, say a ValueError for example,
or even create a bespoke error.


 operation = None
 tokens = math_string.split()
 for token in tokens:
 if token in operations:
 operation = operations[token]
 elif test_number(token) != None:
 numbers.append(test_number(token))
 if len(numbers) > 1:
 break
 if operation is None or len(numbers) < 2:
 return None
 else:
 return operation, numbers[0], numbers[1]

REPL

result = parse_string('1 minus 15')
func, number1, number2 = result
func(number1, number2)

-14

result = parse_string('1 minus 15')
print(result)

None


You never empty numbers so it already contains >1 numbers.
Your loop breaks. And operation is None.
So you return None.

That's why raising an error with suitable text would be clearer.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
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] if then statements

2015-04-29 Thread Alan Gauld

On 29/04/15 02:24, Jacqueline G Solis wrote:

hello,

I keep getting a syntax error.


If you get an error always include the full message text in your 
queries. It helps enormously in finding the problem.



Could you please explain why that happens and how to correct it.


But in this case its obvious...


def main ():
 print( "Welcome to Gonzo Burger!")
 order= int(input("Enter 1 if you want a hamburger,\
 or 2 if you want a cheeseburger:" ))
 if order == 1 :
print("order: 1")
 else:
print("Order: 2")

 drink=int(input("Thank you! Next, enter a 1 if you want a Coke,\
 or a 2 if you want a Sprite:")


Count the parentheses in the line above.


p.s: the error happens in the second if statement.


If you'd sent the error message you wouldn't have to tell us that :-)


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
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] Good Taste Question: Using SQLite3 in Python

2015-04-29 Thread Alan Gauld

On 29/04/15 04:06, Jugurtha Hadjar wrote:


- Initially, each method had its SQL statement(s) inside, but I grouped
all statements in a dictionary, with operations as keys, as a class
'constant' as per previous advice on this mailing list.


We can't see that in the code you posted.
In principle its an acceptable strategy. A close alternative
would be to name the queries as explicit class variables.
So for example you would use:

cur.execute(self.find_phone_query,())

Its less typing and less error prone in that you get a
syntax error on mistyping rather than a run time exception.


- Each method used sqlite3 module on its own, but it was repetitive so I
put that part in its own method `init_db` that returns a tuple
consisting in a connection and a cursor.


That's a common approach.


- Sometimes there was an exception raised, so I used `try` in `init_db`.

- Methods closed the connection themselves, so I used `with` in
`init_db` instead of `try`, as it would close the connection
automatically and rollback (I hope I'm not making this up).


Try/except and with do different things but in this case
you can get away with it. The only loss is that your errors
here are not formatted in the same way as the other messages.


Here's the excerpt




 def __init__(self, phone):

 # Get preliminary information on user and make them
 # available.


Consider using docstrings rather than comments to describe the method
I see you do that below...


 self.phone = phone
 self.known = self.find()

 if self.known:
 self.balance = self.get_balance()
 else:
 self.balance = None

 def init_db(self):
 with sqlite3.connect(self.DB_FILE) as conn:
 return conn, conn.cursor()

 def find(self):
 '''Find the phone in the users database.'''

 (__, cursor) = self.init_db()


Don't use the __ 'variable' here, be explicit, it makes
maintenance much easier.


 try:
 cursor.execute(
 self.QUERIES['FIND_PHONE'],
 (self.phone,)
 )
 found = cursor.fetchone()
 return True if found else False
 except Exception as e:
 return self.ERROR.format(e.args[0])


Don't catch Exception, it's too wide. Catch the
actual errors that might arise, be as specific as possible.


 def create(self, seed_balance):
 ''' Create a database entry for the sender.'''

 conn, cursor = self.init_db()
 try:
 cursor.execute(
 self.QUERIES['CREATE'],
 (self.phone, seed_balance)
 )
 conn.commit()
 except Exception as e:
 return self.ERROR.format(e.args[0])



as above


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
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] if then statements

2015-04-29 Thread Mark Lawrence

On 29/04/2015 02:24, Jacqueline G Solis wrote:

hello,

I keep getting a syntax error. Could you please explain why that happens and 
how to correct it.


def main ():
 print( "Welcome to Gonzo Burger!")
 order= int(input("Enter 1 if you want a hamburger,\
 or 2 if you want a cheeseburger:" ))
 if order == 1 :
print("order: 1")
 else:
print("Order: 2")

 drink=int(input("Thank you! Next, enter a 1 if you want a Coke,\
 or a 2 if you want a Sprite:")
 if drink == 1 :
   print("Order: 1")
 else:
   print("Order: 2")

 print("Thank you! You ordered:")
 if order == 1:
   print("- Hamburger")
 else:
   print("- Cheeseburger")
 if drink == 1 :
   print("- Coke")
 else:
   print("- Sprite")

main ()




-Jackie
p.s: the error happens in the second if statement.



No it doesn't :)  That's where it gets found, but the error is actually 
before then, and as a learning exercise I'll let you find it.  Look very 
carefully at "order=..." and "drink=..." and I'm sure you'll spot the 
difference.


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

Mark Lawrence

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


Re: [Tutor] Fwd: circular movement in pygame

2015-04-29 Thread Alan Gauld

On 29/04/15 08:15, diliup gabadamudalige wrote:


1. x = some code

That is what I used and it worked. I was trying to find how we can do the
same thing by updating the current position by doing

2. x += some code
  Above 1 works. 2 does not. Why is that?



Because they do completely different things!

1 is simply

x = some code

2 is

x = x + some code

In 2 you are adding x to some code.

Of course they don't work the same.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
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] if then statements

2015-04-29 Thread Jacqueline G Solis
hello,

I keep getting a syntax error. Could you please explain why that happens and 
how to correct it. 


def main ():
print( "Welcome to Gonzo Burger!")
order= int(input("Enter 1 if you want a hamburger,\
or 2 if you want a cheeseburger:" ))
if order == 1 :
   print("order: 1")
else:
   print("Order: 2")

drink=int(input("Thank you! Next, enter a 1 if you want a Coke,\
or a 2 if you want a Sprite:")
if drink == 1 :
  print("Order: 1")
else:
  print("Order: 2")

print("Thank you! You ordered:")
if order == 1:
  print("- Hamburger")
else:
  print("- Cheeseburger")
if drink == 1 :
  print("- Coke")
else:
  print("- Sprite")

main ()


 

-Jackie
p.s: the error happens in the second if statement.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: circular movement in pygame

2015-04-29 Thread diliup gabadamudalige
Thanks all for the responses.
Charles Cossé -  yes I can write a simple pygame program that makes a
sprite move in a circle but it may not be the style and order that many may
approve or accept. I consider myself a student. :)
No one has pointed out why the object moves in a circle properly in the bit
of code where it is addressed directly and why it does not when the same
code is applied thru a class.
I know that an object can be made to move around the circumference of a
circle by constantly calculating the point and giving the x and y values

1. x = some code

That is what I used and it worked. I was trying to find how we can do the
same thing by updating the current position by doing

2. x += some code
 Above 1 works. 2 does not. Why is that?

Both the same code. The same variable is used with different names cause
some others were confused when they were the same.

 I hope this time I have answered correctly. No more attachments. (e mail
or otherwise. :) )
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor