Re: [Tutor] new function and a 3 line program not working

2004-12-03 Thread Alan Gauld

> I thought that the '.py ' in this import statement would make the
> interpreter think that newline was a package and therefore try to
recognize
> py as a module in the newline package.
>
> from newline.py import newline

Quite right it should have been

from newline import mnewline!

oops, sorry.

Alan g.


___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help

2004-12-03 Thread Alan Gauld

> I need to know how to run another module through one what is the
command do
> I have to include a path name and if there is any special way I have
to save
> the file

See my tutor for more info on modules and functions.

The short answer is that if you create a module
(ie a python file) and put the code into functions, then you
can impot the module and execute the functions.

Any code that is not in a function will be executed when you
import the module. Thus:


###
# File: mymodule.py
print 'welcome to my module'

def myfunction():
print 'this is my function'

def another():
return 42
##

#
# file myprogram.py
import mymodule

mymodule.myfunction()
print mymodule.another()
mymodule.myfunction()
##

When I run myprogram.py I get:

welcome to my module
this is my function
42
this is my function

The first line gets printed by the import statement,
the second,third and fourth by the function calls.
Notice that the first line can only be generated once
but the functions can be used as often as you like.
So the best course of action is to put all the module
code into functions and you can access those as and
when you need them.

Notice too that the module is just a regular python file,
there is nothing special needed to make it "a module".
Provided it is in the same folder as your program, or
anywhere in pythons search path (sys.path) python will
import it without need for any path specifications etc.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Creating & Handling lots of objects

2004-12-03 Thread Alan Gauld

> I've written a class, with some methods. I then want to be able to
call
> the class repeatedly, to create some objects. The number of objects,
and
> some of their initialisation parameters need to be specified later
(i.e.
> at run-time).

Not quite sure what you mean by the last bit but I'll come
back to that...

> When I generate all these objects, how do I keep track of them.

Check out the OOP topic in my tutor, it discusses this within the
context
of a bank account example - how to manage large numbers of account
holders.

The short answer is put them in a list or dictionary.

> but this is obviously not scaleable. If I use a list, I can do:
> ...
> but then I have to search the list (MyObjects) for the object where
> Object.name="a".
>
> The only other option seems to be finding objects via their hash
codes,
> which I'm sure isn't right

Why not? After all Python uses dictionaries(hashes) for all of its
variables, and every object is an instance of a dictionary which
holds all the attributes... This is exactly the kind of thing hashes
are for.

As for using different initialisation parameters. Do you mean
different types of values or just different values?

If the former - like Java/C++ having multiple constructors - then the
best approach is to use named parameters - look at how Tkinter does
this as a good example.

class C:
 def __init__(self, a=None, b=None, c=None, d=None)
   # do stuff here

now provided you can think up some suitable default values you can
init your object with any combination of a,b,c and d you like like
this:

c1 = C(a="fred",d=42)
c2 = C(b=27,d=0)
c3 = C(a="joe", c=[1,2,3])

and so on...

I'm not sure if thats what you wanted but if not post again to
clarify...

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Creating & Handling lots of objects

2004-12-03 Thread Alan Gauld
> Although I have never done so, I believe you can also 
> store/manipulate objects in a database.

You can but its a lot slower than memory - but a lot more 
scaleale too!

> Has anyone ever worked this option?

Yes, lots of times. In fact most large scale projects will 
need to save objects to some kind of persistent store eventually.
This could be a text file (see my tutor for an example) or a 
full blown database.

Foor simple persistence the pickle and shelve modules are useful.
If you need to do random access and searches then a full RDBMS 
like MySQL will be better.

An Object database might also work - I believe Zope has one 
but I've never used it, nor even read up on it...

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python regular expression

2004-12-03 Thread Alan Gauld
Have you looked at the ConfigParser module that was mentioned earlier
today?
Your file fits its format exactly...

But regular expressions can be used, try the intro in my tutorial,
or the excellent HowTo on the Python web site...

Alan G.


- Original Message - 
From: "kumar s" <[EMAIL PROTECTED]>
To: <[EMAIL PROTECTED]>
Sent: Friday, December 03, 2004 9:23 PM
Subject: [Tutor] Python regular expression


> Dear group,
>
> I have a file with 645,984 lines.  This file is
> composedcompletely of bocks.
>
> For e.g.
>
> [Unit111]
> Name=NONE
> Direction=2
> NumAtoms=16
> NumCells=32
> UnitNumber=111
> UnitType=3
> NumberBlocks=1
>
> [Unit111_Block1]
> Name=31318_at
> BlockNumber=1
> NumAtoms=16
> NumCells=32
> StartPosition=0
> StopPosition=15
> CellHeader=X Y PROBE FEAT QUAL EXPOS POS CBASE PBASE
> TBASE ATOM INDEX CODONIND CODON REGIONTYPE REGION
> Cell1=24 636 N control 31318_at 0 13 A A A 0 407064 -1
> -1 99
> Cell2=24 635 N control 31318_at 0 13 A T A 0 406424 -1
> -1 99
> Cell3=631 397 N control 31318_at 1 13 T A T 1 254711
> -1 -1 99
>
>
>
> [Unit113]
> Name=NONE
> Direction=2
> NumAtoms=16
> NumCells=32
> UnitNumber=113
> UnitType=3
> NumberBlocks=1
>
> [Unit113_Block1]
> Name=31320_at
> BlockNumber=1
> NumAtoms=16
> NumCells=32
> StartPosition=0
> StopPosition=15
> CellHeader=X Y PROBE FEAT QUAL EXPOS POS CBASE PBASE
> TBASE ATOM INDEX CODONIND CODON REGIONTYPE REGION
> Cell1=68 63 N control 31320_at 0 13 T A T 0 40388 -1
> -1 99
> Cell2=68 64 N control 31320_at 0 13 T T T 0 41028 -1
> -1 99
> Cell3=99 194 N control 31320_at 1 13 C C C 1 124259 -1
> -1 99
>
>
>
>
>
> I have a file with identifiers that are found in the
> first file as :
> Name=31320_at
>
>
> I am interested in getting lines of block that are
> present in first to be written as a file.
>
> I am search:
>
> search = re.search ["_at")
>
>
> my question:
> how can i tell python to select some rows that have
> particular pattern such as [Name] or Name of [Unit].
> is there any way of doing this.
> please help me
>
> thanks
> kumar
>
> __
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com
>
>

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] eval and exec

2004-12-04 Thread Alan Gauld
> I'm having trouble understanding the difference between eval and
exec.

eval evaluates an *expression* - that is something that returns a
value.

exec executes a piece of code, it need not return a value.

eval is slightly safer than exec (but not much).

Some examples:

print 'hello'   # use exec for this

6+7-9/3# use eval for this

myfunction(42)   # use eval for this

to make eval useful you need to assign the result to a variable:

res = eval('6+7-9/3')

but exec is just executed on its own:

exec('print "hello"')

Both are extremely dangerous functions from a security
and maintenance/reliability pouint of view and should be
used very rarely.


Was there anything more specific you wanted to know?

HTH

Alan G.

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Global presets ?

2004-12-04 Thread Alan Gauld
> I have some common data directories, like
>
> /home/dave/mygg/gg1.3/logs
> /home/dave/mygg/gg1.3/data
> /home/dave/mygg/gg1.3/datacore
> /home/dave/mygg/gg1.3/arch_data
>
> which increasing numbers of scripts are accessing.

have you considered making the root directory an environment variable?
That way you can read the value (os.getenv) at the start of the
script.
And if you ever need to move the structure you can simply change the
environment value. It also means different users can use their own
structures by defining their own environment value...

> Somewhere I read about importing a script to define common globals
for
> all the scripts that import it.
>
> I tried this, and failed - the variable was only valid for the
module,
> to be expected really :)


# File myvars.py
value1 = 42
value2 = 'spam'


#
# File: prog1.py

import myvars

localvar = myvars.value1
myvars.value2 = 'Alan'


##
#  File prog2.py

import myvars

newvar = myvars.value2

print myvars.value1 - 27
##

Does that help?

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple RPN calculator

2004-12-04 Thread Alan Gauld
> I am new to programming and so don't know "anything" much, yet.
> I am having problem with implementing a simple RPN calculator
> in python.

I'm not surprised. While an RPN vcalculator is one of the easier
calculators to build its not exactly trivial. It sounds like the
kind of thing an ambitious (or optimistic?) teacher might set
for homework... Would I nbe right?

> to make it request for input(s) of say a simple math like  "1 2 3 4
5 + - * /".

Look at raw_input()

But if you are that much of a beginner you need to take several
steps back and try one of the tutorials, they all cover raw_input
fairly early on...

And finally doesn't RPN put the operators first? Or is it me thats
getting confused fromtoo much Lisping recently?...

> Help please with any suggestions or any other better and easier
> way of implementing a RPN calculator.

Python is a fine place to start building RPN calculators. But thee
are so many available that I van't help suspecting homewoprk here,
and we can only offer limited guidance in that case.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Address book sort of

2004-12-04 Thread Alan Gauld
> then retrieve the data when run again. Basically, I'm trying to
simulate
> a simple address book (well not really for the datas are just names
for
> now)

I use an address book as an example program in the early stages of
my tutorial. The finished(well sort of) program is in the modules
& functions topic.

I don't use pickle though since it is very Python specific.

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Global presets ?

2004-12-04 Thread Alan Gauld
> >myvars.value2 = 'Alan'
> >
> >
> >
> Never thought of setting 'myvars.value2 = 'Alan''  I guess this
would
> just set the variable in the myvars namespace since it could not
change
> myvars.py itself.

Absolutely correct and why I put the example in - but I forgot
to point out the hidden gotcha! Glad you figured it out ;-)

> >print myvars.value1 - 27
> >
> >
> Have I misunderstood, should this not be 42 ? Typo or me not
understanding ?

value1 is 42 so the print statement prints 42-27 => 15

Just proving that you can use the values any way you like,
including in expressions.

Alan G.

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to select particular lines from a text

2004-12-04 Thread Alan Gauld
>  This is continuation to my previous email with
> sugject line "Python regular expression".  My text
> file although, looks like .ini file, but it is not. It
> is a chip definition file from Gene chip.  it is a
> huge file with over 340,000 lines.

Thats big but by no means outragous, I have processed files with 
over 1 millionlines before. And they were much more complex format 
too - over 10 fields in a pseudo CSV format.

It took a few minutes but not not hours.

Try it, if there's a real problem think about fixing it. But it 
may just work... On a modern PC you will probably even have enough 
RAM to get it all into memory - less than 30M I'd guess!


Alan G.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Accuracy of time.sleep()

2004-12-04 Thread Alan Gauld
> (and yes, there are some versions of cron for Windows -- I don't
know
> where they can be found, but I used one called nnCron Lite at my job
> this summer)

And on XP/Win2K you can use the 'at' command to schedule jobs.
The only case for sleep() is if you need to maintain context in
memory (maybe because some other interrupt can come in too).

Even then sleep is not, as you discovered absolutely accurate, it
depends on things like CPU load. Instead I'd set sleep to wake me
up a few minutes early (10 minutes say?), then run a new fuction
to calculate the time to go and sleep for the shorter period, then
for the last few seconds sleep for a few seconds at a time and
check time each wake up. Of course even that only gets you within
a second or two.

Other options are to use the system clock and interrupts or signals.
But if possible go with cron or at - thats why thety are there!

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Accuracy of time.sleep()

2004-12-04 Thread Alan Gauld
> It must be cummulative error over 10s of thousands of seconds.

Just so, and depends on howm many other processes are running,
how busy the CPU is etc.

> bodge (& cron or at are better) but I suppose I could calculate
seconds
> to 8:05 sleep(seconds*0.95), re calculate secs to 8:05
sleep(seconds)
> which should reduce the error to almost zip.

Thats the approach I suggest in my otther email :-)

Alan G

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple RPN calculator

2004-12-05 Thread Alan Gauld
> > And finally doesn't RPN put the operators first? Or is it me thats
> > getting confused fromtoo much Lisping recently?...
>
> Nope, RPN calculators (such as the HP48GX, IMHO the best calculator
> ever made) require you to input the operands first, then the
operators.

Yeah, you are right. I had a Novus RPN calculator in the 70's and
it worked exactly as you describe. And yes, it was a lot faster
than infix notation. Too much Lisp confusing my mind :-)

Alan g

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] eval and exec

2004-12-05 Thread Alan Gauld
> dictionary of database instances, dbtables, keyed on table name,
> and I want a general way of creating variables with the name of
> the table so I'm not accessing the dictionary.  Would something
> like this work:
> 
> # dbtables is already built
> for table in dbtables.keys():
> exec("%s = dbtables['%s']" % (table, table))

It will create a lot of variables named after your tables.
The problem with this approach is how will the code that comes 
after this dynamic naming know about those names which don't 
exist when you wrote it? 

You can only access variables that you know exist, but if 
you know they will exist you don't need to do the dynamic 
naming thing...

So this approach is only useful where you know a lot of 
names in advance but don't want to go to the hassle of 
explicitly initialising them all before using them. The cost
of this small time saving is the use of a potentially 
dangerous exec call.

This kind of dynamic naming scheme is only really useful 
in some kind of interactive session, when you run a program 
thats written in advance it is much better to put dynamically 
created objects into a collection IMHO.

Alan g.


___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] eval and exec

2004-12-05 Thread Alan Gauld
> I was trying to eval("import %s" % something).
>
> exec("import %s" % something) works just fine and now I understand
why.

But much better to use the __import__() function for doing that
if possible... Or simply importing all the modules you might need
at the beginning, its not a big overhead...

Alan G.

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Real time reading

2004-12-05 Thread Alan Gauld
> send more than 5 mails pr minute (spams) and if so, get Python to
send a
> warningmail to the mailmaster.
>
> How would I in the best way read the log?

Using the standard file methods...

> To open the file and close it
> every second sounds like a bad idea?

It would be but you don't need to, you could read it every
5 minutes, every 15 minutes or even every hour. So long as
the messages are timestamped - and in a log file they usually
are - you can simply record where you got to last time,
search down to that point and read forward from there. In fact,
never mind time stamping, you could just find the position
in the file using tell(), and the do a seek() that would
be much faster...

The frequency that you analyze the file will be governed
by how often you need to notify the administrator - and
he/she can't possibly read messages coming every second!
(in fact in the event of a DoS attack your alerts would
probably lock up the admins console - and make you almost
as unpopular as the attackers!)

Once every 5 minutes is probably a reasonable time interval.
But why not make the number of minutes you check the file a
configurable item, either a startup parameter or an environment
variable, ir even store in a config file (seems to have been a
lot about these this week :-)

> Is there some function to analyze the
> file, and automatically extract additions to the file?

If you store where you got to last trime and use seek()
to get back there you can just use read() (or readlines)
to grab the new bits on one go, then use tell() to see
where the end is and store that (that config file again?)

Analyzing the contents is something you will need to
write but that's straight string manipulation (I assume
it is a text file!)

HTH

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Can i define anywhere on file object function for reading arange of lines?

2004-12-05 Thread Alan Gauld
> Is there any function where I can specify to python
> buit-in function to select specific line (such as
> starting from segment: page 22 TO the next new line)
> instead of the whole lines until EOF. 
> e.g.:
> a = readlines (From , TO )

Not quite, but you can do:

readlines()[from:to]

With the disadvantage that the whoile file gets read 
into RAM before the slicing takes place - but then it 
gets garbage collected again pretty well immediately...

HTH,

Alan G.

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] eval and exec

2004-12-05 Thread Alan Gauld
> And I can't see the security problem, unless there's a security
> problem already, like if I allowed incoming email to dictate the
> parameters that I send through the socket.  The email provides data
> for argv[1:] but argv[0] is hard-coded.
>
> And I don't see how web traffic can get there at all.

You can generate a CGI call b by typing the GET string straight into
the address bar of the browser. If a smart user realises that some
of the parameters are being interpreted they can (and often will)
try to fake what the page genersates, this could involve putting
python commands, such as 'import os;os.system("rm -f /")' into
the escape string...

Equally if you embed Python in a program and allow users to type
strings whoich are then exec() or eval()'d they could type a
similar os.system() command. Or they might use print and dir
to find variable names and manipulate those.

Even in a config file, if its plain text a hostile (or just
mischievous) user could add a dangerous line and when you try
to exec it bad things happen. Any time you allow users to
influence what code runs you have potential for trouble
- that is the principle behind all these "buffer overrun"
security errors as well as all the script kiddie attacks
- MS allows Outlook to run scripts when mail is open, if
those scripts are harmful we have a virus!

> If we had real users with login rights, then they could get to the
> interpreter and wouldn't need my little daemon to wreck havoc -- if
I
> had my persmissions wrong.

But by opening access to exec() you effectively give your users
access to a PYthon session within *your* login rights (or root
or the web user etc)

Its not a trivial thing to exploit but it can be done and
either accidentally(*) or deliberately bad things can result.

(*) Recall that one of the most common user support issues on
Unix systems is people typing "rm / foo" with a space instead of
"rm /foo". The first one (attempts to) delete the root
directory - oops!

Alan G.

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] eval and exec

2004-12-05 Thread Alan Gauld
> And how can __import__ be safer?

Safer because it is limited in what it can do, import a file.
The file must exist in the python path, so its much harder for
the user to do something bad - they have to create a new file
with malicious code in it and insert it into the python path
and then get that filename string into your program. Its much,
much easier when you can type malicious code directly

> And couldn't he import untrusted code?

Yes, but he has to get the code onto your machine first!

> in it?  And what about the apply() function?  Aren't all of these
the
> same open door?

Again apply calls a pre-existing function, the attacker has
to actually create the function and get it into your namespace
before calling it.

All of these are potentially dangerous, you are right, but
they are second order dangers because they
1) have a clearly delimited scope of what can be done
2) the string executed is not directly executed, it must fit a
   specific form and is therefore more easily monitored for
   "sanity" before execution.
3) The code that is executed must already exist.

> I love the exec() call.  I love the idea of code that makes and
execs
> code.  I'll make myself obsolete.  :^)

It is very powerful, and self modifying code is indeed fun to play
with (albeit surprisingly difficult to find a genuine use for!)
But it must be used in full cognisance of the security dangers.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] eval and exec

2004-12-06 Thread Alan Gauld
> > - MS allows Outlook to run scripts when mail is open, if
> > those scripts are harmful we have a virus!

That is (was, they've improved it a lot) the number one cause
of script kiddie virii. Simply viewing a mail message in the 
preview pane was enough to trigger a script. They have 
improved security greatly in the recent patches though.

But HTML mail has similar issues. If someone handcrafts an HTML
message with some Javascript code then you are relying on your 
browsers sandbox technology to protect you. And if its Windows 
and WSH is enabled the script can read/write the registry...

The ability to script documrnts is powerful, but potentially 
dangerous, just like eval/exec (which are how such 
capabilities are typically implemented!)

Alan G.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] about recursion code

2004-12-07 Thread Alan Gauld
> def selection_sort(lst,start,end):
> """sort the lst from selection start to end"""
> if len(lst)==1:
> return lst
> elif lst=="":
> return ""
> else:
> return lst[:start]+selection_sort(lst,start+1,end)

This doesn't appear to do any actual sorting?
And the recursive call always passes in the 
original list so I assume it never terminates?

Alan G.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 2.3.5 out in January??

2004-12-07 Thread Alan Gauld
> the 2.3 line.  It's *possible* that volunteers for 2.3.6 will
appear.
> That would be unprecedented, but not impossible ...
> end TP's post
>
> I ask here because I'm sure it's a newbie question. It's got me
wondering
> if Microsoft is still working on Windows 3.1..  ;-)

Its not at all unusual for commercial vendors to support an old
line of releases long after the new version goes out. Patches
for Windows NT4 are still potentially available up till the end
of this month... So not 3.1 but NT4 and Win2000 are both currently
supported and developers are working on them - but usually only
for bug fixes etc.

Part of the reason for this is that many users - particularly
in big companies - rely on automated delivery mechanisms to
upgrade their applications "on the fly" and it takes time to
develop the delivery configurations. Also versions might require
hardware upgrades- extra RAM for example - and the cost of those
upgrades may not be available in this years budget so you have
to wait till next year... In other cases its legacy code - for
example we have delayed moving some of our PCS off NT4 because
they use bespoke hardware that needs an ISA bus - which isn't
supported in XP... The cost of redeveloping the hardware has
proved extortionate!

So yes, vendors do support old and new in parallel. Typically
for two full releases or two full years depending on which is
soonest...

Alan G.

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Connecting to interactive program

2004-12-07 Thread Alan Gauld
> Has anyone ever tried to send commands to a running interactive
python
> session from, say, the command line or another app?

This isn't too hard if you use stdin/stdout. But it does depend on
what you mean by send commands from the command line. If the process
is a daemon for example and it isn't stopped waiting for input then
its going to be hard! If its waiting on a socket then its a standard
ipc issue.

> If so, please let me know how you achieved this.

Assuming you mean something that normally interacts with a human
user then you can use things like expect to simulate user input.
Is that what you mean?

Alan G.

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Connecting to interactive program

2004-12-07 Thread Alan Gauld
> I would like to create a python script that would function as
follows.
>
> ./script.py intpy
>
> Where the scipt setsup the comminication to 'intpy' which would be
an
> interactive python sessions (or some other interactive program).

OK, two steps back here I think.

Can you show us an imaginary user session explaining just what is
happening.

> ./script.py intpy

That is the user running a python program called script.py which
is taking a single commandline argument, the string "intpy".

script.py can read intpy via the sys.argv list. But what exactly
does intpy represent? And where does the "other program" that
you refer to come into the picture?

You will need to explain your requirements in a bit more detail
I think.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Removing list elements - was:: [Tutor] Printing two elements in a list

2004-12-07 Thread Alan Gauld
> I know I am wrong here because I do not know how to
> search and remove an element in a list. Can any one
> please help me. 

This is what the filter function is for...
But you can use list comprehensions too:

[element for element in list if element not foo]

so in your case:

lst = f.readlines()  # get file into a list
lst = [line for line in lst if not line.startswith('Name=')]

Or something very similar. For more control use a regular
expression to filter the lines

Alan G.

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Connecting to interactive program

2004-12-07 Thread Alan Gauld
CC'd back to tutor list.

- Original Message - 
From: "Vincent Nijs" <[EMAIL PROTECTED]>
To: "Alan Gauld" <[EMAIL PROTECTED]>
Sent: Tuesday, December 07, 2004 10:56 PM
Subject: Re: [Tutor] Connecting to interactive program


> Alan,
>
> Sorry if I was unclear.
>
> I would like to have python program that will (1) start an
interactive
> session of python, r, matlab or some other program and (2) allow the
user to
> pass commands to that interactive session from a shell command line
(e.g.,
> echo 'x=3'). If the python program opens the interactive session
that will
> also allow direct input into the interactive program by the user.

That sounds pretty much what pyexpect will allow you to do.
Certainly plain ol' expect does that kind of thing. Basically
anything that reads stdin and displays on stdout or stderr
can be driven by expect and therefore by pyexpect.

> If I can get the interactive program to accept commands from a shell
command
> line I can figure out how to send commands from my favorite editor
(VIM).

Now that might be interesting :-)
I assume you have the version of vim that uses python as its
scripting language?

Alan G.

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Removing/Handing large blocks of text

2004-12-08 Thread Alan Gauld
> I'm trying to do this with the re module - the two tags looks like:
>
> 
> ...
> a bunch of text (~1500 lines)
> ...
> 
>
> I need to identify the first tag, and the second, and
unconditionally
> strip out everything in between those two tags, making it look like:
>
> 
> 

A very simplistic approach uses a flag:

atTag = 0
f = open(...)
while not atTag:
line = f.readline()
if line == '':
  atTag = True
  break
outFile.write(line) # + \n, I can't remember...
while atTag:
line = f.readline()
if line == '':
   atTag = False
while f:
outfile.write(f.readline())

This flag approach is sometimes called a sentinal...

I'm sure somebody can find better ways of doing this but I'm
too tired to bother right now! :-(
The sentinel approach will work...

Alan G.

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "TypeError: 'int' object is not callable"??

2004-12-08 Thread Alan Gauld
> Note that SOME languages use () for call. There are other call
constructs,
> such as:
>
> DO function WITH parameters (FoxPro, similar in COBOL)
>
> function parameter   or   parameter1 function parameter2 (APL)

And in Smalltalk:

object message: parameter1 : parameter2 :
parameter3

Or as an example of a message and one descriptor.

myArray put: foo at: 5

The array method is known as   "put:at:"

No parens to be seen (they have a completely different meaning in
Smalltalk)

Alan G.

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] MemoryError

2004-12-08 Thread Alan Gauld
> Traceback: 
> 
> Line 39: seg=codeSt[element:endInd+len(endStr]
> MemoryError
> 
> Hehe. Helpful, no?

Sometimes seeing the whole traceback gives clues as 
to whats throwing the wobbly, without the full stack 
its hard to tell.

However before worrying about that I'd add a print 
statement to print out all those values:

codeStr
element,
endInd
len(endstr)

I suspect the memory error might be an indexing error, 
running off the end of the string or similar... But lets 
see those values at the point of failure.

For your own benefit it might be easier just to use the debugger, 
just set a breakpoint on the line then check the values when the 
debugger stops...

Alan G.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help matching elements from two lists and printingthem

2004-12-09 Thread Alan Gauld
> >>> out = open('sa_int_2.txt','w')
> >>> for ele1 in range(len(spot_cor)):
> x = spot_cor[ele1]

replace this with

for x in spot_cor:

> for ele2 in range(len(spot_int)):
> cols = split(spot_int[ele2],'\t')

and this with

for item in spot_int:
   cols = split(item,'\t')

> y = (cols[0]+'\t'+cols[1])
> if x == y:
> for ele3 in spot_int:
> if y in ele3:
> out.write(ele3)
> out.write('\n')

But that doesn't fix the problem, it just simplifies the code!

> On top of this this process is VERY SLOW on high end
> server too. I think its just the way it is to deal
> with string processing. 

It looks like you have 3 (4?!) levels of nested loops 
(altho' I can't really tell because the indentation got lost) , 
and that is usually going to be slow!

> As you asked I am all parsing out the pieces for a
> tab-delimitted text. I can get the values as CSV
> instead of tab delimitted. But what is the way using
> CSV to deal with this situation. 

There is a CSV module which means you have standard, tested 
code to start with... Sounds like a good place to start from.

Alan G.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to get the 2 complex cube roots of 1?

2004-12-09 Thread Alan Gauld

> My trusty $10 Casio calculator tells me that the 3 cube roots of 1
are:
> 1, (-.5 +0.866025403j), and (-.5 -0.866025403j), or thereabouts. Is
there
> a way to do this in Python?

Sorry the power operation in Python will only return 1+0j
You need to dig out the math books and write a function
to return all the roots. Or hunt google to see if somebody
else has already done one...

Alan G

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] CGI Video collection application File I/O troubles

2004-12-09 Thread Alan Gauld
> When I run the script from my bash shell it creates the videodb
> database file, but when I run it from the browser it doesn't
> create no file whatsoever.

This is usually due to wrong file permissions.
The script runs under the web server and this usually 
has restricted access for security reasons. You need to 
get your sys admin (who may be you! :-) to set things 
up so your script can write OK.

Alan G.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Difference between for i in range(len(object)) and for i inobject

2004-12-09 Thread Alan Gauld
> Here is my code:
> >>> spot_cor=[]
> >>> for m in cor:
> ... cols = split(cor,'\t')

You are splitting the list not the item

  cols = split(m, '\t')

Better to use a meaningful name too:

for line in cor:

would probably have made the mistake more obvious.

> However, when I tried that using some data, as
> demonstrated above, I get error because append method

No its the spil method that doesn't exist and that 
was because you were passing the list instead of 
the object.

Once you get used to the "foreach" semantics of "for"
it really is a better way of working than messing 
around with indexes.

Alan G.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Difference between for i in range(len(object)) andfor i in object

2004-12-09 Thread Alan Gauld
> Personally I am getting weary of a lot of requests that to me seem
to come
> from a lack of understanding of Python..

To be fair that is what the tutor list is for - learning Python.

> Would you be willing to take a good tutorial so you understand
> basic Python concepts and apply them to your code.

But as a tutor author I do agree that I am often tempted
(and sometimes succumb) to just point at the relevant topic
in my tutorial. Particularly since the latest version tries
to answer all of the most common questions asked here, but
still they come up...

> I also despair that you don't seem to benefit from some of our
suggestions.

And this too can be frustrating but sometimes it is the case
that the "student" simply didn't fully appreciate the
significance of what was offered. I'm feeling generous tonight!

:-)

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Capturing Logfile data in Windows

2004-12-09 Thread Alan Gauld
> I have a closed-source application which creates log files. I'd like
to
> capture this logfile data as it is crated, and do clever things with
it!
>
> Is this possible? I guess it must be, because there are "tail" type
> utilities for Windows...

Depends on whether the output goes to stdout or stderr or a hard coded
file. Usually log files are hard coded so you need to write a tail
like
utility. You could do this but why not just download a free one such
as that from cygwin?

If you must write your own start off by looking at the C source code
for the standard Linux/Cygwin tail program to see how they do it.
Its probably easy to convert that to Python and safer than
guessing the best approach...

Alan G.

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PDF and Python

2004-12-09 Thread Alan Gauld

> Hey there. Does anyone know of a way to output PDFs with python? I
have some
> data that I have processed from a series of textfiles that I would
like to
> provide PDF format reports for..

I can't recall what its called but a couple of years ago I found a
module on the Parnassus site for processing PDFs. It was really for
extracting data from a PDF but it might be able to write them too.

HTH,

Alan g.

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] maximum value in a Numeric array

2004-12-10 Thread Alan Gauld
> I am trying to get the maximum value in a 2-D array.  I can use max
but it
> returns the 1-D array that the max value is in and I then I need to
do max
> again on that array to get the single max value.
>
> There has to be a more straightforward way...I have just not found
it.
> I could also flatten the array to 1 D first then do max but the
array I am
> going to be working with is fairly large.

Two max() calls seems pretty straightforward to me!
It probably is possible to be slightly more efficient, but you will
have
to look at every value in the array at least once whatever you do.

The simple brute force approach is probably the best here:

# NOTE: untested code...
def maximum(matrix):
   max = None # not 0 to cope with negative matrices
   for col in matrix:
  for elem in col:
 if not max or (elem > max): max = elem
   return max

This only touches each element once and you can't break out till
the end because you don't know that the last elemement won't be
biggest.

However it might be possible to make it faster by sorting the
colums and just comparing the first elements. This is because
the sort will be in C rather than Python... But premature
optimisation would be pointless if the above works...

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Complex roots

2004-12-12 Thread Alan Gauld
> Are these "numerical approximation methods" pythonically possible?
>

Yes and that's how they are normally found - not necessarily with
Python,
but by applying computer simulations of the equations. Generally you
calculate values in ever decreasing increments until you get enough
accuracy. eg you discover a zero crossingh between 3 and 4, then
between 3.3 and 3.4 then between 3.36 and 3.37 and so on...

Caveat:
You also need to look out for double crossings within a single step
change, so don't make the steps too big. And check the number of
roots you expect versus the number you get as an error detection
scheme.

Alan G.

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OT?: how to google just the 2.4 tutorial?

2004-12-13 Thread Alan Gauld

> I know how to limit google search results to a single site, but is
it
> possible to google just one section of a site?

Can't speak for Google but...

> I'd like to be able to search just the 2.4 tutorial,
> http://www.python.org/doc/2.4/tut/tut.html
> Possible? And if so, how to?

Have you tried using the Python site search tool, it covers the
whole of python.org but thats much narrower than a general web
search on Google...

By typing:

tutorial lists

I got the first 5 hits from the tutor...

OTOH By just typing:

python tutorial lists

into Google the first two hits were both from the official tutorial
so plain google works pretty well too.

Alan G.

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] listing all combinations of elements of a list

2004-12-13 Thread Alan Gauld
> def combination(items)
> list = []
> for i in range(0,len(items)):
>for j in range(0,len(items)):

 for i in items:
 for j in items:

Is both shorter and faster - no len() function calls.

Or if you want to use indices:

size = len(items)  # only calculate once, it won't change!
lst = []# don't use builtin function names for
variables
for i in range(0,size)
 for j in range(i+1,size)
   lst.append()
return lst

That saves a lot of len() calls and a comparison.
Also it avoids iterating over the whole list each time.


> My problems with this code being that a) code I write is usually
pretty
> inefficient, b) it doesn't extend to subsets of size > 2, and c) it
uses
> nested loops, which I have gathered from some previous discussions
on
> this list to be less than ideal.

I've tidied up a little but I think nested loops are a necessary evil
in
this case - although somebody is sure to prove me wrong! :-)

HTH,

Alan G.

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python structure advice ?

2004-12-16 Thread Alan Gauld
> everything was global, how you guys handle a modern structured
> language

Don't worry this is one of the hardest bad habits to break.
You are not alone. The easiest way is to just pass the data
from function to function in the function parameters. Its not
at all unusual for functions to have lots of parameters, "global"
programmers tend to panic when they have more than a couple,
but its not at all bad to have 5 or 6 - more than that gets
unweildy I admit and is usually time to start thinking about
classes and objects.

> I have ended up with my application in several separate directories.

Separate modules is good. Separate directories for anything
other than big programs (say 20 or more files?) is more hassle
than its worth. The files are better kept in a single directory
IMHO. The exception being modules designed for reuse...
It just makes life simpler!

> My problem is that pretty much all the modules need to fix where
they
> are when they exit and pick up from that point later on,

There are two "classic" approaches to this kind of problem:

1) batch oriented - each step of the process produces its own
output file or data structure and this gets picked up by the
next stage. Tis usually involved processing data in chunks
- writing the first dump after every 10th set of input say.
This is a very efficient way of processing large chuinks of
data and avoids any problems of synchronisation since the
output chunks form the self contained input to the next step.
And the input stage can run ahead of the processing or the
processing aghead of the input. This is classic mainframe
strategy, ideal for big volumes. BUT it introduces delays
in the end to end process time, its not instant.

2) Real time serial processing, typically constructs a
processing chain in a single process. Has a separate thread
reading the input data and kicks off a separate processing
thread (or process) for each bit of data received. Each
thread then processes the data to completion and writes
the output. A third process or thread then assembles the
outputs into a single report.

This produces results quickly but can overload the computer
if data starts to arrive so fast that the threads start to
back up on each other. Also error handling is harder since
with the batch job data errors can be fixed at the
intermediate files but with this an error anywhere means
that whole data processing chain will be broken with no way
to fix it other than resubmitting the initial data.

> With my code now running to a few hundred lines
> (Don't laugh this is BIG for me :-D )

Its big for me in Python, I've only writtenone program with
more than a thousand lines of Python wheras I've written
many C/C++ programs in ecess of 10,000 lines and worked
on several of more than a million lines. But few if any
Python programs get to those sizes.

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] am I missing another simpler structure?

2004-12-16 Thread Alan Gauld
> I far prefer the Brian's version, because it lets me set a single 
> breakpoint while I'm debugging, and I can look at the return value 
> before returning it, 

In most debiggers(including Pythons) you can still do that 
with a boolean condition provided the condition does not 
itself contain a function call. Simply evaluate the condition 
in the debugger - eg using the print command.

But if the condition has a function in it this is not wise 
since the function may have side-effects so every time you 
call it may result in a different result.

So my advise is to ony use the 

return 

trick on side-effect free simple expressions, otherwise 
go with the more verbose options.

Same applies to the C ?: operator or the python shortcuts 
using 'and' and 'or'...

Alan G.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python structure advice ?

2004-12-16 Thread Alan Gauld
> Having written this email, it has put my thoughts in order, though
it
> seems a bit cheaty, wouldn't defining all modules that have to
remember
> their internal state as classes be the best bet ?

Its one solution certainly, creeate objects and the objects carry
their state with them. But the problem can be tackled as per my
earlier post without delving into the world of objects.

Alan G.

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Polish translation of my tutor

2004-12-17 Thread Alan Gauld
Are there any Polish speakers on the tutor list who would like 
to check a new version of my tutorial? There are no formal links 
to it yet as there are only a few pages but it can be found at:

http://www.freenetpages.co.uk/hp/alan.gauld/polish/

And any feedback can be sent to me and I'll forward to the 
translator.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python structure advice ?

2004-12-17 Thread Alan Gauld
> For what it's worth, it seems to me to be perfectly normal to have
> classes that are only ever intended to have a single instance.  For
> example, you're never likely to need more than one HTML parser, and
> yet htmllib.HTMLParser is a class...

That's true but the argument for a class in that case is that we
can subclass it for more specialized purposes. If there is only
to be a single instance and it will not be specialized by sub
classing then a simple module will do the job just nicely.

> As Kent said, the main point of a class is that you have a
collection
> of data and operations on that data bundled together.

Dunno if I'd agree that that was the *main point* of classes,
the main point I'd say was to act as a template for objects.
The fact that there might only be one instance is a side issue.

But creating classes that only have a single instance is certainly
OK, after all the original design patterns book by the GoF has a
singleton pattern to ensure that only one oinstance can be created!

> "I want lots of things like this", as it is a declaration of
> modularity -- "This stuff all belongs together as a unit".

So use a module... Python is blessed with both constructs and
we should use whichever is most appropriate. IMHO of course! :-)

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python structure advice ?

2004-12-17 Thread Alan Gauld
> >1) batch oriented - each step of the process produces its own
> >output file or data structure and this gets picked up by the
> >next stage. Tis usually involved processing data in chunks
> >- writing the first dump after every 10th set of input say.
> >
> I see your point, like a static chain, one calling the next &
passing
> data, the problem being that the links of the chain will need to
> remember their previous state when called again, so their output is
a
> function of previous data + fresh data. I guess their state could be
> written to a file, then re-read.

Yes. Just to expand: the typical processing involves three files:
1) the input which is the output of the preceding stage
2) the output which will form input to the next stage
3) the job log. This will contain references to any input data
items that failed to process - typically these will be manually
inspected, corrected and a new file created and submitted at the
end of the batch run.

BUT 3) will also contain the sequence number of the last file and/or
last data item processed so that when the next cycle runs it knows
where to start. It is this belt and braces approach to data
processing and error recovery that makes mainframes so reliable,
not just the hardware, but the whole culture there is geared to
handling failure and being able to *recover* not just report on it.
After all its the mainframes where the really mission critical
software of any large enterprise runs!

As an ex Unix head I learned an awful lot about reliable computing
from the 18 months I spent working on a mainframe project. These
guys mostly live in a highly specialised microcosm of their own
but they have learned a lot of powerful tricks over the last 40
years that the rest of us ignore at our peril. I strongly
recommend that anyone who gets the chance of *a short* contract
in mainframe land, with training, to grab the opportunity with
both hands!

< Steps off soapbox now :-) >

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter questions

2004-12-17 Thread Alan Gauld
> I got some Tkinter related questions for a project that I'm making:
> 1. How to add an image to a button ?

I find the easiest way is to create an PhotoImage object attach
the graphic file(jpg,bmp,gif) to that and assign the PhotoImage
object to the Button.image property. You can "animate" the image
by simply reassigning the file to the underlying PhotoImage onject.

> 2. How can I print text using Tkinter (I want it to be cross
platform,
> so I cant use modules like win32print ) ?

You mean print as in to a printer?
Personally I tend to generate an HTML file and use the
native OS Tools to print that. You can get fancy and
use the native OS priniting libraries but since its
very OS specific I find HTML is easier! OUtside Tkinter
you may well find the GUI libraries have done the cross
platform stuff for you, but not in Tkinter.

> 3. How to I make the program to always open in a full window ?

Define a full window? You mean full screen?
Thats usually better done as a parameter that the user can
set unless there is a very good reason not to. (Personally
I refuse to use any program that insists on opening full screen!)

If OTOH you mean that you don't want the DOS box in the background
thats easy, just rename the .py file to .pyw. But I suspect,
since you talk abouit cross platform you mean full screen.

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.listdir fn

2004-12-10 Thread Alan Gauld
> That is, filename globbing doesn't seem to work. Looks like I'll
have to
> use map/filter to do this.  Is there a better way?

It does if you use the glob module :-)

Python, with batteries included.
But sometimes finding the right battery can be challenging...

Alan G.

>
> Thanks,
> N
>
> -- 
> Nandan Bagchee
>
>
> Patriots don't use Linux.
>
> -- c.o.l.a
>
>
>

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] function that returns a fn

2004-12-12 Thread Alan Gauld

> def getjlistrenderer(opname):
> def listrender():
> # use opname, eg ops=getlist(opname)
> # or set local fn variable
> return renderer;
> return listrender;
> #?or f=listrender(); return f;
>
> Is it really as simple as this?

Assuming your indentation is actually OK then yes, it is
as easy as that.

> books too, but thought I'd get some more pointers as well. Web
searching
> so far only shows lambda, which is one-liner, and that won't do.

Lambda is actually a single *expression* which may cross several
lines. But with nested functions available lambda is the wrong way
to go for higher order programming in Python.

Alan g.


___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hooray! I finished the 'Learning Python for absolutebeginners'

2010-01-09 Thread Alan Gauld


"Tim Goddard"  wrote 


I also figured out how to configure Eclipse IDE to recognize modules.
Apparently in the preferences for each 'project' is a separate
PYTHONPATH.. which is not to be confused with sys.path.  Adding the
appropriate folders to the preferences allows the user to browse
through a module i.e.


I assume you have already installed the PyDev plugin?

I'm currently reading a book on Eclipse (Eclipse Distilled) which has 
turned up many settings and tricks that I was unaware of. It is a 
powerful tool but like all such it takes a lot of learing to get the most 
from it.


Alan G.

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


Re: [Tutor] tk help

2010-01-11 Thread Alan Gauld


"Kirk Vander Meulen"  wrote

I'm working on a program partly to get the hang of gui programming.  I'm 
a

bit puzzled by the behavior of simple dialogs- I wonder why, in the
following code, the second call to tkMessageBox.askyesno always returns
'False' (either 'yes' or 'no' return False!).  If I take out the call to
tkFileDialog.askdirectory(), the second call works as expected
(yes->True,no->False).  I would really appreciate if someone could take a
look at this and tell me what I'm missing.  Thanks,


After converting the imports for Python 3 it worked perfectly for me

 RESTART 




True
True
H:/PROJECTS/Python/Tutor3
True
H:/PROJECTS/Python/Tutor3
 RESTART 






import tkFileDialog,tkMessageBox
addDirectory=tkMessageBox.askyesno('a dialog','Add a directory?')
print(addDirectory)
theDirectory=tkFileDialog.askdirectory()
print(addDirectory)


Any reason why you print it a second time even though there has been no 
change?



print(theDirectory)
addDirectory=tkMessageBox.askyesno('a dialog','Add a directory?')
print(addDirectory)
print(theDirectory)


And the same here?


--
Alan Gauld
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] what is the equivalent function to strtok() in c++

2010-01-11 Thread Alan Gauld


"Dave Angel"  wrote 

If your tokens are separated by whitespace, you can simply use a single 
call to split().  It will turn a single string into a list of tokens.


line = "Now   is the time"
print line.split()

will display the list:
['Now', 'is', 'the', 'time']


And if it's not separated by whitespace you can supply the 
separator, eg a colon:


line.split(':')

For more sophisticated functionality use the re module or a 
specialised parser.



--
Alan Gauld
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] what is the equivalent function to strtok() in c++

2010-01-11 Thread Alan Gauld


"Stefan Behnel"  wrote

For more sophisticated functionality use the re module or a specialised 
parser.


Just a quick note here, "specialised parser" might sound like something 
that's hard to write. It's not.


Good point. I meant one of the many existing parsing packages for
specific purposes such as XML/HTML, csv, configfile etc - or pyparsing
for more general purpose work. I did not mean to write a specialised parser
from scratch, although occasionally that may be needed but usually not.

--
Alan Gauld
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] Tutor Digest, Vol 71, Issue 28

2010-01-11 Thread Alan Gauld


"Make Twilight"  wrote

I am confuse on the text above:
"If you use the 'from import' system, changes made to attrs of the
imported module /won't/ be seen by any other module that imported it.
If you do just an 'import' on a module (or 'import ... as ...'), then
changes made to attrs on the imported module /will /be seen by othe
modules that import it as well.  I hope that is somewhat clear. ;)"

I had tried to simulate this situation:
 Module a---
#!usr/bin/env ptyhon
#Module  a.py
name = "a::name"

Module b
#usr/bin/env python
#Module  b.py
form a import *

while Ture:   # True?
   blah = rawinput("input something:")
   print a.name


This should not work because you have not imported "a" only "name" from a.
This should therefore say

print name



Module c
#usr/bin/env python
#Module c.py
import a

while Ture:
   blah = rawinput("input something:")
   print a.name


But this is OK.

when i excuted b.py,c.py and modified  the attr name = "a::newname",but 
b.py

and c.py were still output "a::name".


How did you execute them? There is nothing to change the attributes
here so how did you change them? If you altered the source code of
a after the imports were run then the changes will not be seen.


what's the problem?
does it the right way python  takes?


I'm not sure there is a problem. It depends on how you are conducting
the test and what you expect the answer to be.

Alan G. 



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


Re: [Tutor] Array slices in python with negative step

2010-01-11 Thread Alan Gauld


"vishwajeet singh"  wrote


Thanks for your response but I am still not clear; can you show me the
equivalent of [::-1]  in terms actually specifying start-index, end-index
which gives me reverse of the given arrary.


I don't think you can, you must use the empty value.

In theory you could use -1 except of course -1 refers to the 'e'...

Its a slight anomoly due to the use of negative indexing. You
can do:

'abcde'[0:5]

and get the same as [0:]

But you cannot put any valid value for x in

'abcde[4 : x :-1]

that gets you the full string. You need to use [4::-1]

HTH,


--
Alan Gauld
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] Searching in a file

2010-01-13 Thread Alan Gauld


"Hugo Arts"  wrote


the most obvious answer would be to take a look at the 'next()'
function, that should solve this immediate problem.


This would be nmy advice too, but you need to get an explicit iterator to 
use it.


it = open(.)
for line in it:
   if 'NEW' in line:
   ln = it.next()

etc...


Yet another approach is to abandon the for loop entirely, and use a
while loop combined with the readline method,


I prefer the next() approach.

But a third option is to use a split and apply it to the whole file as
a string thereby breaking the file into as many chunks as start with
a line containing 'NEW'...

data = open().read()
for chunk in data.split('NEW'):
for line in chunk.split('\n'):  # create lines out of the chunks - you 
may not need this

     # process lines till done

Just a thought.

--
Alan Gauld
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] Searching in a file

2010-01-14 Thread Alan Gauld


"spir"  wrote 


But a third option is to use a split and apply it to the whole file as
a string thereby breaking the file into as many chunks as start with
a line containing 'NEW'...


Why not simply a regex pattern starting with "NEW" and ending with '\n'?


Because I understood the OP had to extract the info from 
the lines *following* the one with NEW. You could mess 
around with match object stat positions etc but split seemed a 
much easier solution. 


Alan G

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


Re: [Tutor] Keeping a list of attributes of a certain type

2010-01-14 Thread Alan Gauld


"Guilherme P. de Freitas"  wrote


Here is my problem. I have two classes, 'Body' and 'Member', and some
attributes of 'Body' can be of type 'Member', but some may not. The
precise attributes that 'Body' has depend from instance to instance,
and they can be added or deleted. I need any instance of 'Body' to
keep an up-to-date list of all its attributes that belong to the class
'Member'. How do I do this?


Check the type of the attribute? Using isinstance()?

I'm not sure of the rationale - why it needs to know the type etc
But isinstance is the most obvious way that I can think of.

Alan G.

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


Re: [Tutor] looking for tutor

2010-01-14 Thread Alan Gauld


"maxwell hansen"  wrote


I have a decent amount of knowledge with QBASIC and am looking
for a tutor who can help me learn the pythonic equivalent of QBASIC
features and commands


The original version of my tutor was based on QBASIC and Python(v1.5!)
It might still be useful for comparisons. The latest version uses VBScript
which is somewhat similar to QBASIC...

http://www.freenetpages.co.uk/hp/alan.gauld/oldtutor/index.htm

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



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


Re: [Tutor] Images on Python 3k

2010-01-16 Thread Alan Gauld


"Luhmann"  wrote

I have only started using python after Py3 was released, so this is is 
the only version I know. I have tried to make my code work in 
Python 2 so I could use PIL, 


This is one of the biggest barriers to adopting Python 3. Until PIL 
gets ported it's a non starter for many folks.


And why Tk doesn't support formats other than GIF and PPM for 
its "PhotoImage" widget is a long standing mystery! Thee has been 
much talk of supporting JPG but nothing has ever materialised.


Alan G.


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


Re: [Tutor] Confirmation about __init__()

2010-01-17 Thread Alan Gauld


"Robert"  wrote

I have read quite a bit in the past 2 months, ( I have also looked at 
codes)

At this point, I think I understand well what __init__() is and does -
But, I have yet to see this *specifically* spelled out about the the
__init__ method for a Class;

It is OPTIONAL, correct ?


Yes as are all metods. There is nothing very special about __init__
except that it is not called explicitly by users of the class. It could 
have

been done as an explicit method as in Smalltalk or Objective C.
In these the instance creation paradigm is a two stage process

obj = [[class new] init]

In Python we get the init call for "free"

Alan G.


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


Re: [Tutor] command line invocation

2010-01-17 Thread Alan Gauld


"Robert"  wrote 


in shell, my current directory is "/tmp",
are line#3 and #4 --- http://paste.pocoo.org/show/166268/ -
"equivalent" --- i.e. yielding the same result ?


No need to use pastebin when its only 2 lines!

Since -m runs a module as a script I think the answer is yes. 

Where they would be different is if you were not in the same folder 
as the module. Then the -m option would search the PYTHONPATH 
whereas without -m I think it would not search for the module, you 
would need to specify the location.


I think...

--
Alan Gauld
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] Subclassing object

2010-01-17 Thread Alan Gauld


"Timo Vanwynsberghe"  wrote


I read that it is advised to subclass object.

Is it really necessary? I mean, everything works, why should I add it to 
my

code?


In older versions of Python it made a difference whether you used object
or not. Using object gave you a "new style" class which has several extra
features, without you got an "old style class" without the features.

In Python v3 you only get new style classes and I think you can omit
the object without detriment.

For comparison here are Python v2.5 definitions


class New(object): pass

...

dir(New)
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', 
'__hash_
_', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', 
'__repr_

_', '__setattr__', '__str__', '__weakref__']

class Old: pass

...

dir(Old)

['__doc__', '__module__']

As you can see there is quite a lot of extra "stuff" in the New class.


In Python 3:


class New(object): pass



dir(New)

['__class__', '__delattr__', '__dict__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__',
'__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', '__weakref__']

class Old: pass



dir(Old)

['__class__', '__delattr__', '__dict__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__',
'__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', '__weakref__']


There is even more "stuff" but it is the same with/without the explicit 
'object'.


HTH,

--
Alan Gauld
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] Subclassing object

2010-01-17 Thread Alan Gauld


"Robert"  wrote

I have been wondering about this "New-style Class" subject along this 
line:


so, *theoretically speaking*, in EXISTING, pre-P3K code,
if one changes everywhere where it's coded "class someClass()" to
"class someClass(object)",
it should not break the programs, right ?


More correctly replacing old style

class SomeClass:

with new style

class SomeClass(object):

should not break anything.
You cannot of course reliably go the other way!

Alan G 



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


Re: [Tutor] adding more text to a file

2010-01-17 Thread Alan Gauld


"Shizuha Aki"  wrote


i need it to be able to add more entries instead of just one.

my code is like this:

while True:
  name = raw_input("what is the name ")
  age = raw_input("what is the age ")

  out_file = open("persons.txt", "w")


It would work if you moved the open() call outside the loop 
so the file is only opened once. Every time you open the file 
you create a new file on top of the old one. You need to 
move the close outside the loop too of course. That way 
you don't need append mode unless you want to run the 
program multiple times to keep adding data.



  out_file.write("name: ")
  out_file.write(name)
  out_file.write("\n")


You should join the strings together and write a full line out at once. 
It will be more efficient and possibly more resilient too.


--
Alan Gauld
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] adding more text to a file

2010-01-17 Thread Alan Gauld


"Magnus Kriel"  wrote

It might be that when you create a file for the first time with 'a', that 
it
will through an exception. So you will have to try with 'w', and if there 
is
an exception, you know the file does not exist and you will have to 
create

the file for the first time with 'w'.


That should not happen. If there is no file 'a' will act like 'w'

Alan G.


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


Re: [Tutor] Python workspace - IDE and version control

2010-01-18 Thread Alan Gauld


 wrote

order to create an efficient and productive Python programming 
workspace: IDE and Version Control.


Both important, although an IDE is perhaps a generous
description of vim! :-)

Obviously, no tool can think for you. The real programming work of 
course is going on in your brain. I am curious what combination of IDE 
and Version Control System you use and also perhaps, what other tools  I 
should be looking at as well.


I tend to use vim under cygwin (which gives me all the Unix tools) as the 
IDE.


I use plain old RCS for version control because its just me working on the 
code.


At work where we have parallel streams I use SVN (used to be Borland 
$tarTeam)

Because we use Eclipse at work I increasingly use Eclipse with PyDev as my
IDE for larger projects - its project support is very effective and I like
the debugger. Also, since I often integrate Java and Jython, Eclipse is 
ideal for

integrating a multi-source project, especially with a UML modelling plugin
added to capture the design.

Finally, I use Subclipse to integrate Eclipse with SVN.

Alan G. 



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


Re: [Tutor] Python workspace - IDE and version control

2010-01-18 Thread Alan Gauld


"Matthew Lee"  wrote


I usually just use NetBeans or the Python IDLE.
I prefer to use NetBeans because it's easier to change and modify code 
and

test. And also because I like to use Jython.

Anything wrong with my setup?


If it works for you then its fine.
IDEs, editors etc are all very personal choices and everyone is different.
I used Netbeans for a while and preferred it to Eclipse at the time, but I 
use

Eclipse because its what we have to use at work and consistency outweighs
the slight advantages I found in Netneans. If you don;t have that 
constraint

use whatever you find works best for you!

Alan G 



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


Re: [Tutor] Python workspace - IDE and version control

2010-01-19 Thread Alan Gauld

"Kent Johnson"  wrote

I use plain old RCS for version control because its just me working on 
the

code.


hg init # create a repository


md RCS in rcs


hg st # show what will be checked in

hg add # mark new files as to be added


Don't need any of that stuff


hg ci -m "Initial checkin" # the actual checkin


ci foo.py in rcs


and voila! you have a version-controlled project!


I prefer RCS - two commands is all you need (ci/co) :-)

Alan G. 



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


Re: [Tutor] Python workspace - IDE and version control

2010-01-19 Thread ALAN GAULD


> >>> I use plain old RCS for version control because its just me working 
>> I prefer RCS - two commands is all you need (ci/co) :-)
>
> Certainly, OTOH, you get only file based commits, no upgrade path 
> should you ever decide that you need to go multiuser 
> (and multiuser can be just you with two different places, 

Well, you get tags which allow you to check in/out a whole project
at a time if need be. And RCS does allow multi user and server 
based working (just by locating the RCS folder there!). In fact the 
biggest project I ever worked on had around 3.5 million lines of 
C++ in 10,000 source files in over 200 folders and it was all 
controlled using RCS and makefiles.

And branching and merging are all standard features too. (We had 
over 400 developers working off the repositories with 4 or 5 branches 
active at any one time - but CVS would have been much easier if it 
had been available at the time - v1.0 was just released the same year 
we started work - 1990!)

But modern tools are much better I agree. And at work, as I said, we use 
subversion (and CVS on older projects). In my time I've also used 
several heavyweight version and configuration control tools - ranging 
in price from a few hundred pounds to several hundred thousand dollars.

The best by a long shot is ClearCase on Unix, although Aide de Camp 
is also good. But these both cost 

For my home use, the biggest Python project I've done had less 
than 10 files in a single folder plus some imported modules from 
my personal collection so RCS is more than adequate.

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


Re: [Tutor] keeping track of the present line in a file

2010-01-21 Thread Alan Gauld


"sudhir prasad"  wrote 


is there any other way to keep track of line number in a file other than
fileinput.filelineno()


You could always do it manually by incrementing a counter every 
time you read a line. But what's the problem with filelineno()?


If you tell us what your problem is we might be able to offer 
a suggestion.



--
Alan Gauld
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] create an object from a class in dll with ctypes?

2010-01-22 Thread Alan Gauld


"katrin schmid"  wrote 

if the resulting .pyd is plattform dependent?
If i create one on windows would linux user need another one?


A Windows DLL will not work on Linux and a Linux library 
will not work on Windows. You need one per OS.


Alan G.

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


Re: [Tutor] create an object from a class in dll with ctypes?

2010-01-22 Thread Alan Gauld


"katrin schmid"  wrote

and there is no portable way of distributing it? 
I could tranlate the cpp code to python but its really lame


Native code is native code I'm afraid. You have to rebuild it for 
every platform. Thats one reason interpreted languages are 
becoming more popular because they are portable. 
The downside of portability is loss of speed.


Alan G.

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


Re: [Tutor] The magic parentheses

2010-01-23 Thread Alan Gauld


"David Hutto"  wrote


This is my first post to the list, so tell me if I'm posting incorrectly.


You are doing fine. Welcome.


My problem is when the results are printed, I get this:

>>>
('Variable 2,', 490.0, 'is greater than', 'Variable 2,', 8.0, '.')



The parentheses, as well as the apostrophes and commas.
I'm sure it's the way I'm having the results printed after it's
through, but not sure how to correct it.


You have two problems in your code(at least!)
---def area2(radius):
   area2r = 3.14159 * mainvar2**2
   return area2r
   print area2r
The print statement will never be called because the return 
statement forces an exit from the function.

-
def return_difference_of12(var1,var2):
   if var1 - var2 > 0:
   y = v1,var1,v3,v2,var2,period
   print y
   elif var2 - var1 > 0:
   z = v2,var2,v3,v2,var1,period
   print z
The assignments to y and z create tuples 
(a,b,c...)So you are asking to print a tuple and Python represents tuples 
by putting parens around the contents.To print them as a string use the 
join() method of a string using an empty string:print ''.join([str(s) for s 
in y])However this is an unusual way to print this type of output,It would 
be more normal to use a format string:print "Variable2: %f id greater than 
Variable1: %f." % (var1,var2)This reduces the number of variables needed 
and also gives you much more control over layout because the %f markers can 
be augmented with width specifiers, justificationhints etc.You can store 
the entire format string in a variable if you wish - especiaslly if you 
want to use it multiple times - but in your case the strings only appear 
once so I wouldn't bother.HTH,-- Alan GauldAuthor of the Learn to Program 
web sitehttp://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] The magic parentheses

2010-01-24 Thread Alan Gauld


"Hugo Arts"  wrote 


print "this is {0}".format("formatted")

this is formatted


Caveat:
this style only works in Python 3.0 upwards  (or maybe in 2.6/2.7?)

Alan G.

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


Re: [Tutor] Is it pythonesque

2010-01-24 Thread Alan Gauld


"Robert Berman"  wrote


def getuserinput():
   while True:
   s1 = raw_input('Enter fraction as N,D or 0,0 to exit>>')
   delim = s1.find(',')
   if delim < 0:
   print 'invalid user input'
   else:
   n = int(s1[0:delim])
   d = int(s1[delim+1::])
   return n,d


Personally I'd do this with

try:
n,d = s1.split(',')
return int(n),int(d)
except ValueError:
print 'invalid user input'
continue


Note ValueError works for both the int conversion and the split() 
assignment



def main():
   while True:
   n,d = getuserinput()
   if n == 0 or d == 0: return 0


correct. Please note there is no true ending return for getuserinput() as 
it

is hung off an if statement and if by some  chance it breaks, it should
return None which will abort the program.


Since you are inside an infinite loop you should only break if you get an
uncaught exception which will generate a stack trace anyhow

That seems fair enough to me...

HTH,


--
Alan Gauld
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] The magic parentheses

2010-01-24 Thread Alan Gauld


"Lie Ryan"  wrote 

and used print, I thought they would be considered the same whether as 
a variable, or as a direct line, guess not.

what is equivalent:
print (a, b, c)

and
x = a, b, c
print x

both construct a tuple and prints a,b,c as tuple


Not quite:


a = 1
b = 2
c = 3
x = a,b,c
print a,b,c

1 2 3

print x

(1, 2, 3)




The first form prints multiple values the second prints the repr of a 
single tuple value. The output is different.


Alan G.


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


[Tutor] Updated topic on my tutorial

2010-01-24 Thread Alan Gauld

I don't normally announce new toppics as I translate them to v3
however I've done quite a bit of rework/expansion to my OOP 
topic, including adding some basic stuff about UML diagrams.


I'm interested in any feedback, especially whether the UML
helps or hinders understanding! And of course any errors 
you see - there will almost certainly be a few!


The direct link is
http://www.alan-g.me.uk/l2p/tutclass.htm

Regards,


--
Alan Gauld
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] The magic parentheses

2010-01-25 Thread Alan Gauld


"David Hutto"  wrote


>>> a = 1
>>> b = 2
>>> c = 3
>>> x = a,b,c
>>> print a,b,c
1 2 3
>>> print x
(1, 2, 3)


So 'print a,b,c' says display the values of a,b,c in the sequence of 
a,b,c given.
'print x' says print the value of x, x grabs a's value, b's value, and 
c's value,

and displays the values for print.


Not quite.
x is a tuple - a collection of values - it does not grab those values, it 
is given them
Once given them it keeps them. If we subsequently change 'a' that change 
will
not be reflected in x! (Note it gets more complex if 'a' is a mutable 
type.)



a = 1
b = 2
c = 3
x = a,b,c
print a,b,c

1 2 3

print x

(1, 2, 3)

a = 66
x

(1, 2, 3)

So no change in x even though a has changed.

print always just displays the string representation of the values passed 
to it.

So when passed a,b,c it prints the string version of a, the string version
of b and the string version of c. When passed x it prints the string 
version

of x which is a tuple. tuples in Python are represented as a sequence of
values inside parentheses. But x does not go and fetch the latest values
of a,b and c, it uses the values provided when x was created.


So the sequence becomes a tuple because it's a value of values,


x is a tuple because that's what we created when we assigned the 3 values.
Any sequence of values outside brackets or quotes is a tuple


t1 = 1,2,3
t2 = 'a','b','c'
t3 = (2,,4,6)
t4 = (t1,t2)



and it's sum comes back in the form of a tuple,


It was a tuple, it does not create itself dynamically.


not an actual end variable.


A tuple is an "end variable". It is just as much a valid type as an
integer, a string or a list. It is just another data type.


In other words the second leap to find the values of a,b,c for value x,


There is no second leap. It stores and uses the values passed to it in
the original assignment.


Now if I want to turn the first values listed under x into tuples
(or use the format function that I think was named in another
reply to return the non-tuple version of the value for x and
I'm going to try it in a few min) of the other two variables,


I'm not sure what you mean here.
The values in x are the original values of a,b and c.
You can access those values using x[0],x[1],x[2].
Is that what you mean?


g = f
a = b,c


This will fail because b and c don;t exist yet.


b = a,c


this will fail because c does not exist yet


c = a,g
x = a,b,c




This is off the topic I think, so I'll repost under another if necessary,
but how do I avoid going into the loop of tuples/variables.


There is no loop, it is not a dynamic lookup. The tuple stores the
values at the time of creation. If the values don;t exist yet(as above)
the assignment will fail to create a tuple and you will get an error.


If a is dependent on knowing what b,c are, and b is dependent
on knowing what a and c are, and c is dependent on knowing
what a and b are, how do I prevent from going into a defining
loop for each.


Python won;t let you create variables using other variables that
have not been defined yet. It is your responsibility as the programmer
to define valriables  before using them.


This is just basically playing with Python's functions, I was
just wondering how to approach such a problem where variables
must come in order but might be dependent on a following variable


It will fail. You must create the variables before use.
We, can do some clever things with functions that can defer
the evaluation of variables until later in the program but thats
an advanced topic that I won't go into here!


In the above, if I want to know c it requires knowing a,g. But
in order to know a, a needs to know b,c-so I can't list c
above a or a above c, because I get the error that the
value of the other is not known when I try to run the script.


Correct, you must find a way to order them such that the
dependencies are sorted out before assignment.

Take a look at the sections on variables and collections,
especially tuples, in the Raw Materials topic of my tutor for
more information..


HTH,

--
Alan Gauld
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] The magic parentheses

2010-01-25 Thread Alan Gauld


"spir"  wrote 

Lie's example actually was:


a,b,c = 1,2,3
print (a,b,c) # here parenthesized

(1, 2, 3)


Oops, I've been using Python 3 too much, I mentally blanked 
out the parens!


Sorry about that.

Alan G.

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


Re: [Tutor] Need help with functions!

2010-01-26 Thread Alan Gauld


"Raymond Kwok"  wrote


I have a function called get_word() that does the random word thing and
returns two things - 1) original word and 2) scrambled word, 


jumble = get_word()[0]
originalword = get_word()[1]


You need to store the return value once and access the two values.

words = get_word()
jumble = words[0]
originalword = words[1]

OR, use the neat Python trick of unpacking into two variables at 
once, like this:


jumble,original_word = get_word()

HTH,


--
Alan Gauld
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] Is wxPython (development) dead?

2010-01-27 Thread Alan Gauld

"Neven Gorsic"  wrote


Since May of 2009 there has not been any update and now web page is not
available any more ...


I'll be very surprised if the whole project is dead - its probably the 
second

most used GUI for Python - but the web site does seem to be down.

FWIW The wxPython mailing list is very much still alive, with 5 new threads
today so far. Maybe you could ask whats going on there?

Alan G. 



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


Re: [Tutor] length of a string? Advice saught

2010-01-27 Thread Alan Gauld


"Kirk Z Bailey"  wrote

I wrote a program to let me edit web-pages without bothering with ftp; it 
loads up a simple form with the page guts in it, and saves it through 
another script.


truncated it- completely omitted the last 1/4 of the original file, 
creating big problems. Looking everything over, I can only conclude that 
somehow python 2.23 (ok, it's an old server; shoot me, I'm poor) has a 
limit on a simple string variable.


Since you don't give us any clues as to how your program works
I can only guess, but I suspect the problem lies not in the string
variable but in the means of populating it. Did you use read()?
And if so from where?

read() functions usually have an optional buffersize parameter
set to a "reasonable" size. If you try to read more than that it
will be truncated. This is explained in the read() documentation
for files. The urllib module has a similar limitation as indicated
by this quote from the docs:

--
One caveat: the read() method, if the size argument is omitted or negative,
may not read until the end of the data stream; there is no good way to
determine that the entire stream from a socket has been read in the general 
case.



I don;t know if you are using either a file read() or urlib.read()
but that may be the cause of the problem?

--
Alan Gauld
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] length of a string? Advice saught

2010-01-28 Thread ALAN GAULD
>> set to a "reasonable" size. If you try to read more than that it
>> will be truncated. This is explained in the read() documentation
>> for files.
>
> ?? files have a buffer size that sets how much is read from the disk
> at once; I don't think it affects how much is read by file.read(). The
> docs for that say,
> "If the size argument is negative or omitted, read all data until EOF
> is reached."

Oops, wrong again! :-)

But the comment re urllib.read() still seems apropos.

Alan G.

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


Re: [Tutor] [File Input Module]Replacing string in a file

2010-01-28 Thread Alan Gauld


"vanam"  wrote


Suppose if data.txt has string Python written in Font size 72 and when
i display the string on the console ie. by below piece of code


Text files don't have font sizes, just text. To store formatting 
information

requires that data to be stored (separate to the text) in the file and then
the rendering program (word processor, browser etc) to interpret the
style information and display appropriately. But the text is always
independant of the formatting.


It wouldnt print with the same Font size on the console (This wont
prove anything wrong as the same font could be backed with a different
file name)


It has nothing to do with the file name, the font size is all to do with 
the

presentation application and any format data stored within the file.
eg in HTML it will be in a style attribute of the text

HTH,

--
Alan Gauld
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] Future of Python Programmers

2010-01-31 Thread Alan Gauld


"nikunj badjatya"  wrote


I have one important question to ask to all of you,
I am a fresher, recently completed my graduation, had started working on
python 2 months back..!! and I just fell in love with the language.
The only concern is there arent enough companies which work on Python.


How many companies do you need?
One is enough if you fork for that one...

Is there any chance where the development of Python will make it as fast 
as

C++ or JAVA, (or it is at its optimum level? ) .


No, just as there is no chance that Java will ever be as fast
as C++ or C++ as fast as C or C as fast as assembler.
You can construct test cases where they approach each other
but raw speed is related to how  close you can get to the machine.
The trade off is that raw speed requires guru level skill and a lot of
development time. So if you measure speed in terms of productivity
Python is already faster than Java!

But your concerms are misplaced.
All programming languages (except perhaps COBOL and FORTRAN)
come and go. When I left university (mid 1980's) everyone was using
Pascal and C. ADA and Prolog were the forecast kings of the block
and a few people were playing with Smalltalk.Then Windows came out
and C++ suddenly took over. Then it was Java.Then scripting languages
became poular. I don;t know what we will be using in 20 years time but
it probavbly won't be Java or C++ or even Python.Get used to it, as a
professional you will learn and use many languages (I know over 20 that
I've used in real projects, and probavbly another dozen that I studied
just for the knowledge they gave). Languages are just not that important.

Stop fiocussing on languages, start to focus on the deeper
fundamentals of programming. Design, architecture, state, data
structures, logic coupling, cohesion, concurrency etc
These things do not change.

--
Alan Gauld
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] Fw: Future of Python Programmers

2010-01-31 Thread ALAN GAULD
Forwarding since I assume this was meant to go 
to either the list or the OP, rather than 
just me...

 Alan Gauld
Author of the Learn To Program website
http://www.alan-g.me.uk/



>
>- Forwarded Message 
>From: Samuel de Champlain 
>To: Alan Gauld 
>Sent: Sunday, 31 January, 2010 14:40:36
>Subject: Re: [Tutor] Future of Python Programmers
>
>In order to get faster programs, you have to become more machine specific. If 
>you want your program to work on several machines, you must include more code 
>for each possible machine architecture. Python and java try to realise the old 
>dream of coding once and running everywhere, therefore they have to be slower 
>in execution, but with the speed of modern machines, this becomes less 
>important. 
>>However, they are fantastic rad (rapid application development) languages. 
>>Time to market and therefore cost is greatly reduced and that is the main 
>>reason they are widely used. Try debugging c and you will learn to appreciate 
>>garbage collectors and the lack of pointer headaches in python.
>>But that is just one person's opinion.
>
>
>On Sun, Jan 31, 2010 at 4:26 AM, Alan Gauld  wrote:
>
>
>>>>"nikunj badjatya"  wrote
>>
>>
>>>>>I have one important question to ask to all of you,
>>>>>>I am a fresher, recently completed my graduation, had started working on
>>>>>>python 2 months back..!! and I just fell in love with the language.
>>>>>>The only concern is there arent enough companies which work on Python.
>>>
>>>>How many companies do you need?
>>>>One is enough if you fork for that one...
>>
>>
>>>>>Is there any chance where the development of Python will make it as fast as
>>>>>>C++ or JAVA, (or it is at its optimum level? ) .
>>>
>>>>No, just as there is no chance that Java will ever be as fast
>>>>as C++ or C++ as fast as C or C as fast as assembler.
>>>>You can construct test cases where they approach each other
>>>>but raw speed is related to how  close you can get to the machine.
>>>>The trade off is that raw speed requires guru level skill and a lot of
>>>>development time. So if you measure speed in terms of productivity
>>>>Python is already faster than Java!
>>
>>>>But your concerms are misplaced.
>>>>All programming languages (except perhaps COBOL and FORTRAN)
>>>>come and go. When I left university (mid 1980's) everyone was using
>>>>Pascal and C. ADA and Prolog were the forecast kings of the block
>>>>and a few people were playing with Smalltalk.Then Windows came out
>>>>and C++ suddenly took over. Then it was Java.Then scripting languages
>>>>became poular. I don;t know what we will be using in 20 years time but
>>>>it probavbly won't be Java or C++ or even Python.Get used to it, as a
>>>>professional you will learn and use many languages (I know over 20 that
>>>>I've used in real projects, and probavbly another dozen that I studied
>>>>just for the knowledge they gave). Languages are just not that important.
>>
>>>>Stop fiocussing on languages, start to focus on the deeper
>>>>fundamentals of programming. Design, architecture, state, data
>>>>structures, logic coupling, cohesion, concurrency etc
>>>>These things do not change.
>>
>>>>-- 
>>>>Alan Gauld
>>>>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 maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Complied Python program...

2010-01-31 Thread Alan Gauld


"Ken G."  wrote

In using Geany, I have the ability to complied a Python program.  For 
example, I can complied "program.py" to program.pyc."


You compile (note spelling) a python script everytime you import it
(if it has not already been compiled).
If you compile a new(or changed) script Python first compiles the
source text into an intermediate version called byte code (sometimes
called p-code) that the interpreter can understand and execute. It
saves the byte-code as a .pyc file so that in future it can import
the compiled version directly (if there is no newer .py file).

This byte-code is similar to what Java produces when you comile jave
into a class file. The Jave runtime engine is basically an interpreter
for Java byte-code. .Net code follows a similar approach too.

What is the purpose of a complied Python program?  Can it be transported 
to another computer without Python installed as run as it is?


No, it needs Python to run it but it can be transported without
the .py file existing - which gives a minimal amount of code
hiding and a marginal startup advantage the first time you run it.
Its not usually worth it IMHO.

You can see the p-code if you use the dis module. The docs give this 
example:



def myfunc(alist):

... return len(alist)
...>>> dis.dis(myfunc)
 2   0 LOAD_GLOBAL  0 (len)
 3 LOAD_FAST0 (alist)
 6 CALL_FUNCTION1
 9 RETURN_VALUE
The bytecode : 0,0,3,0,6,1,9 is more compact but much more primitive than 
the original source text. It is similasr in character to a machine code 
program but is machine independant.Thus it is said to run on a virtual 
machine - the Python interpreter.HTH,-- Alan GauldAuthor of the Learn to 
Program web sitehttp://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] python and sqlite

2010-02-01 Thread Alan Gauld


"Samuel de Champlain"  wrote


Here is another short one that I found:
http://www.wdvl.com/Authoring/python/SQLite/Watts07162009.html
If anyone knows of other tutorials on python and sqlite, please tell me 
of

them.


The databases topic in my tutorial uses SQLite as its database engine.
(Only in the v2 tutor so far)
--
Alan Gauld
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] callable objects

2010-02-02 Thread Alan Gauld


"sudhir prasad"  wrote

i run module1 ,first it calls sm1 in module 2 and a list gets updated,now 
i
again pass the same list to sm2 in module2 but im getting an error " 
'list'

object is not callable"


That suggests that somewhere in your code you are trying to call the list.
ie putting parentheses after it:

lst = [1,2,3]
lst()   # tryiong to call list but list is "not callable"

So I think the error is to do with a mistake in your copde rather than
the module/submodule structure!

But that is guesswork without seeing the code.
When discussing an error always send the full error message so that
we can read the stack trace etc. And post the code if possible too - at
the very least the function where the error occurs!

HTH,


--
Alan Gauld
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] Shashwat Anand you helped with search

2010-02-02 Thread Alan Gauld


"jim serson"  wrote

I think I am using the right method in the wrong way. 


I'm not sure what you expect this to do...

If you could tell me if I am trying the correct method or give 
me a push in the right direction that would be grate thanks.


Maybe a push...


look_in = raw_input ("Enter the search file to look in ")
search = raw_input ("Enter your search item ")


OK, so far. You want to look for search in the file.


c = open(look_in, "r").read().count(search.split()


Assuming there should be another closing paren...
this opens the file and reads it into memory. 
It then counts the occurences of a list produced 
by splitting the search string. This gives a Typeerror for me!

Is that what you wanted?
Or do you actually want to search for each item in your 
search string? I think you are trying to cram too much 
into one line - if for no other eason that it makes debugging 
almost impossible.


Try this:

txt = open(look_in).read()
search2 = search.split()

print search2# is this what you expect?
   
for item in search2:

c = txt.count(item)
print item, txt.count(c)# is this what you expect?
if c > 0:   print search, ",", c,"Of your search was found"
else:   print item, "was not found"
  
It might give you clues as to what you really want.
But using multiple lines is usually a good idea, 
especially when trying to get it working. Its much easier to 
see where things are breaking that way...



--
Alan Gauld
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] Question about importing

2010-02-02 Thread Alan Gauld


"Grigor Kolev"  wrote 


Can I use something like this
#--
import sys
sys.path.append("/home/user/other")
import module
#-


Yes but if you have a lot of modules in there that you might 
want to use in other programs you might prefer to add the 
folder to your PYTHONPATH environment variable. That 
way Python will always look in that folder for your modules.


Thats what I do - I gave a folder whee I put all my reusable 
modules. This folder is not under my Python install folder 
so that when I install a new Python and delete the old I 
don't lose my code... And the PYTHONPATH variable 
works with the new Python.


--
Alan Gauld
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] language aid

2010-02-04 Thread Alan Gauld


"Owain Clarke"  wrote

I had discounted the idea of a dictionary because all the keys need to be 
unique,


Thats true but the values can be lists and do not need to be unique.
Its probably a better starting point that search through a list looking at 
every item.


so whether the key is the English or non-English word, it couldn't cope 
with

for example "too", or a similar word in the other language.


Why not? There is only one word 'too'?
I'm not sure what you see as the problem here?
I can see an issue where the word can be translated multiple ways,
but I don't see how your list of colon separated pairs is any better?
You still have the same issues to deal with - I think?

However, if you do want to pursue that route it would be better to save
the pairs as tuples rather than as x:y strings.


HTH,

--
Alan Gauld
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] correcting an Active State Recipe for conversion to ordinal

2010-02-04 Thread Alan Gauld


"Serdar Tumgoren"  wrote


was hoping that you all could help me "crowdsource" the issue. If you
have the time and inclination, could you look at the code and tell me
if and where I've gone wrong?


Not sure about the reported bugs but some comments:

What happens if

if value % 100/10 <> 1is false? eg. 110-119There is no else so the function 
will return None.Or do you have future divisuion turned on?In that case the 
if will only error on 110...Also <> is deprecated - and not allowed in v3 
so you should probably change it to !=-- Alan GauldAuthor of the Learn to 
Program web sitehttp://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] Variable: From input and output

2010-02-04 Thread Alan Gauld


"ssiverling"  wrote


So I want to learn assembly.  However, it can take a experienced C
programmer a year to learn assembly.


Dunno where you got that from.
An experienced C programmer should pick up assembler in a few days.
C is just "portable assembler" It is almost a textual replacement for 
assembler.
All the different addressing modes of assembler - which confuse higher 
order

language programmers - are all directly translateable into C pointers etc.
(Note, I'm talking about pure C, not C++, which is a very different 
animal!)


thing I was reading is that alot of the tutorials assume prior 
programming


Thats true of Python too, but there are a few asembler tutorials that still
assume zero programming. Unfortunately they do all need you to understand
the basics of how a computer is put together - arithmetic unit, memory,
registers, IO ports etc Assembler is inextricably tied to the machine.

One brilliant book if you can get it (via a library?) is "The Soul of CP/M"
Obviously way out of datae since its based on CP/M but the writing style
is brilliant and it teaches real world assembler - withh use of BIOS 
functions

to read the keyboard etc and builds a usabletext editor by the end.

Some of the very early Peter Norton books are good too, aimed at DOS
and the original IBM PC.

HTH,

--
Alan Gauld
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] Variable: From input and output

2010-02-04 Thread Alan Gauld


"ssiverling"  wrote

thing I was reading is that alot of the tutorials assume prior 
programming


I just checked and Amazon have the Soul of CP/M still available second
hand for less than a dollar!

Gotta be a bargain!

OH, yes, If you want a free PC assembler you can use DOS debug.
Its still there in XP, dunno about Vista or Win7.

But there are loads of freeware ones too.


Alan G. 



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


Re: [Tutor] Simple variable type question

2010-02-05 Thread Alan Gauld


"Antonio de la Fuente"  wrote 


the doctest for the slope function failed, because is expecting a
floating point value and not an integer:


So convert it to a float.


def slope(x1, y1, x2, y2):
result_slope = ((y2 - y1) / (x2 - x1)) * 1.0
return result_slope


  return float(result_slope)

Or just 


 return float(y2-y1/x2-x1)

You might want to use a try/except to catch a zero division error too?


--
Alan Gauld
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] Simple variable type question

2010-02-05 Thread ALAN GAULD


 

Or just 
 return float(y2-y1/x2-x1)
>>
>>
>Alan why are you suggesting this, surely this will cause the decimal values to 
>be truncated?  Or does this somehow work differently in Python 3? 
>

It would work different in v3 because / is no longer interger division.
However, I just misplaced the ) It should have been after y1.

return float(x1-y1)/(x2-y2)

Sorry about that.

Alan G.

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


Re: [Tutor] Simple variable type question

2010-02-05 Thread Alan Gauld


"Sander Sweers"  wrote 


On vr, 2010-02-05 at 20:39 +0000, ALAN GAULD wrote:

return float(x1-y1)/(x2-y2)


Does not work properly in version 2. Example is the 3rd doc test:
float((3-2)/(3-1)) gives 0.0 instead of 0.5. 


That's what I did wrong dfirst time round, I had the parens round 
the whole, it should only be round the first expression.


Alan G.

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


  1   2   3   4   5   6   7   8   9   10   >