Re: [Tutor] Random order program

2011-11-28 Thread Charles Becker
Dave, Myles, et al,

On Nov 27, 2011, at 4:25 PM, Dave Angel  wrote:

> On 11/27/2011 05:17 PM, myles broomes wrote:
>> 
>> 
>> 
>> 
>> 
>> 
>> 
>> #random order list
>> while len(random_word_list) != len(word_list):
>> word = random.choice(word_list)
>> if word not in random_word_list:
>> random_word_list += word
>> 
> If you use  += operator with list on the left side, it assumes something 
> compatible with list on the right.  So either use
> random_word_list  +=  [word]
> Or else use random_word_list.append(word)
>> 
>> 
>> 
>> 
>> 

Everyone has offered some good feedback, I just wanted to throw in this, and 
hopefully everyone can say if I'm correct or not:

A way to make the code more 'pythonic' and easier to read might be to replace 
the conditional 
while len(random_word_list) != len(word_list)
With the following :
For x in range(len(word_list))
This will prevent infinite loops, easier to read, and allows for a lot of other 
uses (even if x is never used).  Any thoughts people?  And would this method 
(on a small or large scale) be 'cheaper' than the original conditional? Or more 
'pythonic'?

Charles

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


Re: [Tutor] Text Proccessing/Command Line Redirection/XML Parsing etc in Python.

2011-11-28 Thread Stefan Behnel

Pritesh Ugrankar, 28.11.2011 07:56:

First of all, my apologies for writing this very long post.


Welcome to the list. :)



I have been through some related questions about this in Stack Overflow as
well as googled it and found that Perl and Python are the two languages
that offer most what I need. As a SAN Administrator, I have a very limited
time to learn a scripting language so I can concentrate on only one. Most
of my questions below may make you think that I prefer Perl, but its
nothing like...Just that I tried learning Perl before for doing stuff I
want to try, but am thinking now what advantages will I have if I try out
Python?


There are two anecdotes that people from both camps frequently report. With 
Perl, people write their script, and then, several months later, they come 
back, look at it, don't understand it anymore, and rewrite it. With Python, 
people write their script, forget about it over time, write it again when 
they need it, and when they happen to find the old one and compare it to 
the new one, they find that both look almost identical.


It's all in the syntax.



All my SAN Management Servers are Windows only.

Following is what I am specifically looking at:

1) Consider the following output:
symdev -sid 1234 list devs
0D62 Not Visible???:? 07C:D13 RAID-5N/A (DT) RW  187843
0D63 Not Visible???:? 08C:C11 RAID-5N/A (DT) RW  187843
0D64 Not Visible???:? 07C:C12 RAID-5N/A (DT) RW  62614
0D65 Not Visible???:? 08C:D14 RAID-5N/A (DT) RW  62614
0D66 Not Visible???:? 07C:D15 RAID-5N/A (DT) RW  31307
0D67 Not Visible???:? 08C:C13 RAID-5N/A (DT) RW  31307
0D68 Not Visible???:? 07C:C14 RAID-5N/A (DT) RW  31307

  Whats given above is only a small part of the output. There are many other
fields that appear but I have left those out for brevity.

The symdev commands generates a list of devices that can be used for SAN
Allocation.

What I want to do is, on the Windows Machines, do something like a grep or
awk so that the 10th field, which contains the size of the devices will be
filtered and I can generate an output like.

Devices of 187 GB = 3

Devices of 62 GB = 2

Devices of 31 GB = 3

Thing is, this output will differ on each storage box. Some may have 10
devices, some may have 100

I can use grep or awk for Windows, but looking at a bigger picture here.

what I want to do is do some kind of filtering of the command line output
so that it will count the type of devices and seggregate them according to
their size.


That's really easy. You open the file (see the open() function) and it 
returns a file object. You can iterate over it with a for-loop, and it will 
return each line as a string. Use the split() method on the string object 
to split the string by whitespace. That returns a list of separate fields. 
Then, pick the fields you want. In code:


with open('thefile.txt') as f:
for line in f:
fields = line.split()
print(fields[9])   # the 10th field, for example

If you are not reading the output from a file but from a process you 
started, take a look at the subprocess module in the standard library.


http://docs.python.org/library/subprocess.html

Also take a look at string formatting for output.

http://docs.python.org/tutorial/inputoutput.html

http://docs.python.org/library/stdtypes.html#string-formatting-operations



Tried Perl, but I found that the syntax was a little difficult to remember.
This is again my own shortcoming as I am not a trained programmer. I only
got to work on the script after a gap of many weeks and by that time, I
forgot what the script was supposed to do so had to start from the
scratchMay be commenting will help :)


Yep, that's Perl at it's best.



Which language will generate Binary executable that is smaller in size and
faster?


You usually don't do that. Instead, you'd install Python on all machines 
where you need it and then just run your code there.


If you really want to go through the hassle to build a self-contained 
executable from each program you write, you will have to bundle the runtime 
for either language with it, so it won't be small.




4) I also want to try out playing with XML outputThe storage commands I
use allow me the output to be directed to an XML FormatIs Python better
suited at this ?


Absolutely. Python has ElementTree. You'll just love working with it.

http://docs.python.org/library/xml.etree.elementtree.html

A quick tutorial is here:

http://effbot.org/zone/element-index.htm



Few more questions pop up like, Which will give me more freedom and ease to
maintain ? Which scripting language is better from the employability point
of view?

I dont want to start with one language and six months or a year down think
"Heck, this was better in the other one".because I really can
concentrate on only one langauge.


There are always certain types of probl

Re: [Tutor] Random order program

2011-11-28 Thread Alan Gauld

On 28/11/11 07:57, Charles Becker wrote:

A way to make the code more 'pythonic' and easier to read might be to
replace the conditional
while len(random_word_list) != len(word_list)
With the following :
for x in range(len(word_list))


Unfortunately that won't work with the OPs algorithm.
It involves randomly extracting an item from word_list until all items 
have been chosen, this is likely to require many more iterations than 
the number of items in the list because the random choice will pick some 
items more than once.


This is why we are suggesting that a different algorithm be used instead!

--
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] Random order program

2011-11-28 Thread Christian Witts

On 2011/11/28 12:17 AM, myles broomes wrote:

I requested help for this code earlier and I thought it had been corrected but 
apparently, there is still a problem with it...

#random word order program
#the user gives the program a list of words
#the program then returns them in a random order

import random

#explain the purpose of the program to the user
print("At the prompt, type in a list of words and they will be returned in a random 
order.")

#get the users input for the list of words, one by one
first_word = input("Please enter your first word: ")
second_word = input("Please enter your second word: ")
third_word = input("Please enter your third word: ")
fourth_word = input("Please enter your fourth word: ")
fifth_word = input("Please enter your fifth word: ")

#create a tuple containing the users words of the words
word_list = (first_word,second_word,third_word,fourth_word,fifth_word)

#create an empty list that the words will go into to be returned in a random 
order
random_word_list = []

print("Now your list will be displayed in a random order.")

#random order list
while len(random_word_list) != len(word_list):
 word = random.choice(word_list)
 if word not in random_word_list:
 random_word_list += word

#display the random word list
print(random_word_list)

input("Press enter to exit...")

And once again, the following is displayed

At the prompt, type in a list of words and they will be returned in a random 
order.
Please enter your first word: one
Please enter your second word: two
Please enter your third word: three
Please enter your fourth word: four
Please enter your fifth word: five
Now your list will be displayed in a random order.

Then the program just stops for some reason. Again, any help is much 
appreciated.

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




Is there anything wrong with just doing the following ?

from random import shuffle
# just type words with space separating the items
# ie. one two three four five
words = input('Please enter a list of words: ')
word_list = words.split()
print word_list
shuffle(word_list)
print word_list

--

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


Re: [Tutor] Tutor Digest, Vol 93, Issue 158

2011-11-28 Thread Pritesh Ugrankar
following was the next element.
> 0D63 Not Visible???:? 08C:C11 RAID-5N/A (DT) RW  187843
>
>  and so on.
>
> What I wanted instead was a way to printout and count the last field.I
> guess I will have to use hashes in Perl. Most examples of Hashes I have
> seen are pre createdBut is there a way to create a Hash on the fly?
> Because I dont know how many devices will be a part of that hashit will
> differ on each storage boxIs there something like this available in
> Python that will let me filter/add/printout the last field in a way that it
> will refer to it as a row and column kind of stuff? Is there a Hash
> equivalent in Python?
>
> Note I am giving Perl examples because I started with Perl firstthough
> personally, I find Python syntax easier to understand...(Again, my
> badmy limitation...not of the language)..
>
> 2) Automate storage allocation. Whats given below is only a small part of
> what I want to do Given is a brief output and explanation.
>
> All storage devices of my storage boxes have hexamdecimal LUN IDs.
>
> Lets say I have a free available LUN IDs between say 5* to A .meaning,
> the command output looks something like this:
> symcfg list -sid 1234 -sa 04B -p 0 -addresses -available
> Symmetrix ID: 000184501234
> Director Device Name Attr Address
> -- -  --
> Ident Symbolic Port Sym Physical VBUS TID LUN
> --    ---  --- ---
> FA-4B 04B 0 - AVAILABLE 0 0 000 *
> 0029 /dev/rdsk/c1t0d1s2 0 0 001
> 0033 /dev/rdsk/c1t0d2s2 0 0 002
> 003D /dev/rdsk/c1t0d3s2 0 0 003
> 0046 Not Visible0 0 004
> - AVAILABLE 0 0 005 *
> 0075 Not Visible0 0 00A
> - AVAILABLE 0 0 00B *
>
>  When there is a "*", from there on, till the next hex number, th LUN IDs
> are available. Meaning, from 000* to 1, nothing is available, but from 005*
> to 00A I have 006 through 009 available. I want to redirect this output to
> an array or a hash or something like that, then filter the last field, and
> then on the fly generate the LUN IDs between the 005 to 009 as well..Then
> using some commands, automate the process of allocating the LUN IDs to some
> free avaiable LUNs which I found in the first command output
>
> Is Perl better at manipulating hex or python?
>
> I know its possible to redirect the above output to a text file as well as
> a CSV file or an XML File and do I/Os on those files and then .but is Perl
> better for that or Python?
>
> 3) I want to generate reports on Performance, like which LUN has more
> IOsWhat will be helpful here is a language that can help me create
> these graphs in excelrun the script and the output should generate a
> graph in Excel
>
> Which language is better suited for my needs? I found Perl syntax a little
> cryptic, but if Perl will be faster and better suited than Python, then I
> am ready to invest more time with Perl
>
> Which language will be faster for text processing/automation?
>
> Which language will generate Binary executable that is smaller in size and
> faster?
> I played a little with Python too...today is my third dayFound the
> syntax much easier to learnAlso came across cxfreeze which creates
> independent binary executables...is something such available in Perl?
>
> 4) I also want to try out playing with XML outputThe storage commands I
> use allow me the output to be directed to an XML FormatIs Python better
> suited at this ?
>
> Few more questions pop up like, Which will give me more freedom and ease to
> maintain ? Which scripting language is better from the employability point
> of view?
>
> I dont want to start with one language and six months or a year down think
> "Heck, this was better in the other one".because I really can
> concentrate on only one langauge.
>
> My apologies in advance if any questions above seem to be dumb or naive.
> -- next part --
> An HTML attachment was scrubbed...
> URL: <
> http://mail.python.org/pipermail/tutor/attachments/2028/ded43c3c/attachment-0001.html
> >
>
> --
>
> Message: 2
> Date: Mon, 28 Nov 2011 00:57:10 -0700
> From: Charles Becker 
> To: "d...@davea.name" 
> Cc: "tutor@python.org" ,  myles broomes
>
> Subject: Re: [Tutor] Random order program
> Message-ID: 
> Content-Type: text/plain; charset="us-ascii"
>
> Dave, Myles, et al,
>
> On Nov 27, 2011, at 4:25 PM, Dave Angel  wrote:
>
> > On 11/27/2011 05:17 PM, myles broomes wrote:
> >>

Re: [Tutor] Tutor Digest, Vol 93, Issue 158

2011-11-28 Thread Alan Gauld

On 28/11/11 09:08, Pritesh Ugrankar wrote:


I am sure that there will be something in Python that will let me
generate the hex stuff that I was talking about.



Python does hex as well as most languages, I'm not sure exactly what you 
want to do in hex however, it wasn't clear from your original post.


One last thing, we prefer if you cut out redundant materialm from the 
posts, it cuts down bandwidth... So no need to include the full original 
message at the bottom.



learning this language. From what I understand, if something can be done
in one scripting language, same can be done in any other, and definitely
in Python.


Python can do most things, some other scripting languages are more 
specialised and therefore less flexible. But Perl, Python, Ruby, Tcl etc 
are all similar in capabilities.



--
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] Random order program

2011-11-28 Thread Alan Gauld

On 28/11/11 08:57, Christian Witts wrote:


Is there anything wrong with just doing the following ?


No, it's what we were trying to get the OP to discover for himself :-)


--
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] Critique and Question

2011-11-28 Thread Mark Lybrand
Okay, so I just started to learn Python.  I have been working through Dive
Into Python 3 and the Google stuff (great exercises IMHO, totally fun).
 However, with Dive, I had an issue with him referencing the files in the
example directory, which from the website seem very unhandy.  Although I
have since stumbled upon his GitHub, I made a Python script to grab those
files for me and it works great, with the exception of doubling the line
spacing.  So here is my code. I hope you critique the heck out of my and
that you point out what I did wrong to introduce double line-spacing.
 Thanks a bunch:

import os
import urllib.request
import re

url_root = 'http://diveintopython3.ep.io/examples/'
file_root = os.path.join(os.path.expanduser("~"), "diveintopython3",
"examples")

main_page = urllib.request.urlopen(url_root).read()
main_page = main_page.decode("utf-8")

pattern = 'href="([^"].*?.)(py|xml)"'
matches = re.findall(pattern, main_page)
for my_tuple in matches:
this_file = my_tuple[0] + my_tuple[1]
data = urllib.request.urlopen(url_root + this_file).read()
data = data.decode("utf-8")
with open(os.path.join(file_root, this_file), mode='w', encoding='utf-8')
as a_file:
a_file.write(data)

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


Re: [Tutor] Random order program

2011-11-28 Thread Peter Otten
Christian Witts wrote:

> Is there anything wrong with just doing the following ?
> 
> from random import shuffle
> # just type words with space separating the items
> # ie. one two three four five
> words = input('Please enter a list of words: ')
> word_list = words.split()
> print word_list
> shuffle(word_list)
> print word_list

You're mixing 3.x input and 2.x print ;)


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


Re: [Tutor] Random order program

2011-11-28 Thread Christian Witts

On 2011/11/28 11:37 AM, Peter Otten wrote:

Christian Witts wrote:


Is there anything wrong with just doing the following ?

from random import shuffle
# just type words with space separating the items
# ie. one two three four five
words = input('Please enter a list of words: ')
word_list = words.split()
print word_list
shuffle(word_list)
print word_list

You're mixing 3.x input and 2.x print ;)


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


Doh, that's what you get when you retype your code instead of copy/pasta 
it, it was originally raw_input.

--

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


[Tutor] why doesn't python show error

2011-11-28 Thread surya k

1. Why doesn't python show error(description given below) at the beginning when 
we use functions which aren't present in the standard modules...

Example: 

TheString = raw_input('enter a string')lengthofStr = strlen(TheString)Look 
closely, I used a wrong function to find length of the string. [ strlen( ) 
belongs to C ].When I run the program, it didn't show any error but when 
entered input, it then showed up!.Why python doesn't show error at the 
beginning just like C does?2. Why doesn't python create executable file (.exe ) 
when we run the code.. If this doesn't do, how can I share my program.. does 
everyone need to have python to check others code and know what it does?    
   
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] why doesn't python show error

2011-11-28 Thread Sarma Tangirala
On 28 November 2011 15:23, surya k  wrote:

>
> 1. Why doesn't python show error(description given below) at
> the beginning when we use functions which aren't present in the standard
> modules...
>
> Example:
>
> TheString = raw_input('enter a string')lengthofStr = strlen(TheString)Look
> closely, I used a wrong function to find length of the string. [ strlen( )
> belongs to C ].When I run the program, it didn't show any error but when
> entered input, it then showed up!.Why python doesn't show error at the
> beginning just like C does?2. Why doesn't python create executable file
> (.exe ) when we run the code.. If this doesn't do, how can I share my
> program.. does everyone need to have python to check others code and know
> what it does?
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


The thing is, python does not compile code like C does. It interprets each
line. So as you say, "it runs". Errors turn up only when they are
encountered.

http://en.wikipedia.org/wiki/Interpreted_language

But python does have a compile version, I believe jython does this.

There are a couple of programs that generate executable, py2exe on Win for
example.

http://stackoverflow.com/questions/2933/an-executable-python-app


-- 
Sarma Tangirala,
Class of 2012,
Department of Information Science and Technology,
College of Engineering Guindy - Anna University
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] why doesn't python show error

2011-11-28 Thread surya k
Thanks for that information. I understood what you are saying but in general 
when python doesn't give us executable files (whether its in Mac/ Linux/ 
Windows).. how could people develop programs ?. 
At some point of time people need to provide a file that runs without the help 
of a python interpreter.. 


From: Sarma Tangirala 
Sent: Monday, November 28, 2011 3:46 PM
To: surya k 
Cc: Python Tutor 
Subject: Re: [Tutor] why doesn't python show error





On 28 November 2011 15:23, surya k  wrote:


  1. Why doesn't python show error(description given below) at the beginning 
when we use functions which aren't present in the standard modules...

  Example: 

  TheString = raw_input('enter a string')lengthofStr = strlen(TheString)Look 
closely, I used a wrong function to find length of the string. [ strlen( ) 
belongs to C ].When I run the program, it didn't show any error but when 
entered input, it then showed up!.Why python doesn't show error at the 
beginning just like C does?2. Why doesn't python create executable file (.exe ) 
when we run the code.. If this doesn't do, how can I share my program.. does 
everyone need to have python to check others code and know what it does? 
  ___
  Tutor maillist  -  Tutor@python.org
  To unsubscribe or change subscription options:
  http://mail.python.org/mailman/listinfo/tutor



The thing is, python does not compile code like C does. It interprets each 
line. So as you say, "it runs". Errors turn up only when they are encountered. 


http://en.wikipedia.org/wiki/Interpreted_language


But python does have a compile version, I believe jython does this.


There are a couple of programs that generate executable, py2exe on Win for 
example.


http://stackoverflow.com/questions/2933/an-executable-python-app





-- 
Sarma Tangirala, 
Class of 2012,
Department of Information Science and Technology,
College of Engineering Guindy - Anna University
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] why doesn't python show error

2011-11-28 Thread Steven D'Aprano

surya k wrote:
Thanks for that information. I understood what you are saying but in general when python doesn't give us executable files (whether its in Mac/ Linux/ Windows).. how could people develop programs ?. 
At some point of time people need to provide a file that runs without the help of a python interpreter.. 


Why?

Perl, Javascript, PHP, Flash, Java, shell scripts, .Net, VisualBasic, and 
hundreds of other languages have been successful for decades, and they all 
require either an interpreter or a runtime environment, or both, to work.


Why should Python be treated any differently?

If you want to include a Python runtime environment with your code, either 
include a version of Python, or use py2exe to wrap the Python runtime 
environment and your code into a single executable.


Unless you are writing device drivers for hardware, or operating system 
kernels, or a few other applications, compiling to machine code is of limited 
value. And even where compiling to machine code is useful, it is often better 
to use a Just In Time compiler that compiles the code when it is run, so it 
can take advantage of runtime information about the data. A good JIT compiler 
can often beat a static compiler for speed.




--
Steven

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


Re: [Tutor] How to handle conjunction operators

2011-11-28 Thread Timo

Op 27-11-11 20:02, Hugo Arts schreef:

On Sun, Nov 27, 2011 at 7:52 PM, surya k  wrote:

Hi,
Could you please tell me why this isn't working and how can I make it
possible...
Consider this code..

name = raw_input("Enter your first name: ")
if name[0] == ("m" or "f" or "b") :
rhyme = name[1:]

What I want here is.. If the name starts with 'm' or 'f' or 'b', The first
letter should be removed.
But this isn't happening here.

This is a very common error. Fact is, the or operator just isn't
distributive with respect to the == operator like that, and for good
reason. What you want is either this:

if name[0] == "m" or name[0] == "f" or name[0] == "b":

or, more idiomatically, you can use the in operator like this:

if name[0] in ("m", "f", "b"):

Or even shorter:
if name[0] in "mfb":

Cheers,
Timo



HTH,
Hugo
___
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] How to handle conjunction operators

2011-11-28 Thread Peter Otten
surya k wrote:

> Could you please tell me why this isn't working and how can I make it
> possible... Consider this code..

> name = raw_input("Enter your first name:") 
> if name[0] == ("m" or "f" or "b") :
>rhyme = name[1:]
>What I want here is.. If the name starts with 'm' or
>'f' or 'b', The first letter should be removed.But this isn't happening
>here.

- If you want to make your code bullet-proof you should also consider the 
case where the user enters an empty string.

- You can check if a string starts with a particular string with the 
startswith() method:

>>> "frank".startswith("f")
True

It's not widely known, but the method accepts a tuple since Python 2.5:

>>> "sue".startswith(("m", "f", "b"))
False
>>> "frank".startswith(("m", "f", "b"))
True

The beauty of this approach is that you are not limited to single-char 
prefixes:

>>> "stephen".startswith(("m", "f", "st"))
True


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


Re: [Tutor] How to handle conjunction operators

2011-11-28 Thread Steven D'Aprano

Timo wrote:


if name[0] in ("m", "f", "b"):

Or even shorter:
if name[0] in "mfb":


Shorter, but wrong.

name = ['fb', 'ph', 'xy']  # oops, bad data
if name[0] in 'mfb':
...


Bad data should lead to an error as close as possible to the source of the bad 
data, and do the wrong thing for a while before blowing up in some unexpected 
part of the code. Code defensively: if you want to be sure name[0] is a single 
character, make sure the test will only pass when given a single character.



--
Steven

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


Re: [Tutor] Weird Try..Except Error

2011-11-28 Thread Michael M Mason
Alan Gauld wrote on 25 November 2011 at 21:11:-
> This is one of the annoying ambiguities of Windows.
> The way it finds the executable for  executables(exe, bat cmd etc) is 
> different to how it finds the executable for associations.
>
> In the former case it uses PATH, in the latter it relies on the file 
> association set in the file properties.
>
> When you install a new Python it  tends to set itself as
> the default interpreter for .py files.

You can use the DOS commands to manipulate file associations on Windows
so that you can run two or more versions of Python on the same computer.
The DOS commands are ASSOC and FTYPE.

First you need to use ASSOC to discover the file type for .py, .pyw and
.pyc files. To use ASSOC type ASSOC followed by the extension you are
interested in. For example, find the file type for .py files, type:-

assoc .py

Typical results from ASSOC will be:-

.py = Python.File
.pyw = Python.NoConFile
.pyc = Python.CompiledFile

Next, use FTYPE to discover the 'open' commands associated with each of
these file types. To use FTYPE type FTYPE followed by the file type as
given by the ASSOC command. For example:-

ftype Python.File

Typical results from FTYPE will be something like this:-

Python.File="C:\Python27\python.exe" "%1" %*
Python.NoConFile="C:\Python27\pythonw.exe" "%1" %*
Python.CompiledFile="C:\Python27\python.exe" "%1" %*

What we can do now is create our own set of file types, one for Python 2.7
and one for Python 3.2. This is done using the FTYPE command (of course,
your paths may be different to the ones shown):-

ftype Python32.File="C:\Python3\python.exe" "%1" %*
ftype Python32.NoConFile="C:\Python3\pythonw.exe" "%1" %*
ftype Python32.CompiledFile="C:\Python3\python.exe" "%1" %*
ftype Python27.File="C:\Python27\python.exe" "%1" %*
ftype Python27.NoConFile="C:\Python27\pythonw.exe" "%1" %*
ftype Python27.CompiledFile="C:\Python27\python.exe" "%1" %*

That's the preparatory work completed. We can now choose which version of
Python will run when a *.py file is executed using the ASSOC command. To
select Python 3 we'd use these commands:-

assoc .py = Python32.File
assoc .pyw = Python32.NoConFile
assoc .pyc = Python32.CompiledFile

...and to use Python 2.7 we'd use these commands:-

assoc .py = Python27.File
assoc .pyw = Python27.NoConFile
assoc .pyc = Python27.CompiledFile

-- 
Michael

This mail was sent via Mail-SeCure System.



 
 

This footnote confirms that this email message has been scanned by
PineApp Mail-SeCure for the presence of malicious code, vandals & computer 
viruses.




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


[Tutor] Multiplater gaming

2011-11-28 Thread surya k
I am building a multiplayer game (Game:Bingo) where friends(players) connect 
over internet. In this particular game, users sends a "character/ number" to 
all other players..

Can you please shed some light on it. I've been looking into 'Core Python 
Programming' book by Chun but I couldn't understand clearly. 

So, If possible, please provide links to related free e-books / tutorials.

my another question is.. do I need to setup any external hardware 
infrastructure to get this done ??


Thanks for sparing your valuable time on this!


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


Re: [Tutor] Critique and Question

2011-11-28 Thread Dave Angel

On 11/28/2011 04:28 AM, Mark Lybrand wrote:

Okay, so I just started to learn Python.  I have been working through Dive
Into Python 3 and the Google stuff (great exercises IMHO, totally fun).
  However, with Dive, I had an issue with him referencing the files in the
example directory, which from the website seem very unhandy.  Although I
have since stumbled upon his GitHub, I made a Python script to grab those
files for me and it works great, with the exception of doubling the line
spacing.  So here is my code. I hope you critique the heck out of my and
that you point out what I did wrong to introduce double line-spacing.
  Thanks a bunch:

import os
import urllib.request
import re

url_root = 'http://diveintopython3.ep.io/examples/'
file_root = os.path.join(os.path.expanduser("~"), "diveintopython3",
"examples")

main_page = urllib.request.urlopen(url_root).read()
main_page = main_page.decode("utf-8")

pattern = 'href="([^"].*?.)(py|xml)"'
matches = re.findall(pattern, main_page)
for my_tuple in matches:
this_file = my_tuple[0] + my_tuple[1]
data = urllib.request.urlopen(url_root + this_file).read()
data = data.decode("utf-8")
with open(os.path.join(file_root, this_file), mode='w', encoding='utf-8')
as a_file:
a_file.write(data)

You don't tell what your environment is, nor how you decide that the 
file is double-spaced.  You also don't mention whether you're using 
Python 2.x or 3.x


My guess is that you are using a Unix/Linux environment, and that the 
Dive author(s) used Windows.  And that your text editor is interpreting 
the cr/lf pair (hex 0d 0a) as two line-endings.  I believe emacs would 
have ignored the redundant cr.  Python likewise probably won't care, 
though I'm not positive about things like lines that continue across 
newline boundaries.


You can figure out what is actually in the file by using repr() on bytes 
read from the file in binary mode.  Exactly how you do that will differ 
between Python 2.x and 3.x


As for fixing it, you could either just use one of the dos2unix 
utilities kicking around (one's available on my Ubuntu from the Synaptic 
package manager), or you could make your utility manage it.  On a 
regular file open, there's a mode paramter that you can use "u", or 
better "ru" to say Universal.  It's intended to handle any of the three 
common line endings, and use a simple newline for all 3 cases.  I don't 
know whether urlopen() also has that option, but if not, you can always 
copy the file after you have it locally.



--

DaveA

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


Re: [Tutor] Multiplater gaming

2011-11-28 Thread Andreas Perstinger

On 2011-11-28 13:22, surya k wrote:

I am building a multiplayer game (Game:Bingo) where friends(players)
connect over internet. In this particular game, users sends a
"character/ number" to all other players..

Can you please shed some light on it. I've been looking into 'Core
Python Programming' book by Chun but I couldn't understand clearly.


What are your specific problems? We can't help you if you don't give us 
more information about your program. Show us the problematic parts of 
your code.



So, If possible, please provide links to related free e-books /
tutorials.


Some tutorials (IIRC you have already programming experiences, haven't 
you?):

http://wiki.python.org/moin/BeginnersGuide/Programmers


my another question is.. do I need to setup any external hardware
infrastructure to get this done ??


I'm not a hardware expert, but if you want to create an online game 
you'll need at least some kind of server which probably has to be online 
24/7 and is able to handle the traffic.


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


Re: [Tutor] Critique and Question

2011-11-28 Thread Mark Lybrand
Sorry for not providing all the required info. I am running python 3.2 on
windows vista. I determined the files are double spaced by viewong them
(random sampling) in notepad++. Not double spaced on server by downloading
one in the browser. Can I use the 'Wu' flag when writing.  I might just be
'w'-ing. I will look when I get home.

Thanks

Mark

Also a little bummed that subprocess module doesn't appear to work on
windows. I probably (hopefully) won't need it, but it still bums me.
 On Nov 28, 2011 4:27 AM, "Dave Angel"  wrote:

> On 11/28/2011 04:28 AM, Mark Lybrand wrote:
>
>> Okay, so I just started to learn Python.  I have been working through Dive
>> Into Python 3 and the Google stuff (great exercises IMHO, totally fun).
>>  However, with Dive, I had an issue with him referencing the files in the
>> example directory, which from the website seem very unhandy.  Although I
>> have since stumbled upon his GitHub, I made a Python script to grab those
>> files for me and it works great, with the exception of doubling the line
>> spacing.  So here is my code. I hope you critique the heck out of my and
>> that you point out what I did wrong to introduce double line-spacing.
>>  Thanks a bunch:
>>
>> import os
>> import urllib.request
>> import re
>>
>> url_root = 
>> 'http://diveintopython3.ep.io/**examples/
>> '
>> file_root = os.path.join(os.path.**expanduser("~"), "diveintopython3",
>> "examples")
>>
>> main_page = urllib.request.urlopen(url_**root).read()
>> main_page = main_page.decode("utf-8")
>>
>> pattern = 'href="([^"].*?.)(py|xml)"'
>> matches = re.findall(pattern, main_page)
>> for my_tuple in matches:
>> this_file = my_tuple[0] + my_tuple[1]
>> data = urllib.request.urlopen(url_**root + this_file).read()
>> data = data.decode("utf-8")
>> with open(os.path.join(file_root, this_file), mode='w', encoding='utf-8')
>> as a_file:
>> a_file.write(data)
>>
>>  You don't tell what your environment is, nor how you decide that the
> file is double-spaced.  You also don't mention whether you're using Python
> 2.x or 3.x
>
> My guess is that you are using a Unix/Linux environment, and that the Dive
> author(s) used Windows.  And that your text editor is interpreting the
> cr/lf pair (hex 0d 0a) as two line-endings.  I believe emacs would have
> ignored the redundant cr.  Python likewise probably won't care, though I'm
> not positive about things like lines that continue across newline
> boundaries.
>
> You can figure out what is actually in the file by using repr() on bytes
> read from the file in binary mode.  Exactly how you do that will differ
> between Python 2.x and 3.x
>
> As for fixing it, you could either just use one of the dos2unix utilities
> kicking around (one's available on my Ubuntu from the Synaptic package
> manager), or you could make your utility manage it.  On a regular file
> open, there's a mode paramter that you can use "u", or better "ru" to say
> Universal.  It's intended to handle any of the three common line endings,
> and use a simple newline for all 3 cases.  I don't know whether urlopen()
> also has that option, but if not, you can always copy the file after you
> have it locally.
>
>
> --
>
> DaveA
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] pass tuples to user defined function(beginner)

2011-11-28 Thread Mayo Adams
I am trying to pass a set of tuple strings from a file to a function I
have defined.  Each tuple is on a separate line, and looks something
like this:
 ('note',2048)
The function has two parameters , and is defined thus: def
findindex(dval,ticks):
Apparently, I need to cast the second value as an integer in the body
of the function in order to work with it as such, but when I attempt
int(ticks) I get
ValueError: invalid literal for int() with base 10: '2048)'

Upon searching for elucidation of this on the internet I find nothing
but esoterica, at least as far as I am concerned.
Any pointers would make me happy.

--
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] pass tuples to user defined function(beginner)

2011-11-28 Thread James Reynolds
On Mon, Nov 28, 2011 at 12:32 PM, Mayo Adams  wrote:

> I am trying to pass a set of tuple strings from a file to a function I
> have defined.  Each tuple is on a separate line, and looks something
> like this:
>  ('note',2048)
> The function has two parameters , and is defined thus: def
> findindex(dval,ticks):
> Apparently, I need to cast the second value as an integer in the body
> of the function in order to work with it as such, but when I attempt
> int(ticks) I get
> ValueError: invalid literal for int() with base 10: '2048)'
>
> Upon searching for elucidation of this on the internet I find nothing
> but esoterica, at least as far as I am concerned.
> Any pointers would make me happy.
>
> --
> Mayo Adams
>
>
>
> mayoad...@gmail.com
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



Your problem is in the error message:

ValueError: invalid literal for int() with base 10: '2048)'

observer, Python tells you this isn't a number: '2048)'

Indeed, this is correct, because you '2048)' is not a number.

What you really want to pass to '2048', which int('2048')

can understand just fine.

So, trim off the parenthesis, or something.

Alternatively, since you aren't actually passing a "tuple" but something
that looks like a python tuple as a string, you could eval it:

a = "('note',2048)"
b = eval(a)

print a, type(a), b, type(b)

>> ('note',2048)  ('note', 2048) 

In working with the second, you do normal tuple operations, like b[1] to
access that index

When passing to a function, you do this: findindex(*b)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Critique and Question

2011-11-28 Thread Dave Angel

On 11/28/2011 12:31 PM, Mark Lybrand wrote:

Sorry for not providing all the required info. I am running python 3.2 on
windows vista. I determined the files are double spaced by viewong them
(random sampling) in notepad++. Not double spaced on server by downloading
one in the browser. Can I use the 'Wu' flag when writing.  I might just be
'w'-ing. I will look when I get home.

Thanks

Mark

Also a little bummed that subprocess module doesn't appear to work on
windows. I probably (hopefully) won't need it, but it still bums me.
  On Nov 28, 2011 4:27 AM, "Dave Angel"  wrote:


On 11/28/2011 04:28 AM, Mark Lybrand wrote:


Okay, so I just started to learn Python.  I have been working through Dive
Into Python 3 and the Google stuff (great exercises IMHO, totally fun).
  However, with Dive, I had an issue with him referencing the files in the
example directory, which from the website seem very unhandy.  Although I
have since stumbled upon his GitHub, I made a Python script to grab those
files for me and it works great, with the exception of doubling the line
spacing.  So here is my code. I hope you critique the heck out of my and
that you point out what I did wrong to introduce double line-spacing.
  Thanks a bunch:

import os
import urllib.request
import re

url_root = 
'http://diveintopython3.ep.io/**examples/
'
file_root = os.path.join(os.path.**expanduser("~"), "diveintopython3",
"examples")

main_page = urllib.request.urlopen(url_**root).read()
main_page = main_page.decode("utf-8")

pattern = 'href="([^"].*?.)(py|xml)"'
matches = re.findall(pattern, main_page)
for my_tuple in matches:
this_file = my_tuple[0] + my_tuple[1]
data = urllib.request.urlopen(url_**root + this_file).read()
data = data.decode("utf-8")
with open(os.path.join(file_root, this_file), mode='w', encoding='utf-8')
as a_file:
a_file.write(data)

  You don't tell what your environment is, nor how you decide that the

file is double-spaced.  You also don't mention whether you're using Python
2.x or 3.x

My guess is that you are using a Unix/Linux environment, and that the Dive
author(s) used Windows.  And that your text editor is interpreting the

>

You can figure out what is actually in the file by using repr() on bytes
read from the file in binary mode.  Exactly how you do that will differ
between Python 2.x and 3.x



You put your comments BEFORE the quoted text (top-posted), so they 
appear out of order.  In a forum like this one, the convention is to add 
your remarks after the part you're quoting.


Use a hex viewer to see what the file actually looks like.  My guess 
doesn't apply, since if you had the reverse problem (reading text file 
in a Windows program that was generated in Linux)  MIGHT have a symptom 
of showing all the lines concatenated.  That's not what you describe.


if you don't have a hex viewer, you could write one, or you could just 
write a function that uses repr() on the first 200 bytes of the file.


As for subprocess, why would you guess that it doesn't work on Windows? 
 Perhaps if there's something specific that you've tried, you could 
start a new thread showing what you tried and how it misbehaved.  Don't 
forget to supply your environment information as well as the source code 
you tried, and any stack trace from the crash.



--

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


[Tutor] Functional tutorial covering SQL database + GUI interface

2011-11-28 Thread Monte Milanuk
Hello all,

Thought I might ask here just to make sure my Google-fu isn't on the fritz and 
I'm not missing something already existing...

Is there / do you know of any tutorial that covers actually using an SQL 
database with a GUI interface (say, sqlite and tkinter since they come 
packaged with python by default) to build something moderately useful like a 
small address book i.e. CRUD application?  

Seems like most of the tutorials cover isolated 'proof of concept' db access 
or small windows with a button and label, not a lot more.  I'm kind of at that 
point where I think I'm ready to move beyond that to making something a little 
more functional and thought I might see if there were any prior works that 
covered this sort of thing.

TIA,

Monte

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


[Tutor] tkinter message & button questions

2011-11-28 Thread Cranky Frankie
I have a program I'm testing in Python 3.1 in Windows XP using tkinker
to dispay random quotes. It works except for two things.

1) The program displays a random quote of the day when it's invoked,
but I want to have a "Next quote" button so that additional random
quotes can be displayed. Here are the parts of the program were I get
the first quote:


def get_random_quote():# create a function
to get a random quote from quote_dict

rq = (random.randrange(len(quote_dict))+1)  # pick a
random entry from the quote dictionary
return rq


def output_quote():
rand_quote = get_random_quote() # get a random quote
quote = quote_dict[rand_quote][1] # put the quote in a
string varible
author = quote_dict[rand_quote][0]# put the author in a
string variable
om = (quote+"\n\n"+author)  # format the output
string variable
return om


out_message = output_quote()

msg_widget = Message(win, anchor = NW, justify = LEFT, width = 1000,
bd= 2, bg = "white",
 relief = SOLID, text=out_message)




Here is my button the get the next quote:



next_button = Button(win, text="Next Quote", command=output_quote()) #
create button  widget
next_button.pack(side=LEFT)



Even though I'm calling the same function, output_quote(), the screen
is not getting refreshed. There is no error, just the new quote is not
showing up in the message box. How do I refresh the message box?

2) The message widget seems to be sizing based on the size of the text
you present to it. For a small quote it's small, for a longer quote it
streches out wide and then adds more lines. I'd like to present a
consistent sized message box when the program is run, no matter if the
text is small or large, but I can't figure out how to do that. In
other words, I'd like the message widget in question 1 above to
display as a box capable of storing, say, 1,000 characters, even if I
only give it 100, so the program looks the same every time it's
invoked. Is there a way to make a default sized message widget?

-- 
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] pass tuples to user defined function(beginner)

2011-11-28 Thread Dave Angel

On 11/28/2011 12:47 PM, James Reynolds wrote:

On Mon, Nov 28, 2011 at 12:32 PM, Mayo Adams  wrote:


I am trying to pass a set of tuple strings from a file to a function I
That's an undefined term.  Python doesn't have a type called 'tuple 
strings'.

have defined.  Each tuple is on a separate line, and looks something
like this:
  ('note',2048)
The function has two parameters , and is defined thus: def
findindex(dval,ticks):
Apparently, I need to cast the second value as an integer in the body
of the function in order to work with it as such, but when I attempt
int(ticks) I get
ValueError: invalid literal for int() with base 10: '2048)'

Upon searching for elucidation of this on the internet I find nothing
but esoterica, at least as far as I am concerned.
Any pointers would make me happy.

--
Mayo Adams



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




Your problem is in the error message:

ValueError: invalid literal for int() with base 10: '2048)'

observer, Python tells you this isn't a number: '2048)'

Indeed, this is correct, because you '2048)' is not a number.

What you really want to pass to '2048', which int('2048')

can understand just fine.

So, trim off the parenthesis, or something.

Alternatively, since you aren't actually passing a "tuple" but something
that looks like a python tuple as a string, you could eval it:

a = "('note',2048)"
b = eval(a)

print a, type(a), b, type(b)


('note',2048)  ('note', 2048)

In working with the second, you do normal tuple operations, like b[1] to
access that index

When passing to a function, you do this: findindex(*b)


My two-cents:

Avoid eval like the plague.   It's not a tool for the beginner, it's an 
escape hatch when all else fails.  So let's look at the first approach.


First comment is that the stuff in a text file is not treated in any way 
the same as the stuff in the source code.  Parentheses, quotes, and 
commas do not have any special meaning.


Whenever writing data to a file, if you expect to be able to read the 
same data back (as opposed to giving it to a human), you need to be 
careful about how you format it.  In effect, the writing and the reading 
have to be considered at the same time, and you have to decide just what 
constraints on the data, and what you'll do if the data doesn't meet 
those constraints.  Nothing magic about the parentheses, and I wouldn't 
have written them in the first place.


So what were the constraints on the original data?  If you're sure 
neither field can have any commas in it, then you could use line.split() 
with a comma as a delimiter.  And once you've split, you strip off the 
leading parenthesis on the zeroth item, and the trailing parens on the 
1th item.


At that point a simple int() function on the 1th item will convert the 
digit characters to an integer.


--

DaveA

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


Re: [Tutor] tkinter message & button questions

2011-11-28 Thread Peter Otten
Cranky Frankie wrote:

> I have a program I'm testing in Python 3.1 in Windows XP using tkinker
> to dispay random quotes. It works except for two things.
> 
> 1) The program displays a random quote of the day when it's invoked,
> but I want to have a "Next quote" button so that additional random
> quotes can be displayed. Here are the parts of the program were I get
> the first quote:
> 
> 
> def get_random_quote():# create a function
> to get a random quote from quote_dict

Crankie, your comments carry very little information, but entirely mess up 
the formatting of the scripts you post. Please avoid all comments but those 
that really help understanding your program. Keep the line length under 80 
chars and start a new line if that doesn't suffice.

> 
> rq = (random.randrange(len(quote_dict))+1)  # pick a
> random entry from the quote dictionary
> return rq
> 
> 
> def output_quote():
> rand_quote = get_random_quote() # get a random quote
> quote = quote_dict[rand_quote][1] # put the quote in a
> string varible
> author = quote_dict[rand_quote][0]# put the author in a
> string variable
> om = (quote+"\n\n"+author)  # format the output
> string variable
> return om
> 
> 
> out_message = output_quote()
> 
> msg_widget = Message(win, anchor = NW, justify = LEFT, width = 1000,
> bd= 2, bg = "white",
>  relief = SOLID, text=out_message)
> 
> 
> 
> 
> Here is my button the get the next quote:
> 
> 
> 
> next_button = Button(win, text="Next Quote", command=output_quote()) #

Here you are assigning the result of an output_quote() call (i. e. one of 
your quotes) to the command parameter. To get a new quote you need command 
be a function that somehow displays a new quote

def update_quote():
   # your code to make a new quote appear
   # on the screen

next_button = Button(..., command=update_quote)

Note the missing (), you are really passing the function

> create button  widget
> next_button.pack(side=LEFT)
> 
> 
> 
> Even though I'm calling the same function, output_quote(), the screen
> is not getting refreshed. There is no error, just the new quote is not
> showing up in the message box. How do I refresh the message box?
> 
> 2) The message widget seems to be sizing based on the size of the text
> you present to it. For a small quote it's small, for a longer quote it
> streches out wide and then adds more lines. I'd like to present a
> consistent sized message box when the program is run, no matter if the
> text is small or large, but I can't figure out how to do that. In
> other words, I'd like the message widget in question 1 above to
> display as a box capable of storing, say, 1,000 characters, even if I
> only give it 100, so the program looks the same every time it's
> invoked. Is there a way to make a default sized message widget?

You may need another layout manager (.place()).


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


Re: [Tutor] Functional tutorial covering SQL database + GUI interface

2011-11-28 Thread Alan Gauld

On 28/11/11 17:49, Monte Milanuk wrote:


Is there / do you know of any tutorial that covers actually using an SQL
database with a GUI interface (say, sqlite and tkinter since they come
packaged with python by default) to build something moderately useful like a
small address book i.e. CRUD application?


My tutorial shows how to build an address book in SqlLite.
But it doesn't add the GUI layer. But the GUI is pretty much independant 
of the SQL Layer (or should be!)


The Case Study app shows a more representative GUI with some radio 
buttons and a Text widget(where you could dump the result of a SQL 
qwuery for example...)



Seems like most of the tutorials cover isolated 'proof of concept' db access
or small windows with a button and label, not a lot more.


Thats all most tutorials will cover, its an exercise for the reader to 
join all the bits together :-)


But seriously, if I ever get round to finishing the missing topics I do 
intend to take the address book right through to a web application on 
top of a SQL database Just finding the time is the problem.



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

2011-11-28 Thread Chris Hare

I have been searching around a bit, but not really finding anything which is 
meaningful.

I want to embed a set of help files in my application, and display them from 
within the application.  I could use plain text files, which would be easy to 
suck into a Text field, but it would be nice to include rich text features and 
maybe even graphics.

Is there some way of displaying rich text files, such as RTF or HTML from 
within a python Tkinter widget?

Thanks

Chris


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


Re: [Tutor] pass tuples to user defined function(beginner)

2011-11-28 Thread Steven D'Aprano

James Reynolds wrote:


Alternatively, since you aren't actually passing a "tuple" but something
that looks like a python tuple as a string, you could eval it:


Please don't give beginners terrible advice like this.

There are already too many programs vulnerable to code injection attacks 
without us encouraging newbies to write more.


If anyone here doesn't know what a code injection attack is, and what it has 
to do with eval and exec, then please do not write another line of code until 
you have have learned.




a = "('note',2048)"
b = eval(a)



And then one day somebody finds a way of passing input like this to your web 
server using that code:


"__import__('os').system('echo i got you now rm-rf')"

Say goodnight Gracie. I hope you have good backups.



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


Re: [Tutor] advice

2011-11-28 Thread Alan Gauld

On 28/11/11 22:05, Chris Hare wrote:


Is there some way of displaying rich text files, such as RTF or HTML
from within a python Tkinter widget?


Not so much RTF but you can set different fonts and colours etc within 
the standard text widget. You could either use HTML or a subset to save 
your styles and interpret that when loading the widget.



But its much more common these days to just use HTML and launch a 
browser. The browser module may help there.


--
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] pass tuples to user defined function(beginner)

2011-11-28 Thread Dave Angel
1.  Please post messages to the list, a private response is not 
appropriate unless it's just a thanks, or other private msg.  Easiest 
way is probably to use Reply-All.


2.  Don't top-post.  Put your responses AFTER whatever you're quoting. 
It's a forum policy, for most usenet groups.


On 11/28/2011 01:45 PM, Mayo Adams wrote:

Thanks for your reply. I didn't say Python had a type called "tuple
strings", just that the lines in the file were tuples, and that the
elements of each tuple were strings. I suppose that is what I should
have said.


Still wrong on both counts.  A tuple does not and cannot exist in such a 
file.  And the original tuple must have consisted of a string and a number.



If I knew how to avoid the parenthesis, I would have, and it is
helpful to know that there is nothing meaningful about the
parentheses, as you say. Ill try to find a way to write the data to
the file without the parentheses.


The parentheses is only part of the problem.  You still haven't defined 
what constraints you had on the data in those tuples.  If you do, we can 
suggest various ways to store the data so that it's easy, efficient, 
and/or possible to retrieve it again.



Now since your message was out of order, I had to delete all the rest of 
the history.




--

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


Re: [Tutor] Critique and Question

2011-11-28 Thread Mark Lybrand
Just so y'all know, I replaced all the urlopen, read, write, nonsense with
the following:

urllib.request.urlretrieve(url_root + this_file, os.path.join(file_root,
this_file))

and it's all good :)

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


Re: [Tutor] pass tuples to user defined function(beginner)

2011-11-28 Thread bob gailer

On 11/28/2011 12:47 PM, James Reynolds wrote:



On Mon, Nov 28, 2011 at 12:32 PM, Mayo Adams > wrote:


I am trying to pass a set of tuple strings from a file to a function I
have defined.  Each tuple is on a separate line, and looks something
like this:
 ('note',2048)



As already pointed out - this is a string (a representation of a tuple), 
not a tuple.


Your code must parse the string to extract the string representations of 
the values, then convert as needed to the desired Python values.


Tasks like this are not trivial.

Using eval as already noted is the easiest but not the best solution.

Perhaps we should back up and ask the overall objective of the program. 
Where did this file come from? Could we store the data in some other 
(easier to parse) manner?


If each line will always contain a string literal and an integer literal 
then the simplest encoding is:

note 2048

the program then is:

for line in file(path):
  val1, val2 = line.split)
  findindex(val1, int(val2))

Also see http://docs.python.org/library/json.html


The function has two parameters , and is defined thus: def
findindex(dval,ticks):
Apparently, I need to cast the second value as an integer in the body
of the function in order to work with it as such, but when I attempt
int(ticks) I get
ValueError: invalid literal for int() with base 10: '2048)'

Upon searching for elucidation of this on the internet I find nothing
but esoterica, at least as far as I am concerned.
Any pointers would make me happy.

--
Mayo Adams



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




Your problem is in the error message:

ValueError: invalid literal for int() with base 10: '2048)'

observer, Python tells you this isn't a number: '2048)'

Indeed, this is correct, because you '2048)' is not a number.

What you really want to pass to '2048', which int('2048')

can understand just fine.

So, trim off the parenthesis, or something.

Alternatively, since you aren't actually passing a "tuple" but 
something that looks like a python tuple as a string, you could eval it:


a = "('note',2048)"
b = eval(a)

print a, type(a), b, type(b)

>> ('note',2048)  ('note', 2048) 

In working with the second, you do normal tuple operations, like b[1] 
to access that index


When passing to a function, you do this: findindex(*b)


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



--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] Coin game

2011-11-28 Thread bob gailer

On 11/27/2011 7:43 PM, Guess?!? wrote:


Two players take turns flipping a fair coin. The game ends when the 
same outcome occurs on three flips in a row. Whichever player flipped 
the coin last, wins. For example:




Here's my version of a simple compact program.

import random
N = 10
tosses = ''.join(random.choice("HT") for i in range (N))
w = min(tosses.find("TTT") % N + 1,tosses.find("HHH") % N + 1)
if w == N: print 'no winner'
else: print tosses[:w+2], 'player %s wins.' %((w % 2) + 1,)

--
Bob Gailer
919-636-4239
Chapel Hill NC

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


[Tutor] useful function or reinventing the wheel??

2011-11-28 Thread Mark Lybrand
I am a habitual wheel re-inventor, so it would not surprise me, but I made
this little function that I was kinda proud of (seeing that I have only
been learning python like a week now):

It just takes a directory and checks to see if all the directories,
sub-directories exist and creates them if they don't:

def insure_exists_dir(dir):
  grow_path = [dir]
  while not os.path.ismount(grow_path[0]):
part_tuple = os.path.split(grow_path[0])
grow_path.insert(0, part_tuple[0])

  del(grow_path[0])
  while grow_path:
if not os.path.exists(grow_path[0]):
  os.mkdir(grow_path[0])
del(grow_path[0])
  return(dir)


Opinions?  What should I really be using?

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


Re: [Tutor] pass tuples to user defined function(beginner)

2011-11-28 Thread Dave Angel

On 11/28/2011 11:25 PM, bob gailer wrote:

On 11/28/2011 12:47 PM, James Reynolds wrote:



On Mon, Nov 28, 2011 at 12:32 PM, Mayo Adams > wrote:


I am trying to pass a set of tuple strings from a file to a 
function I

have defined.  Each tuple is on a separate line, and looks something
like this:
 ('note',2048)



As already pointed out - this is a string (a representation of a 
tuple), not a tuple.


Your code must parse the string to extract the string representations 
of the values, then convert as needed to the desired Python values.


Tasks like this are not trivial.

Using eval as already noted is the easiest but not the best solution.

Perhaps we should back up and ask the overall objective of the 
program. Where did this file come from? Could we store the data in 
some other (easier to parse) manner?


This file came from the OP's other thread, "Re: [Tutor] write list of 
tuples to file (beginner)"  At that point, he didn't say what the file 
was for.
If each line will always contain a string literal and an integer 
literal then the simplest encoding is:

note 2048

the program then is:

for line in file(path):
  val1, val2 = line.split)
  findindex(val1, int(val2))


Well, this also assumes the string has no whitespace in its internals.

As i said in my last response, the first thing that's needed is a 
complete spec on what these arguments might be.  We have an example of 
1, that happens not to have any quotes, commas, spaces or anything else 
interesting in the string.  And the number happens to be an integer.  
can we assume much?  Not really.


--

DaveA

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


Re: [Tutor] useful function or reinventing the wheel??

2011-11-28 Thread Dave Angel

On 11/28/2011 11:30 PM, Mark Lybrand wrote:

I am a habitual wheel re-inventor, so it would not surprise me, but I made
this little function that I was kinda proud of (seeing that I have only
been learning python like a week now):

It just takes a directory and checks to see if all the directories,
sub-directories exist and creates them if they don't:

def insure_exists_dir(dir):
   grow_path = [dir]
   while not os.path.ismount(grow_path[0]):
 part_tuple = os.path.split(grow_path[0])
 grow_path.insert(0, part_tuple[0])

   del(grow_path[0])
   while grow_path:
 if not os.path.exists(grow_path[0]):
   os.mkdir(grow_path[0])
 del(grow_path[0])
   return(dir)


Opinions?  What should I really be using?

I couldn't follow your code, but finally concluded that it's trying to 
create a directory, creating the directories parents also if they don't 
exist either.  It would be much simpler if written recursively, but 
there's no need.


Check out os.makedirs(), and see if it meets your needs.   (that's 
makedirs() function, in the os module)




--

DaveA

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


Re: [Tutor] useful function or reinventing the wheel??

2011-11-28 Thread Mark Lybrand
>
>
>>  I couldn't follow your code, but finally concluded that it's trying to
> create a directory, creating the directories parents also if they don't
> exist either.  It would be much simpler if written recursively, but there's
> no need.
>
> Check out os.makedirs(), and see if it meets your needs.   (that's
> makedirs() function, in the os module)
>
>
Okay, so I guess commenting is in order :)  "It was hard for me to write
it, so it should be hard for you to read it." comes to mind.

And I will probably try to write it recursively based on your suggestion,
even though long term, I will just make use of os.makedirs, since that was
what I was re-inventing.

thanks

>
>
> --
>
> DaveA
>
>


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


Re: [Tutor] useful function or reinventing the wheel??

2011-11-28 Thread Dave Angel

On 11/29/2011 12:19 AM, Mark Lybrand wrote:




  I couldn't follow your code, but finally concluded that it's trying to

create a directory, creating the directories parents also if they don't
exist either.  It would be much simpler if written recursively, but there's
no need.

Check out os.makedirs(), and see if it meets your needs.   (that's
makedirs() function, in the os module)



Okay, so I guess commenting is in order :)  "It was hard for me to write
it, so it should be hard for you to read it." comes to mind.

And I will probably try to write it recursively based on your suggestion,
even though long term, I will just make use of os.makedirs, since that was
what I was re-inventing.



You're welcome.  I'd look forward to seeing your rewrite, and whether 
it's really shorter and more straightforward.


Another advantage is doing less disk I/O if you start by trying the 
requested directory directly, and only recursing to parents if you can't 
make the requested directory.


I took a quick stab at it  (ask me later for mark.py)  and it wasn't as 
straightforward as I expected.  The main problem comes down to how to 
define the base case.  I think you might have the same problem also. 
You assume that you can safely go back to the mount point.  But if the 
path given is relative, you have to allow for that as well. Perhaps a 
call to os.path.abspath is in order.  I also think that ismount() might 
not be legal on Windows, if you care about that.


Also, we have to worry about what happens when one of the directories 
cannot be made for reasons unrelated to the syntax of the string.  For 
example, the user might not have write permissions for one or more of 
the directories.  In fact, the user might not have read permissions either.


--

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