[Tutor] Naming conventions

2015-04-28 Thread Mitesh H. Budhabhatti
Hello Friends,

Can you please suggest good naming conventions/guidelines to following
while writing Python code?  Thanks.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Trouble Downloading 3.2 tutorial

2015-04-28 Thread O'Shea, Connor
Greetings. I have been experiencing difficulty getting my computer to
download the 3.2 python program. My computer has Windows 8 software. What
do you suggest I do to address this problem?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Naming conventions

2015-04-28 Thread Mark Lawrence

On 28/04/2015 08:31, Mitesh H. Budhabhatti wrote:

Hello Friends,

Can you please suggest good naming conventions/guidelines to following
while writing Python code?  Thanks.



PEP 8 - Style Guide for Python Code at 
https://www.python.org/dev/peps/pep-0008/


--
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] Trouble Downloading 3.2 tutorial

2015-04-28 Thread Alan Gauld

On 28/04/15 00:08, O'Shea, Connor wrote:

Greetings. I have been experiencing difficulty getting my computer to
download the 3.2 python program. My computer has Windows 8 software. What
do you suggest I do to address this problem?



You don't say what kind of "trouble" nor which distribution of
Python you are trying to download.

If its the official python.org one then, as a Windows user I
suggest you try the ActiveState  site since their version
includes many extra Windows features.

Also you say Python v3.2 however the latest version is v3.4.
Unless you have a strong reason to use 3.2 I suggest you
get 3.4 instead, any 3.2 code should run under 3.4.

If you are trying to download one of the "super Pythons"
like Anaconda then I can't help and suggest you ask on
their user fora.

If none of that helps come back to us with a more detailed
description of exactly what you are trying to do, where,
what happens, and any error messages you see.

--
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] pip install M2crypto

2015-04-28 Thread Alan Gauld

On 28/04/15 03:14, Juanald Reagan wrote:

Good Evening,

  I am trying to install the M2crypto package via pip and receive an error.
Python version is 2.7.4, any ideas on how to fix the SWIG error?


Do you have SWIG installed? It should be in your repo.




 unable to execute swig: No such file or directory

 error: command 'swig' failed with exit status 1



--
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] How to output dictionary data to CSV file

2015-04-28 Thread Paradox

I have some data structured like this:

{'B002':'NRP 2014','B003':'HBB 2015'}

Basically account numbers and project names, each account number has a 
project name.  I represent it in a dictionary because that seemed the 
best way to keep the account numbers and project names together.  I want 
to save that information to a file, CSV seemed the easiest format 
(though I am open to suggestions if there is a better way!).  I expected 
I could write a function that would create a CSV file that looks like this:


B002,NRP 2014
B003,HBB 2015

I thought the DictWriter method of the CSV module should do the trick so 
wrote this:


def write_fqas(fqa_csv,fqa_dict):
with open('fqa_csv','w') as csvfile:
writer = csv.DictWriter(csvfile,fieldnames=['FQA','Description']
writer.writerows(fqa_dict)

This didn't yield the results I was looking for, instead it raises

ValueError: dict contains fields not in fieldnames: 'B', '0', '0', '2'

It seems to be parsing through the key of the first item in the 
dictionary rather than simply saving it to the CSV file as the first 
field on a line (like I expected).  Obviously there is something about 
how csv.DictWriter works that I don't understand.


Any assistance is appreciated.

thomas
==
Thomas C. Hicks, MD, MPH
Training Manager, Gansu Gateway
Lanzhou, Gansu, PR China
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to output dictionary data to CSV file

2015-04-28 Thread Paradox

How rude of me, I neglected to note I am using Python 3.4.3.

On 04/28/2015 04:51 PM, Paradox wrote:

I have some data structured like this:

{'B002':'NRP 2014','B003':'HBB 2015'}

Basically account numbers and project names, each account number has a 
project name.  I represent it in a dictionary because that seemed the 
best way to keep the account numbers and project names together.  I 
want to save that information to a file, CSV seemed the easiest format 
(though I am open to suggestions if there is a better way!).  I 
expected I could write a function that would create a CSV file that 
looks like this:


B002,NRP 2014
B003,HBB 2015

I thought the DictWriter method of the CSV module should do the trick 
so wrote this:


def write_fqas(fqa_csv,fqa_dict):
with open('fqa_csv','w') as csvfile:
writer = csv.DictWriter(csvfile,fieldnames=['FQA','Description']
writer.writerows(fqa_dict)

This didn't yield the results I was looking for, instead it raises

ValueError: dict contains fields not in fieldnames: 'B', '0', '0', '2'

It seems to be parsing through the key of the first item in the 
dictionary rather than simply saving it to the CSV file as the first 
field on a line (like I expected).  Obviously there is something about 
how csv.DictWriter works that I don't understand.


Any assistance is appreciated.

thomas
==
Thomas C. Hicks, MD, MPH
Training Manager, Gansu Gateway
Lanzhou, Gansu, PR China


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


Re: [Tutor] How to output dictionary data to CSV file

2015-04-28 Thread Peter Otten
Paradox wrote:

> I have some data structured like this:
> 
> {'B002':'NRP 2014','B003':'HBB 2015'}
> 
> Basically account numbers and project names, each account number has a
> project name.  I represent it in a dictionary because that seemed the
> best way to keep the account numbers and project names together.  I want
> to save that information to a file, CSV seemed the easiest format
> (though I am open to suggestions if there is a better way!).  I expected
> I could write a function that would create a CSV file that looks like
> this:
> 
> B002,NRP 2014
> B003,HBB 2015
> 
> I thought the DictWriter method of the CSV module should do the trick so
> wrote this:
> 
> def write_fqas(fqa_csv,fqa_dict):
>  with open('fqa_csv','w') as csvfile:
>  writer = csv.DictWriter(csvfile,fieldnames=['FQA','Description']
>  writer.writerows(fqa_dict)
> 
> This didn't yield the results I was looking for, instead it raises
> 
> ValueError: dict contains fields not in fieldnames: 'B', '0', '0', '2'
> 
> It seems to be parsing through the key of the first item in the
> dictionary rather than simply saving it to the CSV file as the first
> field on a line (like I expected).  Obviously there is something about
> how csv.DictWriter works that I don't understand.

DictWriter expects a sequence of dicts where the keys are the column names. 
Example:

>>> import csv
>>> import sys
>>> data = [
... {"FQA": "B002", "Description": "NRP 2014"},
... {"FQA": "B003", "Description": "HBB 2015"},
... ]
>>> writer = csv.DictWriter(sys.stdout, fieldnames=["FQA", "Description"])
>>> writer.writerows(data)
B002,NRP 2014
B003,HBB 2015

As you want to write both keys and values as a column you can pass the dict 
items() to a normal csv.writer:

>>> data = {'B002':'NRP 2014','B003':'HBB 2015'}
>>> writer = csv.writer(sys.stdout)
>>> writer.writerows(data.items())
B002,NRP 2014
B003,HBB 2015

> How rude of me, I neglected to note I am using Python 3.4.3.

And now you're top-posting to make it even worse ;)


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


Re: [Tutor] How to output dictionary data to CSV file :p:

2015-04-28 Thread Thomas C. Hicks



On 04/28/2015 05:30 PM, Peter Otten wrote:

>>>data = {'B002':'NRP 2014','B003':'HBB 2015'}
>>>writer = csv.writer(sys.stdout)
>>>writer.writerows(data.items())

B002,NRP 2014
B003,HBB 2015
That is exactly what I was looking for!  Thanks, apparently my knowledge 
deficit is in understanding dictionary methods.



>How rude of me, I neglected to note I am using Python 3.4.3.

And now you're top-posting to make it even worse;)

Lesson learned!

thomas

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


Re: [Tutor] How to output dictionary data to CSV file

2015-04-28 Thread Alan Gauld

On 28/04/15 09:51, Paradox wrote:


to save that information to a file, CSV seemed the easiest format


You could consider JSON too.
JSON looks a lot like a Python dictionary of strings so is
almost a perfect match to your data. The json module is in
the standard library.


--
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] Pythonic review (descriptors)

2015-04-28 Thread Sage Hack
I'm looking for somebody willing to review parts of this code
https://github.com/SageHack/cloud-buster and let me know what is not
Pythonic :P

I want to improve my Python coding skills but I'm not sure exactly what
to study next.

Right now I'm trying to use descriptors correctly and I'd like to know
if this is about right
https://github.com/SageHack/cloud-buster/tree/master/bust/descriptor

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


Re: [Tutor] Pythonic review (descriptors)

2015-04-28 Thread Alan Gauld

On 28/04/15 10:55, Sage Hack wrote:

I'm looking for somebody willing to review parts of this code
https://github.com/SageHack/cloud-buster and let me know what is not
Pythonic :P


> https://github.com/SageHack/cloud-buster/tree/master/bust/descriptor

The thing that jumps out to me is your use of class variables to hold a 
dictionary of instance responses based on the instance ID. That

pattern looks like this, and you use it in every class:

class SomeClass:
classvar = {}

def __init__(self,id):
   self.id = id
def __get__(self...):
   v = getSomeValue()
   sel.classvar[self.id] = v

Normally you'd store instance specific data in the instance
itself not in a class variable. also you overwrite the
classvariable entry for each instance every time you call
the get(). Is that really what you want?

The other thing is that you should have docstrings for
both the classes and methods.

Finally, and not Python specific, You have several classes
sharing the same 'ID' data - self.domain - that's usually
a bad OOP smell. Only one class should be mastering any
given type of  data, so maybe your other classes are
really methods of whichever is the master class? Particularly
since they don't have any explicit methods (also a bad OOP
smell) of their own.


--
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] Pythonic review (descriptors)

2015-04-28 Thread Alan Gauld

On 28/04/15 10:55, Sage Hack wrote:

I'm looking for somebody willing to review parts of this code
https://github.com/SageHack/cloud-buster and let me know what is not
Pythonic :P



https://github.com/SageHack/cloud-buster/tree/master/bust/descriptor


Another point re the PageTitle class:

class PageTitle(object):

titles = {}

def __init__(self, url, host=None):
self.url = url
self.host = host

def __get__(self, obj=None, objtype=None):...

@property
def id(self):
if self.host:
return self.url+':'+self.host
else:
return self.url


There is not much point in calculating the id each time,
it could simply be set in the init(). You never change
the url or host.


--
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] Naming conventions

2015-04-28 Thread Steven D'Aprano
On Tue, Apr 28, 2015 at 01:01:04PM +0530, Mitesh H. Budhabhatti wrote:
> Hello Friends,
> 
> Can you please suggest good naming conventions/guidelines to following
> while writing Python code?  Thanks.

Most important rule of all: names should be descriptive and 
understandable, not too short or cryptic, not so long that they are 
painful to use. Very common names may be abbreviated. Names should be 
easy to say aloud.

# Good names
length, len, map, format

# Bad names
a, the_thing_we_process, szty

Avoid "funny" or meaningless names:

pizza = 23
homework = 5
print (pizza > homework)


It is acceptable to use standard one-letter variable names in 
generic functions, especially for algebraic (maths) functions and 
short utility functions, e.g.:

i, j, k: integer loop variables
m, n: other integers
x, y: floats
z: complex numbers
s: string or set
d: dict
L: list  (don't use l because it can look like 1)
o: object
u, v: vectors, arrays, sets

are common choices. But don't over-use one-letter names.

Otherwise, names should be self-descriptive:

# Bad
L = get_customers()  # list of customers

# Good
customers = get_customers()

Use plurals for lists, sets or dicts of some data type, and the singular 
for individual data types. E.g.:

names = ['John', 'Mary', 'Fred', 'Sue']
for name in names:
process(name)


Functions and methods should be verbs or verb-phrases in all lowercase, 
for example:

expand() sort() lift() prepare_database() create_factory()

Variables holding data values should be nouns:

   page count header footer server client factory

(Watch out for words which can be both a noun and a verb, like count.)

Classes should be nouns with initial capitals:

Car Engine Animal HTTPServer

and instances should be lowercase:

server = HTTPServer()

The exception is if the class is a "small" primitive or simple type, 
like built-ins int, str, dict, list etc. But even then, you may choose 
to use Initial Capitals instead.

Modules should follow the all-lowercase name. If possible, modules 
should describe what they are about:

math string io unicodedata

but it is also acceptable for modules to have an arbitrary name which 
you just have to learn:

pillow flask zope fabric nose



Does this help?


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


[Tutor] Fwd: circular movement in pygame

2015-04-28 Thread diliup gabadamudalige
-- Forwarded message --
From: diliup gabadamudalige 
Date: Tue, Apr 28, 2015 at 6:22 PM
Subject: circular movement in pygame
To: pygame-us...@seul.org


Looking at the code on this page lines 47 & 48

http://programarcadegames.com/python_examples/show_file.php?file=sprite_circle_movement.py

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

?

I tired it in the code attached and strangely it works ok but only OUTSIDE
THE class. When I implement the exact code in a class it does something
weird.  I can't find where I have gone wrong.

Please help.

Many thanks in advance.

Diliup Gabadamudalige


**
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.
**




-- 
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.
**
import sys, os, pygame, itertools
from math import sin,cos,pi, radians
from pygame.locals import *

os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (50,50) #Set window position

pygame.init()
clock = pygame.time.Clock()
FPS = 1000

SCREENW = 800   #screen width
SCREENH = 740   #screen height

BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
ORANGE = (128, 100, 30)
FONT1= "Cookie-Regular.ttf"

SCREEN = pygame.display.set_mode((SCREENW, SCREENH), 0, 32) #display screen
clock = pygame.time.Clock()

#---
def maketext(msg,fontsize, colour = ORANGE, font = FONT1):
mafont = pygame.font.Font(font, fontsize)
matext = mafont.render(msg, True, colour)
matext = matext.convert_alpha()
return matext

#---
def print_info():
""
textcos = maketext(str(round(obj.rect.x, 2)) + "   " + 
str(round(obj.rect.y, 2)), 30)
SCREEN.blit(textcos, (obj.rect.x, obj.rect.y + 30))

#---
class object_factory(pygame.sprite.Sprite):

def __init__(self, imagelist, xpos = 0, ypos = 0, speedx = 0, speedy = 0, 
value = 0):
"""Constructor"""
pygame.sprite.Sprite.__init__(self)
self.name = ""
self.frame = 0
self.imagelist = imagelist
self.image = imagelist[self.frame]
self.mask = pygame.mask.from_surface(self.image) # pixelmask
self.rect = self.image.get_rect()
self.rect.x = xpos
self.rect.y = ypos
self.speedx = speedx
self.speedy = speedy
self.timer = 0
self.timerlimit = 10

#--
def move(self):  # wallsprites, Herosprite, looptime
self.rect.x += self.speedx
self.rect.y += self.speedy

#--
def update(self):
""
self.image = self.imagelist[self.frame]
if self.timer >= self.timerlimit:
self.frame += 1
if self.frame >= len(self.imagelist):
self.frame = 0
self.timer = 0
self.timer += 1

plat = pygame.image.load("plt0.png").convert_alpha()
star = pygame.image.load("gemp0.png").convert_alpha()
box = pygame.image.load("crateB.png").convert_alpha()

platforms = pygame.sprite.Group()
boxes = pygame.sprite.Group()
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman

Re: [Tutor] Fwd: circular movement in pygame

2015-04-28 Thread Alan Gauld

On 28/04/15 16:38, diliup gabadamudalige wrote:

-- Forwarded message --
From: diliup gabadamudalige 
Date: Tue, Apr 28, 2015 at 6:22 PM
Subject: circular movement in pygame
To: pygame-us...@seul.org


It's good that you tried the python-game list for a
pygame question. But if pygame-users can't give a
definitive answer then its even less likely that the
tutor list will. Although you might need to allow
a full 24 hours to get answers, email is not an
instant delivery mechanism.


Looking at the code on this page lines 47 & 48

http://programarcadegames.com/python_examples/show_file.php?file=sprite_circle_movement.py


I didn't look at the code in that tutorial, but...


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


Yes, that's just normal Python syntax. It adds/multiplies
the current value of self.rect with "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


But its unlikely to have the same effect as this since the
above two lines are calculating a new value based on radius,
angle, and centre rather than one based on the current
values of self.rect


I tired it in the code attached and strangely it works ok but only OUTSIDE
THE class. When I implement the exact code in a class it does something
weird.  I can't find where I have gone wrong.


I can't see your code but are you sure you are using self in
all the appropriate places in your class based code?


--
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-28 Thread Oscar Benjamin
On 28 April 2015 at 16:38, diliup gabadamudalige  wrote:
>
> Looking at the code on this page lines 47 & 48
>
> http://programarcadegames.com/python_examples/show_file.php?file=sprite_circle_movement.py
>
> 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

There's no way to do that. The second version ignores the previous
value of self.rect.x/y.

I'm going to guess that the angle has only changed by a small amount
delta_angle between iterations in which case there would be a way to
do it approximately.

The real question is just why though? The second version is correct
and will be correct for ever. The first version would only be
approximately correct and over time you'd probably find that the
position would drift so that the ball was effectively at a different
radius.

In any case if
 x = r * sin(theta)
then
dx/dt = r * cos(theta) * dtheta/dt.
Since
y = r * cos(theta) that's
dy/dt = x * dtheta/dt.
So you could update y approximately with:
y += x * dtheta/dt * deltat
where deltat is your timestep. In your code that would be:
self.rect.x += self.rect.y * self.speed
self.rect.y -= self.rect.x * self.speed

Really what you have now is better though.
___
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-28 Thread Oscar Benjamin
On 28 April 2015 at 19:37, diliup gabadamudalige  wrote:
>
> I thank all those who responded to my question
>
> Here is the code that I had written.
>
> When updating is applied to a surface object the rotation works but when it
> is applied through a class to an object it goes wrong in about 3 rotations.
> As far as I can see the code is the same. What is wrong? If you can correct
> some code and show me would help.

Your code is too long and complicated for me to read through it all.
You should simplify your problem before posting it somewhere like
this. Make a simpler program that does something similar but without
all the pygame stuff. For example your program might just loop through
printing out the positions of the object at different times e.g.:

# game.py
#
# This program simulates a ball moving at constant speed
# in a two dimensional space.
#

# Initial position of ball
xpos = 0
ypos = 0

# Horizontal and vertical speed
xspeed = 1
yspeed = 2

# Timestep
deltat = 0.125

# Run through 10 iterations of simulation
for n in range(10):
# Update state
xpos += xspeed * deltat
ypos += yspeed * deltat

# Output current state
print('Position = (%.3f, %.3f)' % (xpos, ypos))

$ python game.py  # Show the output
Position = (0.125, 0.250)
Position = (0.250, 0.500)
Position = (0.375, 0.750)
Position = (0.500, 1.000)
Position = (0.625, 1.250)
Position = (0.750, 1.500)
Position = (0.875, 1.750)
Position = (1.000, 2.000)
Position = (1.125, 2.250)
Position = (1.250, 2.500)

Once you have made a simpler program carefully explain what it is that
you want it to do and show us how what it does is different. Don't
expect people on this list to download your code and run it.

Also please put your code in the email and not in an attachment and
please reply back to the tutor list rather than directly to me.


--
Oscar
___
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-28 Thread diliup gabadamudalige
I thank all those who responded to my question

Here is the code that I had written.

When updating is applied to a surface object the rotation works but when it
is applied through a class to an object it goes wrong in about 3 rotations.
As far as I can see the code is the same. What is wrong? If you can correct
some code and show me would help.

On Tue, Apr 28, 2015 at 11:58 PM, Oscar Benjamin  wrote:

> On 28 April 2015 at 16:38, diliup gabadamudalige 
> wrote:
> >
> > Looking at the code on this page lines 47 & 48
> >
> >
> http://programarcadegames.com/python_examples/show_file.php?file=sprite_circle_movement.py
> >
> > 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
>
> There's no way to do that. The second version ignores the previous
> value of self.rect.x/y.
>
> I'm going to guess that the angle has only changed by a small amount
> delta_angle between iterations in which case there would be a way to
> do it approximately.
>
> The real question is just why though? The second version is correct
> and will be correct for ever. The first version would only be
> approximately correct and over time you'd probably find that the
> position would drift so that the ball was effectively at a different
> radius.
>
> In any case if
>  x = r * sin(theta)
> then
> dx/dt = r * cos(theta) * dtheta/dt.
> Since
> y = r * cos(theta) that's
> dy/dt = x * dtheta/dt.
> So you could update y approximately with:
> y += x * dtheta/dt * deltat
> where deltat is your timestep. In your code that would be:
> self.rect.x += self.rect.y * self.speed
> self.rect.y -= self.rect.x * self.speed
>
> Really what you have now is better though.
> ___
> 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.
**
import sys, os, pygame, itertools
from math import sin,cos,pi, radians
from pygame.locals import *

os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (50,50) #Set window position

pygame.init()
clock = pygame.time.Clock()
FPS = 1000

SCREENW = 800   #screen width
SCREENH = 740   #screen height

BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
ORANGE = (128, 100, 30)
FONT1= "Cookie-Regular.ttf"

SCREEN = pygame.display.set_mode((SCREENW, SCREENH), 0, 32) #display screen
clock = pygame.time.Clock()

#---
def maketext(msg,fontsize, colour = ORANGE, font = FONT1):
mafont = pygame.font.Font(font, fontsize)
matext = mafont.render(msg, True, colour)
matext = matext.convert_alpha()
return matext

#---
def print_info():
""
textcos = maketext(str(round(obj.rect.x, 2)) + "   " + 
str(round(obj.rect.y, 2)), 30)
SCREEN.blit(textcos, (obj.rect.x, obj.rect.y + 30))

#---
class object_factory(pygame.sprite.Sprite):

def __init__(self, imagelist, xpos, ypos, speedx = 0, speedy = 0, value = 
0):
"""Constructor"""
pygame.sprite.Sprite.__init__(self)
self.name = ""
self.frame = 0
self.imagelist = imagelist
self.image = imagelist[self.frame]
self.mask = pygame.mask.from_surface(self.image) # pixelmask
self.rect = self.image.get_rect()
self.rect.x = xpos
self.rect.y = ypos
#self.speedx = speedx
#self.speedy = speedy
self.timer = 0
self.timerlimit = 10

#--
#def move(self):  # wallsprites, Herosprite, looptime
#self.rect.x += self.speedx
#self.rect.y += self.speedy

#--
def update(self):
""
self.image = self.imagelist[self.frame]
if self.timer >= self.timerlimit:
s

Re: [Tutor] How to output dictionary data to CSV file :p:

2015-04-28 Thread Thomas C. Hicks


On 04/28/2015 09:43 PM, Alan Gauld wrote:

You could consider JSON too.
JSON looks a lot like a Python dictionary of strings so is
almost a perfect match to your data.


Sounds great, I'll check it out.  Thanks!

thomas
==
Thomas C. Hicks, MD, MPH
Training Manager, Gansu Gateway
Lanzhou, Gansu, PR China
___
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-28 Thread Dave Angel

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

I thank all those who responded to my question

Here is the code that I had written.

When updating is applied to a surface object the rotation works but when it
is applied through a class to an object it goes wrong in about 3 rotations.
As far as I can see the code is the same. What is wrong? If you can correct
some code and show me would help.



By top-posting, you're messing up the readability of your response.  And 
by trying to use an attachment, you're messing up a large portion of the 
people reading this thread.


Post a simplified example, inline in your message, and *following* any 
quote you're using.


If your symptom is that the data diverges eventually from the intended 
trajectory, the problem is that you're accumulating errors.  Each point 
you do you're rounding the calculation by storing it in finite 
precision.  After enough roundoffs, the error becomes visible.


If you need to reliably move an object in a circle, you'll want to store 
the location in angular terms, center, radius, and angle.


Then each time around the loop, increment the angle by a non-rounded 
amount, and recalculate the x/y coordinates.



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


[Tutor] Good Taste Question: Using SQLite3 in Python

2015-04-28 Thread Jugurtha Hadjar

Hello, all..

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_balance)
)
conn.commit()
except Exception as e:
return self.ERROR.format(e.args[0])




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


[Tutor] Function works one time then subsequently fails

2015-04-28 Thread Jim Mooney Py3winXP
This is really puzzling me. I'm parsing a string to do some simple math
operations and practice tossing functions around. My parser works on the
first run, then it continually fails on the same input.

"""
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,
  '-': minus, 'minus': minus, 'multiply': multiply, '*':
multiply,
  'times': multiply, 'divide': divide, '/': divide,
  'divided': divide}

numbers = []

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()
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
>>> result = parse_string('1 minus 15')
>>> print(result)
None
>>>


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


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

2015-04-28 Thread Cameron Simpson

On 28Apr2015 20:58, Jim Mooney Py3winXP  wrote:

This is really puzzling me. I'm parsing a string to do some simple math
operations and practice tossing functions around. My parser works on the
first run, then it continually fails on the same input.


[...]

numbers = []

[...]

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

[...]

At a first glance numbers is a global. It is reset to [] at program start, but 
never again. So you're appending to it forever. I have not investigated further 
as to how that affects your program's flow.


Cheers,
Cameron Simpson 

There are two ways of dealing with this problem: one is complicated and
messy, and the other is simple and very elegant. We don't have much time
left, so I'll just show you the complicated and messy way.
- Richard Feynman, 1981
___
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-28 Thread Jim Mooney Py3winXP
On 28 April 2015 at 21:27, Cameron Simpson  wrote:

> At a first glance numbers is a global. It is reset to [] at program start,
> but never again. So you're appending to it forever. I have not investigated
> further as to how that affects your program's flow.
>
> Cheers,
> Cameron Simpson 
>

Took you less time to find that than me. I, of course, realized I forgot to
empty the number list on each time through the parse loop, After I posted
;')  Seems to work okay otherwise, although criticism of Pythonicity is
welcome. I just wanted to practice tossing functions around. I'll put it
into a user input loop and work it. It won't catch everything. I have to
study regexes for that.

At this point I'm starting to lose track and have to think of better ways
to organize so I recall and understand what I'm doing. I know there are
general tuts on that but that's just reading. Is there a python-specific
tut on it where I could follow actual code along with the interpreter to
reinforce things? Or, what is the official word for
organize-so-you-don't-forget-or-get-confused so I can search google with it?

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


Re: [Tutor] Naming conventions

2015-04-28 Thread Mitesh H. Budhabhatti
Thank you so much Mark, Steven.  This will definitely help.  I really
appreciate.


On Tue, Apr 28, 2015 at 8:45 PM, Steven D'Aprano 
wrote:

> On Tue, Apr 28, 2015 at 01:01:04PM +0530, Mitesh H. Budhabhatti wrote:
> > Hello Friends,
> >
> > Can you please suggest good naming conventions/guidelines to following
> > while writing Python code?  Thanks.
>
> Most important rule of all: names should be descriptive and
> understandable, not too short or cryptic, not so long that they are
> painful to use. Very common names may be abbreviated. Names should be
> easy to say aloud.
>
> # Good names
> length, len, map, format
>
> # Bad names
> a, the_thing_we_process, szty
>
> Avoid "funny" or meaningless names:
>
> pizza = 23
> homework = 5
> print (pizza > homework)
>
>
> It is acceptable to use standard one-letter variable names in
> generic functions, especially for algebraic (maths) functions and
> short utility functions, e.g.:
>
> i, j, k: integer loop variables
> m, n: other integers
> x, y: floats
> z: complex numbers
> s: string or set
> d: dict
> L: list  (don't use l because it can look like 1)
> o: object
> u, v: vectors, arrays, sets
>
> are common choices. But don't over-use one-letter names.
>
> Otherwise, names should be self-descriptive:
>
> # Bad
> L = get_customers()  # list of customers
>
> # Good
> customers = get_customers()
>
> Use plurals for lists, sets or dicts of some data type, and the singular
> for individual data types. E.g.:
>
> names = ['John', 'Mary', 'Fred', 'Sue']
> for name in names:
> process(name)
>
>
> Functions and methods should be verbs or verb-phrases in all lowercase,
> for example:
>
> expand() sort() lift() prepare_database() create_factory()
>
> Variables holding data values should be nouns:
>
>page count header footer server client factory
>
> (Watch out for words which can be both a noun and a verb, like count.)
>
> Classes should be nouns with initial capitals:
>
> Car Engine Animal HTTPServer
>
> and instances should be lowercase:
>
> server = HTTPServer()
>
> The exception is if the class is a "small" primitive or simple type,
> like built-ins int, str, dict, list etc. But even then, you may choose
> to use Initial Capitals instead.
>
> Modules should follow the all-lowercase name. If possible, modules
> should describe what they are about:
>
> math string io unicodedata
>
> but it is also acceptable for modules to have an arbitrary name which
> you just have to learn:
>
> pillow flask zope fabric nose
>
>
>
> Does this 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] Function works one time then subsequently fails

2015-04-28 Thread Cameron Simpson

On 28Apr2015 22:27, Jim Mooney Py3winXP  wrote:

On 28 April 2015 at 21:27, Cameron Simpson  wrote:

At a first glance numbers is a global. It is reset to [] at program start,
but never again. So you're appending to it forever. I have not investigated
further as to how that affects your program's flow.


Took you less time to find that than me. I, of course, realized I forgot to
empty the number list on each time through the parse loop, After I posted
;')  Seems to work okay otherwise, although criticism of Pythonicity is
welcome. I just wanted to practice tossing functions around. I'll put it
into a user input loop and work it. It won't catch everything. I have to
study regexes for that.


Basicly, you should almost never have a global variable. There is a host of 
special circumstances where globals solve some specific problems. But by and 
large, don't do it without a very concrete reason.


If numbers had been local to the parse function you would never have been 
bitten by this. There's no need for it to be global; you can return the 
operator and the operands (numbers) easily from the parse function.



At this point I'm starting to lose track and have to think of better ways
to organize so I recall and understand what I'm doing. I know there are
general tuts on that but that's just reading. Is there a python-specific
tut on it where I could follow actual code along with the interpreter to
reinforce things? Or, what is the official word for
organize-so-you-don't-forget-or-get-confused so I can search google with it?


"functional decomposition"?

One rule of thumb is that functions should be short. That way you can generally 
keep their purpose and internal oparations in your head in one go, and the 
whole thing also fits on your screen.


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 

If this experiment we're doing works, then I will follow up and push it as
hard as possible. And if it doesn't work, I will write a science-fiction
novel where it does work. It's a win-win situation.
- John Cramer on his experiment for possible cuasality violation
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor