Re: [Tutor] Variables (with lists??)

2011-11-22 Thread delegbede
Hi Chris,

Straight to the point, this is how to populate a python dictionary. 

customer = {}

This statement makes a new dictionary, which is empty though, called customer. 
A python dictionary has a pair of key and value linked with semicolon and 
seperated from other pairs by a comma. 

 
print “Add a new customer to the database\n”

custNum = raw_input(‘Enter a customer number: ‘) 

This expects an input from the user and then sets that to the variable 
custName. 
Here is a thing to note here, whatever the user enters is treated as a string 
because of raw_input. That's another lesson as a whole. 
What's in the parenthesis would be shown at the prompt when the program is run. 
It tells the user what to do. 

customer['firstName'] = raw_input(‘Customer First Name: ‘)

This creates a pair of key value in a dictionary. Initially, the dictionary 
customer was empty. This statement now creates a key 'firstname' that has the 
value of whatever is entered by the user as the Customer First Name. 

customer['lastName'] = raw_input(‘Customer Last Name: ‘)

The same explanation for the above explains this and the rest all through the

customer['zip'] = raw_input(‘Customer Zip Code: ‘)

You can also look at what others would say. 

While searching google, search, creating python dictionary. 

HTH. 

Regards. 
Sent from my BlackBerry wireless device from MTN

-Original Message-
From: Chris Kavanagh 
Sender: tutor-bounces+delegbede=dudupay@python.org
Date: Tue, 22 Nov 2011 23:15:49 
To: 
Subject: [Tutor] Variables (with lists??)

I was going over one of Derek Banas' tutorials on youtube, and came 
across something I hadn't seen before. A variable with a list beside it 
(see code below). He sets the variable, customer , equal to a dict. Then 
uses the variable with ['firstname'],['lastname'], ect. I've never seen 
this in my short programming life. What is this called? And is there any 
documentation on it?? I tried to google it, but had no idea what to 
google, lol. The code below is just partial code. . .

Thanks for the help, and I hope everyone has a happy Thanksgiving!




customer = {}

print “Add a new customer to the database\n”

custNum = raw_input(‘Enter a customer number: ‘)
customer['firstName'] = raw_input(‘Customer First Name: ‘)
customer['lastName'] = raw_input(‘Customer Last Name: ‘)
customer['streetAdd'] = raw_input(‘Customer Street Address: ‘)
customer['city'] = raw_input(‘Customer City: ‘)
customer['state'] = raw_input(‘Customer State: ‘)
customer['zip'] = raw_input(‘Customer Zip Code: ‘)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Variables (with lists??)

2011-11-22 Thread Andreas Perstinger

On 2011-11-23 05:15, Chris Kavanagh wrote:

I was going over one of Derek Banas' tutorials on youtube, and came
across something I hadn't seen before. A variable with a list beside it
(see code below). He sets the variable, customer , equal to a dict. Then
uses the variable with ['firstname'],['lastname'], ect. I've never seen
this in my short programming life. What is this called?


That's the Python syntax to indexing dictionary keys (comparable to the 
index of lists, tuples, ...)


In general, you set a value with

dictionary[key] = value

where "key" can be any immutable type (strings, numbers, tuples if they 
just contain strings, numbers and other tuples) and "value" anything you 
want to save for that key.


To get the value of a key, just use

dictionary[key]

Example:
>>> customer = {}
>>> customer["name"] = "Chris"
>>> customer["name"]
'Chris'


And is there any documentation on it??


The tutorial on dictionaries:
http://docs.python.org/tutorial/datastructures.html#dictionaries

The library reference on dictionaries:
http://docs.python.org/library/stdtypes.html#mapping-types-dict

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


[Tutor] Variables (with lists??)

2011-11-22 Thread Chris Kavanagh
I was going over one of Derek Banas' tutorials on youtube, and came 
across something I hadn't seen before. A variable with a list beside it 
(see code below). He sets the variable, customer , equal to a dict. Then 
uses the variable with ['firstname'],['lastname'], ect. I've never seen 
this in my short programming life. What is this called? And is there any 
documentation on it?? I tried to google it, but had no idea what to 
google, lol. The code below is just partial code. . .


Thanks for the help, and I hope everyone has a happy Thanksgiving!




customer = {}

print “Add a new customer to the database\n”

custNum = raw_input(‘Enter a customer number: ‘)
customer['firstName'] = raw_input(‘Customer First Name: ‘)
customer['lastName'] = raw_input(‘Customer Last Name: ‘)
customer['streetAdd'] = raw_input(‘Customer Street Address: ‘)
customer['city'] = raw_input(‘Customer City: ‘)
customer['state'] = raw_input(‘Customer State: ‘)
customer['zip'] = raw_input(‘Customer Zip Code: ‘)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Shortening the code

2011-11-22 Thread Asokan Pichai
On Wed, Nov 23, 2011 at 2:47 AM, Mic  wrote:
>
[LOTS OF STUFF SNIPPED]
>>> self.chair1.configure(bg="green")
>>> os.remove ("Hamburg_Dortmund20_00")
>
>> And now you delete that file you created without having
>> done anything with it?
>
> The meaning is that when the button is pressed once,  it changes color and
> creates the file. That means you have
> booked the chair. If you click the button once more, the button removes the
> file, and changes color to green
> which indicates that you have un booked your chair. I hope you understand
> now why I delete the file :)

Often if you  [name things]/[write code] in terms of WHAT you want to do, rather
than HOW you want to do, you will find the going easier

For example, a function that is named *bookChair(chairId)*, inside which
you change color to green or whatever is worth considering.

HTH

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


Re: [Tutor] Physics Engine

2011-11-22 Thread eire1130
I think python- ogre has a physics engine? Its 3d though

Sent from my Verizon Wireless BlackBerry

-Original Message-
From: Christopher King 
Sender: tutor-bounces+eire1130=gmail@python.org
Date: Tue, 22 Nov 2011 19:22:27 
To: python mail list
Subject: [Tutor] Physics Engine

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


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


[Tutor] Physics Engine

2011-11-22 Thread Christopher King
Does anyone know a good physics engine that works with livewires, or a
good reference on how to build 2-D physic engines (preferably the former.)
It needs to work well with rope objects.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Quacks like an object

2011-11-22 Thread Christopher King
>
> You want to persist data changes to a file? Thats easy enough.

Yes, but I want it built in to the objects built in methods like for
example doing
*listquacker[3]="This string needs to be updated immediately**."*
Should write the new data to a file. It should also work for all data
types, not just list.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] File vs. Database (possible off topic)

2011-11-22 Thread Ken G.

On 11/22/2011 08:13 AM, Steven D'Aprano wrote:

Ken G. wrote:
It occurred to me last week while reviewing the files I made in using 
Python, it could be somewhat similar to a database.


What would be a different between a Python files and Python 
databases?  Granted, the access in creating them are different, I 
really don't see any different in the format of a file and a database.


A database is essentially a powerful managed service built on top of 
one or more files. There's nothing you can do with a database that you 
can't do with a big set of (say) Windows-style INI files and a whole 
lot of code to manage them. A database does all the management for 
you, handling all the complexity, data integrity, and security, so 
that you don't have to re-invent the wheel. Since database software 
tends to be big and complicated, there is a lot of wheel to be 
re-invented.


I wish to thank those whom replied to my previous question regarding 
database vs. file.  The responses received was quite useful and helpful.


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


Re: [Tutor] Shortening the code

2011-11-22 Thread Mic



OK, So I'll guess you want a desktop program that eventually sends
commands to an online service?
If so thats a lot easier to do with Tkinter... :-)


Well, it is enough if the program can run on my desktop. However, there are
courses about learning how to make programs like these online, but I feel
like that is too hard for me at the moment, right? :)



text_file=open("Hamburg_Dortmund20_00","w")
text_file.write("Hamburg-Dortmund")
text_file.close()



Hmmm, that looks suspicious. You just created a text file with

one line.

I thought I should make it as simple as possible when posting here?
If you would have liked me to I can paste all the information I store
in the file, but it would have been a lot of lines then, which would had
been unnecessary?


def chair_color_red():
global chair1_color
chair1_color=("yellow")
change_button2_color_red()



The function says red but the code says 'yellow'


My bad. It is supposed the be red there.




self.chair1.configure(bg="green")
os.remove ("Hamburg_Dortmund20_00")



And now you delete that file you created without having
done anything with it?


The meaning is that when the button is pressed once,  it changes color and 
creates the file. That means you have
booked the chair. If you click the button once more, the button removes the 
file, and changes color to green
which indicates that you have un booked your chair. I hope you understand 
now why I delete the file :)




(*)Instead of a dictionary we could have used a class
but I think that's a leap too far for you just yet. But
this is a project that would be easier using classes
and objects. An exercise for the future.

I have made simple programs with classes before. I know how to use these
instance variables (correct name in english?) and how to create objects of 
the class,

but nothing more.


I suspect this is all a bit much in one go, if so, we can

break it down into more manageable chunks.

Yes, it feels like a lot to take in at once, but tomorrow I will try your 
suggestions
for a couple of hours and hopefully get it to work. If I fail at that, 
perhaps we could

"break it down into more manageable chunks".

Thanks for your help once again!


Mic 


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


Re: [Tutor] Shorten Code

2011-11-22 Thread Alan Gauld

On 22/11/11 19:41, Mic wrote:


A Tkinter program is never going to be an online GUI, it only works on
the desktop. For that you need to use HTML5/Flash/Javascript/Java etc.
And its all a lot more messy.


No, I didn't mean that it have to work online. It is just fine if it
works on the desktop.


OK, So I'll guess you want a desktop program that eventually sends 
commands to an online service?

If so thats a lot easier to do with Tkinter... :-)



def chair1_clicked(self):
"""This method runs if chair one is clicked"""


First thing to do is take the variable out of the function name and pass 
it as a parameter.


def chair_clicked(self, chairID):

Now you can call that and pass in the actual chair that was
clicked as a parameter. (I'm going to assume you went for a list of 
chairs so the actual value of aChair is the index in the list)



def change_chair1_value():
global chair1_value
button2_value=not chair1_value


You really want to stop using global values.
Make them attributes of your class. Life will be much easier!
And you won;t need all these little functions cluttering up
your code.


if chair_value:


Becomes

if self.chairs[chairID][0]

This assumes you store the value and button as a tuple and value
is the first element. So when you create the chairs your code looks like:

for ch in ch_data:
chairs.append((ch_data[0], Button(self, text=ch_data[1],) )


self.chair1.configure(bg="yellow")


You are still hard coding the color rather than using your variables


text_file=open("Hamburg_Dortmund20_00","w")
text_file.write("Hamburg-Dortmund")
text_file.close()


Hmmm, that looks suspicious. You just created a text file with
one line.


def chair_color_red():
global chair1_color
chair1_color=("yellow")
change_button2_color_red()


The function says red but the code says 'yellow'

Again take the value out of the function name and make it
a parameter.

def set_chair_color(chairID, col):
 chairs[chairID][1] = col

And now I'm assuming the second value of chairs is the color. Its 
getting complicated. Maybe time we introduced dictionaries(*)

Then it looks like:

def set_chair_color(chairID, col):
 chairs[chairID]['color'] = col

and your initialisation code looks like:

for id,ch in enumerate(ch_data):
chairs[id] = {'value':0, 'color':'white',
  'button' = Button(self, text=ch_data[0],) )


self.chair1.configure(bg="green")
os.remove ("Hamburg_Dortmund20_00")


And now you delete that file you created without having
done anything with it?

I suspect this is all a bit much in one go, if so, we can
break it down into more manageable chunks.


(*)Instead of a dictionary we could have used a class
but I think that's a leap too far for you just yet. But
this is a project that would be easier using classes
and objects. An exercise for the future.

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

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


Re: [Tutor] Shorten Code

2011-11-22 Thread Mic

Button1 is supposed to represent chair one in the train.



So call it chair_1 or put it in a list called chairs
so that you can access them as chairs[0] or whatever.
But get a name that reflects what its actually used for.


Yes, perhaps that is a good way to go. I didn't think about that.



at the top of my email, I am writing a larger program. This program is
supposed to be a GUI  online booking program for train tickets.



OK, That's a pity.
A Tkinter program is never going to be an online GUI, it only works on
the desktop. For that you need to use HTML5/Flash/Javascript/Java etc.
And its all a lot more messy.


-
No, I didn't mean that it have to work online. It is just fine if it works 
on the desktop.
I can only imagine how much more complicated things would be then. But if I 
understood it correctly,
with the help and information I got from you in this mail and in your 
previous mail, I can manage to
solve my problems? It is a bit hard right now to understand, because I am 
unfamiliar with using tuples/lists

and data tables. I will do my best to get it to work.




However, I understand if you don't have time to answer these probably
stupid and simple questions, I am still  grateful for your previous 
answers!



They are neither simple nor stupid, they are very sensible questions and
you are tackling a significant program. Sadly I don't think your
approach will work for an 0nline solution (ie a web based one).


I just got my program to work today, but I want to shorten the code
using your suggestions in this and your previous email. I still find this 
hard
to do because that way of thinking is completely new to me. I have one of 
these functions
below for each chair. I just want to use one instead of so many functions. 
That is why I am trying to understand and

implement your suggestions.

def chair1_clicked(self):
  """This method runs if chair one is clicked"""

  def change_chair1_value():
  global chair1_value
  button2_value=not chair1_value

  chair1_clicked ()

  if chair_value:

  self.chair1.configure(bg="yellow")
  text_file=open("Hamburg_Dortmund20_00","w")
  text_file.write("Hamburg-Dortmund")
  text_file.close()



  def chair_color_red():
  global chair1_color
  chair1_color=("yellow")
  change_button2_color_red()




  else:
  self.chair1.configure(bg="green")
  os.remove ("Hamburg_Dortmund20_00")




  def chair1_color_green():
  global chair1_color
  chair_color=("green")
  chair1_color_green()






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


[Tutor] basic class loading question

2011-11-22 Thread Cranky Frankie
Dave thank you for your patience. It really is appreciated.

In the interest of closing this thread I'm posting the final version
that works, and achieves the goal of showing how to represent data
both in a list and in an object:

#
# Example to show the difference between list data and object data
#
class Qb:
def __init__(self, first_name='', last_name='', phone='',
email='', stadium=''):
self.first_name = first_name
self.last_name = last_name
self.phone = phone
self.email = email
self.stadium = stadium

Qb_list = [["Joe", "Montana", "415-123-4567",
"joe.mont...@gmail.com","Candlestick Park"],
["Fran", "Tarkington","651-321-7657",
"frank.tarking...@gmail.com", "Metropolitan Stadidum"],
["Joe", "Namath", "212-222-", "joe.nam...@gmail.com", "Shea Stadium"],
["John", "Elway", "303-9876-333", "john.el...@gmai.com", "Mile
High Stadium"],
["Archie", "Manning", "504-888-1234", "archie.mann...@gmail.com",
"Louisiana Superdome"],
["Roger", "Staubach", "214-765-8989", "roger.staub...@gmail.com",
"Cowboy Stadium"]]

quarterbacks = []   # Create an empty object list

len_Qb_list = len(Qb_list)  # Get the lenght of the list of
lists which is the
#number of rows in the input data

for i in range(0, len_Qb_list): # Iterate for the number of rows

nq = Qb(*Qb_list[i])# Create an instance of class Qb called "nq"
#and populate each field
quarterbacks.append(nq) # Append an instance of object
"nq" into object list "quarterbacks"
i = i + 1   # Iterate for each row in "Qb_list"

print (quarterbacks[3].phone)   # Print an item from the object
list "quarterbacks"
print (Qb_list[3][2])   # Print the same object from the
original list of lists




-- 
Frank L. "Cranky Frankie" Palmeri
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] write list of tuples to file (beginner)

2011-11-22 Thread Alan Gauld

On 22/11/11 18:50, Mayo Adams wrote:


for item in tuplelist
outputfile.write (item)

doesn't work, and I suppose I scarcely expect it should, but I am at a
loss to find out how to do it.


You need to convert the tuple to a string.
And you need to add a newline at the end.

A simple way is:

 for item in tuplelist
 outputfile.write (str(item) + '\n')

But the formatting may not be exactly as you'd like.
In that case write your own string convertor, call
it tuple2string or something and use it like

for item in tuplelist
outputfile.write (tuple2string(item) )


Of course, if you ever want to read the data back
you'll need a corresponding string2tuple() function
that unpicks your formatting back to a tuple...

HTH,

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

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


[Tutor] calling modules in different minor versions of Python

2011-11-22 Thread Gregory, Matthew
Hi all,

We work with a python package (ESRI geoprocessor) that only releases their 
packages tied to specific minor version of Python (e.g. 2.5).  We are 
predominantly working with 2.6, but have Python 2.5 installed as well.

When we want to call modules that use the geoprocessor package, we are using 
subprocess.call from 2.6:

  subprocess.call('C:/Python25/Python spam.py ')

where spam.py is a module that uses the geoprocessor and  are the 
arguments to pass.  Apart from moving our code base to 2.5, is there a better 
way to handle this that doesn't require a separate subprocess call?

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


Re: [Tutor] basic class loading question

2011-11-22 Thread Alan Gauld

On 22/11/11 17:09, Cranky Frankie wrote:


Dave I'm sorry but I just don't get this. I have virtually no
experience  with classes.


You need to step back and rethink the terminology a bit.
A class is a cookie cutter for creating objects.
Objects are instances of the class.


What seems like it should work is this:

###
len_Qb_list = len(Qb_list)

for i in range(0, len_Qb_list):
 quarterbacks = Qb(*Qb_list[i])
 i = i + 1


This repeatedly creates an instance of Qb and assigns it to the variable 
quarterbacks. quarterbacks always holds the last

instance to be created, the previous instance is destroyed.

You want to create a list (not an instance of Qb but an
ordinary list) which will hold these quarterback objects
you are creating.


print (quarterbacks[2].last_name)


This tries to print the second something of quarterbacks. But since 
quarterbacks is a single object it fails.


So you need sometjing like this

quarterbacks = []  # an empty list

# get each list entry in turn
for data in Qb_list:
# create an object and add to the list of quarterbacks
quarterbacks.append(Qb(*data))

And now

print quarterbacks[2].last_name

makes sense. It will print the last name of the 3rd entry.


In other words, define an instance of the Qb class called
quarterbacks, and then "load" or instantiate instances of the class
using the 6 sets of values from Qb_list.


An instance of Qb is just a quarterback object. You can't load it with 
instances of anything.


You might find it useful to read the OOP topic in my tutorial for a 
different explanation of OOP...


HTH

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

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


Re: [Tutor] write list of tuples to file (beginner)

2011-11-22 Thread Hugo Arts
On Tue, Nov 22, 2011 at 7:50 PM, Mayo Adams  wrote:
> I have a list of tuples of the form (string,integer) that I would like to
> write  to  a file with a line break between each. Simply writing to a file
> object thus
>
> for item in tuplelist
>    outputfile.write (item)
>
> doesn't work, and I suppose I scarcely expect it should, but I am at a loss
> to find out how to do it.
>

Pro tip: When you seek programming help, never, ever write "it doesn't
work." For us, it is the least helpful problem description ever.
Instead, you should describe to us two things:

1) what you expected to happen
2) what happened instead

under 2, make sure you include any possible error messages you got.
For example, when I tried to write a tuple to a file, I got this:

Traceback (most recent call last):
  File "", line 1, in 
f.write((1, 2))
TypeError: expected a character buffer object

Well, hello, a TypeError! Now we have some idea of what's going on. A
TypeError means that a function argument you supplied is of an
incorrect type. And well, that makes sense, since the write function
expects a "character buffer object" (in most cases, that'll be a
string), and we supplied a tuple.

So how do we solve this? Well, the easiest way is to convert our tuple
into a string:

f.write(str(item))

that'll write your item to the file formatted like a tuple, i.e.
enclosed in parentheses and with a comma separating the items. We
could also write it in a different way, like only separated by a
space:

f.write("%s %s" % item)

This uses the string formatting operator % (you might want to read up
on it). You can choose tons of different formats using this same
formatting technique, pick what you like. You can even mimic what we
did with the str() function up above:

f.write("(%s, %s)" % item)

though that's a bit redundant, of course. But the important point is
that the file is just text, so you can format the data you write to it
however you like, as long as you write it as text. If you want to
write actual python objects rather than text representations of them,
you should look at the pickle module.

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


Re: [Tutor] Shortening code.

2011-11-22 Thread Alan Gauld

On 22/11/11 15:11, Mic wrote:


> Also, do you really need the colors, you don't actually use them for
> anything below except the initial color, but you might as well just hard



Button1 is supposed to represent chair one in the train.


So call it chair_1 or put it in a list called chairs
so that you can access them as chairs[0] or whatever.
But get a name that reflects what its actually used for.

> When you click at the button, which represents a chair,

it is supposed to change color to show that the chair now is booked. If
you press it one more time, it is supposed to
change color to show that the chair is free to book.


Thats all fine but you are not doing that, so the variable
is currently pointless. Either change the code to use the variable or 
delete the variable which is simply wasting space and time and making 
the code less readable.



-
I understand why you think I don't need to change the global value,
since I am already changing the color with this line.
self.hello_bttn1.configure(bg="green", text="Hi_1")

The thing is that this window I have created is just a window in another
window. I want the color to be the same that it was before I closed the
window.
Otherwise the color would be green when I open the window again, despite
closing the window when the button was red. I hope you understand what I
mean by this?


Yes, but the point is that you are not using the variable just now. So 
use it even if its not part of your master plan just yet. Or, if the 
code is only to demonstrate a point leave it out completely




at the top of my email, I am writing a larger program. This program is

> supposed to be a GUI  online booking program for train tickets.

OK, That's a pity.
A Tkinter program is never going to be an online GUI, it only works on 
the desktop. For that you need to use HTML5/Flash/Javascript/Java etc.

And its all a lot more messy.


However, I understand if you don't have time to answer these probably
stupid and simple questions, I am still  grateful for your previous answers!


They are neither simple nor stupid, they are very sensible questions and 
you are tackling a significant program. Sadly I don't think your 
approach will work for an 0nline solution (ie a web based one).


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

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


[Tutor] write list of tuples to file (beginner)

2011-11-22 Thread Mayo Adams
I have a list of tuples of the form (string,integer) that I would like to
write  to  a file with a line break between each. Simply writing to a file
object thus

for item in tuplelist
   outputfile.write (item)

doesn't work, and I suppose I scarcely expect it should, but I am at a loss
to find out how to do it.

-- 
Mayo Adams



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


Re: [Tutor] basic class loading question

2011-11-22 Thread Dave Angel

On 11/22/2011 12:09 PM, Cranky Frankie wrote:

On Tue, Nov 22, 2011 at 11:26 AM, Dave Angel  wrote:
snip

quarterbacks = []
for 
 quarterbacks.append(   )


Now that you really have a list, then you can print a particular one with:

print (quarterbacks[2].last_name)

Dave I'm sorry but I just don't get this. I have virtually no
experience  with classes.

What seems like it shoud work is this:

###
len_Qb_list = len(Qb_list)

for i in range(0, len_Qb_list):
 quarterbacks = Qb(*Qb_list[i])
That creates one quarterback, not a list of them.  So you need to append 
that to some list.  As I said in my earlier message, you might want to 
append it to a list called quarterbacks, not replace the earlier object.

 i = i + 1

print (quarterbacks[2].last_name)


In other words, define an instance of the Qb class called
quarterbacks, and then "load" or instantiate instances of the class
using the 6 sets of values from Qb_list.

My error message is:

Traceback (most recent call last):
   File "D:/Python31/q", line 27, in
 print (quarterbacks[2].last_name)
TypeError: 'Qb' object does not support indexing



As long as it's a single object of your class, you can't index it.

Do you have any experience building a list in Python?  If you're trying 
to do it in a for loop. you'd have something like


objects= [] #create empty list
for  .whatever..
 newobject = ..something
 objects.append(newobject)


Now you have a list called objects.   You also have a newobject, which 
is the last one added.



--

DaveA

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


Re: [Tutor] basic class loading question

2011-11-22 Thread Cranky Frankie
On Tue, Nov 22, 2011 at 11:26 AM, Dave Angel  wrote:
snip
> quarterbacks = []
> for 
>     quarterbacks.append(       )
>
>
> Now that you really have a list, then you can print a particular one with:
>
> print (quarterbacks[2].last_name)

Dave I'm sorry but I just don't get this. I have virtually no
experience  with classes.

What seems like it shoud work is this:

###
len_Qb_list = len(Qb_list)

for i in range(0, len_Qb_list):
quarterbacks = Qb(*Qb_list[i])
i = i + 1

print (quarterbacks[2].last_name)


In other words, define an instance of the Qb class called
quarterbacks, and then "load" or instantiate instances of the class
using the 6 sets of values from Qb_list.

My error message is:

Traceback (most recent call last):
  File "D:/Python31/q", line 27, in 
print (quarterbacks[2].last_name)
TypeError: 'Qb' object does not support indexing






-- 
Frank L. "Cranky Frankie" Palmeri
Risible Riding Raconteur & Writer
“How you do anything is how you do everything.”
- from Alabama Crimson Tide training room
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] basic class loading question

2011-11-22 Thread Dave Angel

On 11/22/2011 09:20 AM, Cranky Frankie wrote:

OK, but this is still not working:

class Qb:
 def __init__(self, first_name='', last_name='', phone='',
email='', stadium=''):
 self.first_name = first_name
 self.last_name = last_name
 self.phone = phone
 self.email = email
 self.stadium = stadium



Qb_list = [["Joe", "Montana", "415-123-4567",
"joe.mont...@gmail.com","Candlestick Park"],
 ["Fran", "Tarkington","651-321-7657",
"frank.tarking...@gmail.com", "Metropolitan Stadidum"],
 ["Joe", "Namath", "212-222-", "joe.nam...@gmail.com", "Shea Stadium"],
 ["John", "Elway", "303-9876-333", "john.el...@gmai.com", "Mile
High Stadium"],
 ["Archie", "Manning", "504-888-1234", "archie.mann...@gmail.com",
"Louisiana Superdome"],
 ["Roger", "Staubach", "214-765-8989", "roger.staub...@gmail.com",
"Cowboy Stadium"]]



len_Qb_list = len(Qb_list)

for i in range(0, len_Qb_list):
 quarterbacks = Qb(*Qb_list[i])
 i = i + 1

print(quarterbacks.last_name(2))


You'll generally get better responses by saying in what way it's not 
working.  In this case, I get an exception in the print statement at the 
end.  So your message ought to state that, and show the traceback.


The specific error that causes that exception is you're trying to call a 
string.  What's that (2) all about anyway?   quarterbacks is an objext 
of type Qb, and quarterbacks.last_name is a string.


Your variable quarterbacks currently contains an object representing the 
last line of the list, the one for Roger Staubach.   You kept replacing 
the value in quarterbacks with the next item from the original list.  If 
you actually want a list of the objects, you need to say so.


quarterbacks = []
for 
 quarterbacks.append(   )


Now that you really have a list, then you can print a particular one with:

print (quarterbacks[2].last_name)

(I tested my own variant using python 2.7.   And i'm not saying your 
code can't be improved.  You're learning, and getting it correct is much 
more important than getting it "optimal.")


--

DaveA

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


[Tutor] Shortening code.

2011-11-22 Thread Mic


Please change to a sensible subject when replying to digest messages.

-Yes, sorry about that.



from tkinter import*

button1_color="green"
button1_value=False

button2_color="green"
button2_value=False


buttonX_value still doesn't say much about *why* the variable is there.
What are you storing in it. What does the value represent?

Also, do you really need the colors, you don't actually use them for
anything below except the initial color, but you might as well just hard
code it to "green", it would be shorter and more explicit...



This is a part of a larger program I am writing, where you are supposed to 
book chairs on a train.
Button1 is supposed to represent chair one in the train. When you click at 
the button, which represents a chair,
it is supposed to change color to show that the chair now is booked. If you 
press it one more time, it is supposed to

change color to show that the chair is free to book.
That was the idea. I am sorry if this was confusing, I will try to explain 
it more detailed later on in the mail.


-

   if button1_value:
   self.hello_bttn1.configure(bg="red", text="Hi_2")


Note that this is the line that really changes the button's color.
And it does not use the variable...


  def change_button1_color_red():
  global button1_color
  button1_color=("red")
  change_button1_color_red()


Whereas this function and its call do nothing but change the value of a
variable that is never used after the initial creation. If you took this
out the code would run with exactly the same effect.


  else:
  self.hello_bttn1.configure(bg="green", text="Hi_1")


Same, here. You set the color explicitly, then create
a function and call it just to update a variable you don't use.


  def change_button1_color_green():
  global button1_color
  button1_color=("green")
  change_button1_color_green()


-
I understand why you think I don't need to change the global value, since I 
am already changing the color with this line.

 self.hello_bttn1.configure(bg="green", text="Hi_1")

The thing is that this window I have created is just a window in another 
window. I want the color to be the same that it was before I closed the 
window.
Otherwise the color would be green when I open the window again, despite 
closing the window when the button was red. I hope you understand what I 
mean by this?


###
   def button2_clicked(self):
   """This method runs if button two is clicked"""

   def change_button2_value():
   global button2_value
   button2_value=not button2_value

   change_button2_value()

   if button2_value:

   self.hello_bttn2.configure(bg="red", text="Hi_2")

   def change_button2_color_red():
   global button2_color
   button2_color=("red")
   change_button2_color_red()

   else:
   self.hello_bttn2.configure(text="Hi_1", bg="green")

   def change_button2_color_green():
   global button2_color
   button2_color=("green")
   change_button2_color_green()



Notice that both button handlers are identical except they work on
different buttons and test values. What we'd like is a single
function that gets passed the widget and test as parameters.
It would look like this:

def button_clicked(self, widget, test):
if test:
widget.configure(bg="red", text="Hi_2")
else:
widget.configure(text="Hi_1", bg="green")


and to call it we create two short event handlers:

def button1_clicked(self):
 self.button1_value = not self.button1_value
 self.button_clicked(button1,self.button1_value)


def button2_clicked(self):
 self.button2_value = not self.button2_value
 self.button_clicked(button2,self.button2_value)


Notice I've moved the test values to instance variables
rather than globals, but thats just a style thing you could have
referenced the globals within the handlers instead.

I also removed those spurious functions from the main
button_clicked code.

-

This was exactly what I thought, that they these functions are so similiar 
that it should be one way to
shorten this code. In reality, in my larger program, I have about 10 buttons 
that should change value,

and colors when you click them.



However, I did not understand this part of your suggestions:



> Generally you build a data table with all the config parameters that
> will varty then you build a loop to read the values from the
> data table.
> Store the c

Re: [Tutor] Question on List Comprehensions

2011-11-22 Thread Steve Willoughby

On 21-Nov-11 23:49, Charles Becker wrote:

Alan, Steve, future readers,

After some re-reading and hacking I was able to discover the solution.  Since I 
raised the question here it is :

[['{0}'.format(x+1), x+1] for x in range(size)]


Just to fill out some other refinements for your information, if you're 
not planning to do anything special with the string formatting in each 
list, you don't really need to call format() when all it's doing is just 
making a string representation of the data value.  so

  '{0}'.format(x+1)
could just be
  str(x+1)

Resulting in:
  [[str(x+1), x+1] for x in range(size)]

Also, if you didn't like the repeated x+1 in there, you could just 
change the range call to go from 1..size directly:


  [[str(x), x] for x in range(1,size+1)]




--
Steve Willoughby / st...@alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] basic class loading question

2011-11-22 Thread Cranky Frankie
OK, but this is still not working:

class Qb:
def __init__(self, first_name='', last_name='', phone='',
email='', stadium=''):
self.first_name = first_name
self.last_name = last_name
self.phone = phone
self.email = email
self.stadium = stadium



Qb_list = [["Joe", "Montana", "415-123-4567",
"joe.mont...@gmail.com","Candlestick Park"],
["Fran", "Tarkington","651-321-7657",
"frank.tarking...@gmail.com", "Metropolitan Stadidum"],
["Joe", "Namath", "212-222-", "joe.nam...@gmail.com", "Shea Stadium"],
["John", "Elway", "303-9876-333", "john.el...@gmai.com", "Mile
High Stadium"],
["Archie", "Manning", "504-888-1234", "archie.mann...@gmail.com",
"Louisiana Superdome"],
["Roger", "Staubach", "214-765-8989", "roger.staub...@gmail.com",
"Cowboy Stadium"]]



len_Qb_list = len(Qb_list)

for i in range(0, len_Qb_list):
quarterbacks = Qb(*Qb_list[i])
i = i + 1

print(quarterbacks.last_name(2))




-- 
Frank L. "Cranky Frankie" Palmeri
Risible Riding Raconteur & Writer
“How you do anything is how you do everything.”
- from Alabama Crimson Tide training room
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] basic class loading question

2011-11-22 Thread Dave Angel

On 11/22/2011 08:17 AM, Cranky Frankie wrote:

I have a basic question about how to load a class. If I have this class:

class QB:
 def __init__(self, first_name='', last_name='', phone='',
email='', stadium=''):
 self.first_name = first_name
 self.last_name = last_name
 self.phone = phone
 self.email = email
 self.stadium = stadium

and this data:

QB_list = [["Joe", "Montana", "415-123-4567",
"joe.mont...@gmail.com","Candlestick Park"],
 ["Fran", "Tarkington","651-321-7657",
"frank.tarking...@gmail.com", "Metropolitan Stadidum"],
 ["Joe", "Namath", "212-222-", "joe.nam...@gmail.com", "Shea Stadium"],
 ["John", "Elway", "303-9876-333", "john.el...@gmai.com", "Mile
High Stadium"],
 ["Archie", "Manning", "504-888-1234", "archie.mann...@gmail.com",
"Louisiana Superdome"],
 ["Roger", "Staubach", "214-765-8989", "roger.staub...@gmail.com",
"Cowboy Stadium"]]

What is the best way to load it? I'm thinking there should be an
append method, but I'm having trouble getting it to work.



No idea what you mean by "load a class."

You can create an object by the classname and parentheses, containing 
the paramters as specified in the __init__() method.  So since your 
class was called QB (which should be Qb, by naming conventions):


obj = QB("Joe", "Montana", "415-213-4567",

joe.mont...@gmail.com","Candlestick Park")

and since that happens to be one element of your list, you could use

obj = QB( *QB_list[0] )

If you want a collection of such objects, you might want to write a loop, and 
then indeed the append method might be useful.

Write some code, and show us where you get stuck.


--

DaveA

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


Re: [Tutor] File vs. Database (possible off topic)

2011-11-22 Thread Steven D'Aprano

Ken G. wrote:
It occurred to me last week while reviewing the files I made in using 
Python, it could be somewhat similar to a database.


What would be a different between a Python files and Python databases?  
Granted, the access in creating them are different, I really don't see 
any different in the format of a file and a database.


A database is essentially a powerful managed service built on top of one 
or more files. There's nothing you can do with a database that you can't 
do with a big set of (say) Windows-style INI files and a whole lot of 
code to manage them. A database does all the management for you, 
handling all the complexity, data integrity, and security, so that you 
don't have to re-invent the wheel. Since database software tends to be 
big and complicated, there is a lot of wheel to be re-invented.


To be worthy of the name "database", the service must abide by the ACID 
principles:


Atomicity
-

The "all or nothing" principle. Every transaction must either completely 
succeed, or else not make any changes at all. For example, if you wish 
to transfer $100 from account A to account B, it must be impossible for 
the money to be removed from A unless it is put into B. Either both 
operations succeed, or neither.



Consistency
---

Any operation performed by the database must always leave the system in 
a consistent state at the end of the operation. For example, a database 
might have a table of "Money Received" containing $2, $3, $5, $1 and $2, 
and another field "Total" containing $13, and a rule that the Total is 
the sum of the Money Received. It must be impossible for an operation to 
leave the database in an inconsistent state by adding $5 to the Money 
Received table without increasing Total to $18.



Isolation
-

Two transactions must always be independent. It must be impossible for 
two transactions to attempt to update a field at the same time, as the 
effect would then be unpredictable.



Durability
--

Once a transaction is committed, it must remain committed, even if the 
system crashes or the power goes out. Once data is written to disk, 
nothing short of corruption of the underlying bits on the disk should be 
able to hurt the database.



Note that in practice, these four ACID principles may be weakened 
slightly, or a lot, for the sake of speed, convenience, laziness, or 
merely by incompetence. Generally speaking, for any program (not just 
databases!) the rule is:


"Fast, correct, simple... pick any two."

so the smaller, faster, lightweight databases tend to be not quite as 
bullet-proof as the big, heavyweight databases.



Modern databases also generally provide an almost (but not quite) 
standard interface for the user, namely the SQL programming language. 
Almost any decent database will understand SQL. For example, this command:


SELECT * FROM Book WHERE price > 100.00 ORDER BY title;

is SQL to:

* search the database for entries in the Book table
* choose the ones where the price of the book is greater than $100
* sort the results by the book title
* and return the entire record (all fields) for each book

So, broadly speaking, if you learn SQL, you can drive most databases, at 
least well enough to get by.



--
Steven

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


[Tutor] basic class loading question

2011-11-22 Thread Cranky Frankie
I have a basic question about how to load a class. If I have this class:

class QB:
def __init__(self, first_name='', last_name='', phone='',
email='', stadium=''):
self.first_name = first_name
self.last_name = last_name
self.phone = phone
self.email = email
self.stadium = stadium

and this data:

QB_list = [["Joe", "Montana", "415-123-4567",
"joe.mont...@gmail.com","Candlestick Park"],
["Fran", "Tarkington","651-321-7657",
"frank.tarking...@gmail.com", "Metropolitan Stadidum"],
["Joe", "Namath", "212-222-", "joe.nam...@gmail.com", "Shea Stadium"],
["John", "Elway", "303-9876-333", "john.el...@gmai.com", "Mile
High Stadium"],
["Archie", "Manning", "504-888-1234", "archie.mann...@gmail.com",
"Louisiana Superdome"],
["Roger", "Staubach", "214-765-8989", "roger.staub...@gmail.com",
"Cowboy Stadium"]]

What is the best way to load it? I'm thinking there should be an
append method, but I'm having trouble getting it to work.


-- 
Frank L. "Cranky Frankie" Palmeri
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python code trouble!

2011-11-22 Thread Asokan Pichai
Okay!

I wrote some code. It is below so that you can avoid scrolling down and
seeing it if you do not want to see any code!

HTH
Asokan
































people = list(" ABCDEFGHIJKLMN")
COUNT = len(people)
remove = 3
SPACE = ' '

def survivorCount(a):
   return len(a) - a.count(SPACE)

pos = 0
men = 0
while survivorCount(people) != 1:
   if people[pos] != SPACE:
men += 1
if men % remove == 0:
  print "removed", people[pos], "at", pos
  people[pos] = SPACE
   pos = (pos + 1) % COUNT

print ''.join(people).strip()
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor