[Tutor] Tuples / Critique of How to Think like a Computer Scientist [Was: Re: Tuples]

2006-04-12 Thread Danny Yoo


On Wed, 12 Apr 2006, Kaushal Shriyan wrote:

> I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap09.htm
> I did not understood the below Section at all :(

Hi Kaushal,

Ok, let's trying starting somewhere else and see at what point you get 
stuck.  It'll also give you a chance to practice what you do understand so 
far.

Are you comfortable about being able to return things besides numbers or 
strings from a function?  In particular, do you have any experience 
writing functions that return tuples?

For example, could you write a function that takes two elements, and wraps 
its input in a tuple?  Let's call this function something, like wrap(). 
We'd expect wrap() to do something like this:

 wrap(5, 6)   --> (5, 6)
 wrap("hello", "world") --> ("hello", "world")

Would you be able to write a definition of wrap()?  Let's start from there 
and see if we can isolate where you're getting stuck.

Also, if you are having trouble with How to Think Like a Computer 
Scientist, I wouldn't be ashamed; I'm not such a big fan of it myself 
anymore.  You might want to take a look at the other tutorials on:

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

---

I'm going to rant, but not at you, but at that particular tutorial you're 
reading.  To the others on the list: frankly, I really do not like the 
approach that "How to Think like a Computer Scientist" uses in marching 
through all the concepts it tries to teach; in a critical eye, I would say 
that it's doesn't do such a good job in integrating concepts, nor does it 
have natural flow.  Am I alone in thinking this?

Chapter Nine seems especially problematic in terms of flow.  It's as if 
they say: "Here are tuples, a data structure.  You should learn them. 
Ok, next up: here's something else you have to learn called random 
numbers.  They have nothing to do with those tuple things what we just 
talked about, but we have to hurry if we're going to finish covering all 
the things in the glossary."

Maybe I'm just reading too pessimistically into it, but the tutorial just 
seems to go out of its way to avoid flowing one concept into another, but 
instead jolting the student across the landscape.  When I read part of 
that section you pointed out, there's one particular thing I strongly 
disagree with, that is, when they throw a rocky curveball with the 
introduction of the "broken" swap() function:


def swap(x, y):  # broken
   x, y = y, x


The issue they try to tackle here really has nothing to do with tuples. 
The same "bug" occurs with:

##
def broken_swap(x, y):
 t = x
 x = y
 y = t
##

or, for that matter:

##
def broken_double(x):
 x = x * 2
##

So I'm actually not quite sure why the tutorial is trying to make a point 
about this.  It's an issue that should have been touched on much earlier 
in Chapter Five or Six, when functions and "multiple assignment" were 
introduced, so mixing it in with the tuple stuff just seems off-track and 
deliberately bewildering.  And mixing it in haphazardly here risks the 
student thinking: "does the issue here have anything to do with this 
'immutability' thing I just read about a few paragraphs ago?"
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Explanation of Lists data Type

2006-04-12 Thread Kaushal Shriyan
Hi All

I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap08.htm

8.7 List slices

>>> list = ['a', 'b', 'c', 'd', 'e', 'f']
>>> list[1:3]
['b', 'c']  -> I understood this
>>> list[:4]  -->  Does this mean its list[0:4]
['a', 'b', 'c', 'd']  > I didnot understood this
>>> list[3:] -->  Does this mean its list[3:0]
['d', 'e', 'f'] > I didnot understood this
>>> list[:] -->  Does this mean its list[0:0]
['a', 'b', 'c', 'd', 'e', 'f'] > I didnot understood this

Please explain me

Thanks in Advance

Regards

Kaushal
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Explanation of Lists data Type

2006-04-12 Thread Pujo Aji
Hello,On 4/12/06, Kaushal Shriyan <[EMAIL PROTECTED]> wrote:
Hi AllI am referring to http://www.ibiblio.org/obp/thinkCSpy/chap08.htm8.7 List slices>>> list = ['a', 'b', 'c', 'd', 'e', 'f']
>>> list[1:3]['b', 'c']  -> I understood this 
>>> list[:4]  -->  Does this mean its list[0:4]   ':' here means --> from the first element to element index 4
['a', 'b', 'c', 'd']  > I didnot understood this >>> list[3:] -->  Does this mean its list[3:0]
   ':' here means --> from element index 3 to the last element  ['d', 'e', 'f'] > I didnot understood this 
>>> list[:] -->  Does this mean its list[0:0]   ':' here means --> from the first element to the last element
['a', 'b', 'c', 'd', 'e', 'f'] > I didnot understood this 
Please explain meThanks in AdvanceRegardsKaushalHope, this helpspujo 
___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Explanation of Lists data Type

2006-04-12 Thread Pujo Aji
Sorry for the last explanationsthere is a correction!On 4/12/06, Pujo Aji <[EMAIL PROTECTED]> wrote:
Hello,
On 4/12/06, Kaushal Shriyan <[EMAIL PROTECTED]
> wrote:
Hi AllI am referring to http://www.ibiblio.org/obp/thinkCSpy/chap08.htm
8.7 List slices>>> list = ['a', 'b', 'c', 'd', 'e', 'f']
>>> list[1:3]['b', 'c']  -> I understood this 

>>> list[:4]  -->  Does this mean its list[0:4]   ':' here means --> from the first element to element index 3 # corrected

['a', 'b', 'c', 'd']  > I didnot understood this >>> list[3:] -->  Does this mean its list[3:0]
   ':' here means --> from element index 3 to the last element  ['d', 'e', 'f'] > I didnot understood this
 
>>> list[:] -->  Does this mean its list[0:0]   ':' here means --> from the first element to the last element

['a', 'b', 'c', 'd', 'e', 'f'] > I didnot understood this 

Please explain meThanks in AdvanceRegardsKaushalHope, this helpspujo
 

___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Explanation of Lists data Type

2006-04-12 Thread Noufal Ibrahim

On Wed, April 12, 2006 2:42 pm, Kaushal Shriyan wrote:

 list[:] -->  Does this mean its list[0:0]
> ['a', 'b', 'c', 'd', 'e', 'f'] > I didnot understood this

I remember you once asked another question related to sequence slices and
I mentioned the effects of slicing with no indices. You sure you're
reading the replies? ;)

When you leave an index in the slice argument, it will assume that you
meant the maximum (or minimum as the case may be) possible.

For example.
>>> foo = ['a','b','c','d','e']
>>> foo[2]   #Element at index 2
'c'
>>> foo[2:]  #Elements from index two till the end
['c', 'd', 'e']
>>> foo[:2]  #Elements from the beginning till index 2.
['a', 'b']
>>>

Now, when you give a [:] to the slice operator, you get a copy of the
original list. This is shown below

>>> bar = foo[:]  #bar contains a copy of foo
>>> baz = foo #baz is an alias for foo (not a copy)
>>> baz is foo#Are baz and foo the same?
True  #Yes they are
>>> bar is foo#Are bar and foo the same?
False #No they're not. It's a copy remember?
>>> bar[2]="test" #Change element at index 2 of bar to "test"
>>> bar   # Print it
['a', 'b', 'test', 'd', 'e'] # It's changed
>>> foo  # Has foo changed as well?
['a', 'b', 'c', 'd', 'e']# Nope. Because bar is a copy of foo.
>>> baz[2]="test"# Now we change element at index 2 of baz.
>>> baz  # Has baz changed?
['a', 'b', 'test', 'd', 'e'] # Of course. :)
>>> foo  # Has foo changed?
['a', 'b', 'test', 'd', 'e'] # Yes. Since baz was an alias of foo.
>>>

I trust this clears things up.

Also, try not to use "list" as a variable name since it's a builtin.

-- 
-NI

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Extending a list within a list comprehension

2006-04-12 Thread Kent Johnson
Victor Bouffier wrote:
> On Tue, 2006-04-11 at 22:17 -0400, Kent Johnson wrote:
>> Victor Bouffier wrote:
>>
>>> If the second element in each array passed as x is of variable length
>>> (that is, it has a different element count than three, in this case),
>>> the program needs to extend the list instead. Without list
>>> comprehensions, and the added capability to utilize and sized list as a
>>> second element, my code ended up looking like the following:
>>>
>>> temporal = []
>>> for x in elements:
>>> lst = [x[0], description[x[0]]]
>>> lst.extend(x[1])
>>> temporal.append([x[1][1], lst])
>>> temporal.sort()
>>> temporal.reverse()  # sort descending
>>> elements = [ x[1] for x in temporal ]
>>>
>>> Is there a way to use list comprehensions to append or extend the array
>>> as needed by the second code listing?
>> I think you are looking for
>> temporal = [ [x[0], description[x[0]]] + x[1] for x in elements ]
>>
> 
> Hi Kent,
> I try this one and get the following error:
> 
> TypeError: list objects are unhashable

It's helpful if you show the traceback as well as the error message.
> 
> I figured it is because of the x[0] element being used as a dict key.
> Can you explain further where this error comes from? Are you getting it
> too?

No, I don't know what is causing it. Isn't x[0] a string? What is 
description? I didn't run the code myself.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dictionary datatype

2006-04-12 Thread kakada
It also works for me now:)

First i tried it with Konsole in Kate and it's not working.
It sometimes happen with assignment statement:

i += 1 (not working)
i+=   1(working)

but later on I tested it again and both are working.

Thanks for your help, though.

da




Jason Massey wrote:
> Works for me:
>
> >>> dict1 = { 0x2018:u'k', 0x2019:u'd'}
> >>> n = 0x2018
> >>> print dict1[n]
> k
> >>>
>
> On 4/11/06, * kakada* <[EMAIL PROTECTED]
> > wrote:
>
> Hello all,
>
> For example, I have a dictionary:
> dict1 = { 0x2018:u'k', 0x2019:u'd'}
>
> I assign:
> n = 0x2018
> print dict1[n]
>
> Then:
> KeyError: '0x2018'
>
> But I can call directly:
> print dict1[0x2018]
>
> So, what is wrong with this? How can I solve it?
>
> Thx
>
> kakada
> ___
> Tutor maillist  -  Tutor@python.org 
> http://mail.python.org/mailman/listinfo/tutor
>
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] failing to learn python

2006-04-12 Thread Payal Rathod
On Tue, Apr 11, 2006 at 07:35:15PM +0100, Alan Gauld wrote:
> Python is a general programmjing language great for bigger jobs.  If 

But what does Python excel at. That si my main question. Whatevfer I 
think of I can already do or know a way to do in shell. I am not getting 
where would I need Python.
e.g. for parsing log files with regex I rather use egrep than Python.  
For counting the number of mails received for a user I use awk, where 
can I use Python. Everyone says it is a "general programming language", 
but what in the world is a "general programming language"?
The Python video said that one can take this language to good level in 1 
afternoon, for me it has been 2 months and more. What is wrong?

With warm regards,
-Payal
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] failing to learn python

2006-04-12 Thread Kent Johnson
Payal Rathod wrote:
> On Tue, Apr 11, 2006 at 07:35:15PM +0100, Alan Gauld wrote:
>> Python is a general programmjing language great for bigger jobs.  If 
> 
> But what does Python excel at. That si my main question. Whatevfer I 
> think of I can already do or know a way to do in shell. I am not getting 
> where would I need Python.
> e.g. for parsing log files with regex I rather use egrep than Python.  
> For counting the number of mails received for a user I use awk, where 

It's possible that for the jobs you need to do, you are already using 
the best tools. If you know shell, egrep and awk, they are probably 
better than Python at doing the things they do.

For me, I don't know those specialized tools and I have chosen not to 
learn them because I don't often need their capabilities and Python can 
do what they do. Maybe not as easily to one fluent in both, but I would 
rather learn one tool that is widely useful than several narrow ones 
that I would use rarely.

> can I use Python. Everyone says it is a "general programming language", 
> but what in the world is a "general programming language"?

A programming language that can be used for a wide variety of tasks, 
rather than being specialized to a particular domain. Some things that 
Python can be used for that might be hard with the tools you know:
mailing list manager (Mailman)
spam filter (SpamBayes)
distributed file sharing (BitTorrent)
dynamic web site (Django, TurboGears, etc, etc)
web scraping (urllib, BeautifulSoup)
XML processing (ElementTree, etc)
GUIs (Tkinter, wxPython, etc)

Also take a look at some of the case studies here:
http://www.python.org/about/success/

or search sourceforge.net for Python projects.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] encoding

2006-04-12 Thread Hugo González Monteverde
kakada wrote:
 > LookupError: unknown encoding: ANSI
 >
 > so what is the correct way to do it?
 >

stringinput.encode('latin_1')

works for me.

Do a Google search for Python encodings, and you will find what the 
right names for the encodings are.

http://docs.python.org/lib/standard-encodings.html

Hugo

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dictionary datatype

2006-04-12 Thread Hugo González Monteverde
kakada wrote:

> I assign:
> n = 0x2018
> print dict1[n]
> 
> Then:
> KeyError: '0x2018'
> 

Notice the error menstions a *string*. You probably mistyped it, not in 
the email, but in your actual program.

Hugo
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dictionary datatype

2006-04-12 Thread Alan Gauld
> For example, I have a dictionary:
> dict1 = { 0x2018:u'k', 0x2019:u'd'}
> 
> I assign:
> n = 0x2018
> print dict1[n]
> 
> Then:
> KeyError: '0x2018'

The error is complaining that you are using a string as a key.
Are you sure you aren't assigning

n = '0x2018'

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


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tuples / Critique of How to Think like a Computer Scientist[Was: Re: Tuples]

2006-04-12 Thread Alan Gauld
> I'm going to rant, but not at you, but at that particular tutorial you're 
> reading.  To the others on the list: frankly, I really do not like the 
> approach that "How to Think like a Computer Scientist" uses in marching 
> through all the concepts it tries to teach; in a critical eye, I would say 
> that it's doesn't do such a good job in integrating concepts, nor does it 
> have natural flow.  Am I alone in thinking this?

I shouldn't comment at all I suppose but I personally think CSpy is
a reasonable CS text if you were using it with a (human) tutor to provide
context. That is, it teaches the CS concepts well enough but doesn't
provide much context.

But living in a glass house as I do, I don't like to throw stones at other
tutorials so I'll leave it at that!

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


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Explanation of Lists data Type

2006-04-12 Thread Alan Gauld
Kaushal,

> 8.7 List slices

You might find it worth going through the official tutor section 
on slicing, it explains the various forms quite well.

>>> list[:4]  -->  Does this mean its list[0:4]

Sort of, it means from *the beginning* to 4.

>>> list[3:] -->  Does this mean its list[3:0]

No it means from 3 to *the end*

>>> list[:] -->  Does this mean its list[0:0]

No, it means from *the beginning* to *the end*

These are all just shortcut conventions that you need to learn.
Another one that can be confusing is negative slices:

list[-3:]

means from the -3 position(ie 3 from the end) to the end

list[3:-3] 

means from the 3rd position to the -3 position

I find it helps to thingk of the collection organised as a ring 
with the counter sitting between the items. Thus zero sits 
between the first and last items. Unfortunately this breaks down if you do

list [-3:3]

which is an error but is not reported as such, rathger it returns 
an empty list!

Basically, play with them a lot and you will get used to their 
little oddities, the huge benefits outweigh the occasional confusion.

HTH,

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


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] failing to learn python

2006-04-12 Thread Danny Yoo


On Wed, 12 Apr 2006, Payal Rathod wrote:

> can I use Python. Everyone says it is a "general programming language", 
> but what in the world is a "general programming language"?

One idea behind a "general purpose programming language" is that it's not 
specialized toward anything in particular.  It's meant to be malliable and 
a bit formless.  A programmer makes what one can with it.


> e.g. for parsing log files with regex I rather use egrep than Python. 
> For counting the number of mails received for a user I use awk

And for text parsing and processing, I think that's perfectly right, and 
you're using the best tools for that application.  (Actually, you might 
want to look into Perl, which integrates regexes very deeply into its 
language.)  You're more effective with those tools because awk and sed are 
domain-specific: they are specifically designed to do text processing very 
well.


You can think of Python as a tool-maker.  If you already are working in 
solely in one domain, where there are already plenty of tools already 
written for you, then you may not get so much out of a general-purpose 
language.  This point is made in an amusing way in Literate Programming:

 http://www-cs-faculty.stanford.edu/~uno/lp.html

The story goes that Knuth, when given the common-words problem, wrote up 
beautiful algorithm, designed a cool data structure to support it, and 
wrote it all in literate programming style.

Bentley, on the other hand, used awk and other shell utilities, and in a 
few minutes, got a more correct solution.  *grin*



> But what does Python excel at. That si my main question. Whatevfer I 
> think of I can already do or know a way to do in shell. I am not getting 
> where would I need Python.

But _someone_ had to write awk and sed: they didn't come fully-formed from 
the head of Zeus.

That's what a general-purpose language like Python is for.  You wouldn't 
write a web application in sed or awk because those two languages have 
limitations on what they're allowed to touch.


> The Python video said that one can take this language to good level in 1 
> afternoon, for me it has been 2 months and more. What is wrong?

No, you're not wrong.  Anyone who says that programming can be learned in 
an afternoon is selling something.  *grin*
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] n00b question: dictionaries and functions.

2006-04-12 Thread Jesse
Hey, this should be an easy question for you guys. I'm writing my first program (which Bob, Alan, and Danny have already helped me with--thanks, guys!), and I'm trying to create a simple command-line interface. I have a good portion of the program's "core functions" already written, and I want to create a dictionary of functions. When the program starts up, a global variable named command will be assigned the value of whatever the user types:

 
command = raw_input("Cmd > ")
 
If command is equivalent to a key in the dictionary of functions, that key's function will be called. Here's an example that I wrote for the sake of isolating the problem:
 

def add():    x = float(raw_input("Enter a number: "))    y = float(raw_input("And a second number: "))    print x + ydef subtract():    x = float(raw_input("Enter a number: "))
    y = float(raw_input("And a second number: "))    print x - y    
commands = {"add": add(), "subtract": subtract()} 
Now, before I could even get to writing the while loop that would take a command and call the function associated with that command in the commands dictionary, I ran this bit of code and, to my dismay, both add() and subtract() were called. So I tried the following:

 
def add(x, y):
    x = float(raw_input("Enter a numer: "))
    y = float(raw_input("And a second number: "))
add = add()
 
When I ran this, add() was called. I don't understand why, though. Surely I didn't call add(), I merely stored the function call in the name add. I would expect the following code to call add:
 

def add(x, y):
    x = float(raw_input("Enter a numer: "))
    y = float(raw_input("And a second number: "))
add = add()
add
 
Can someone clear up my misunderstanding here? I don't want to end up writing a long while loop of conditional statements just to effect a command-line interface.
 
-Jesse
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] n00b question: dictionaries and functions.

2006-04-12 Thread Bob Gailer
Jesse wrote:
> Hey, this should be an easy question for you guys. I'm writing my 
> first program (which Bob, Alan, and Danny have already helped me 
> with--thanks, guys!), and I'm trying to create a simple command-line 
> interface. I have a good portion of the program's "core functions" 
> already written, and I want to create a dictionary of functions. When 
> the program starts up, a global variable named command will be 
> assigned the value of whatever the user types:
>  
> command = raw_input("Cmd > ")
>  
> If command is equivalent to a key in the dictionary of functions, that 
> key's function will be called. Here's an example that I wrote for the 
> sake of isolating the problem:
>  
>
> def add():
> x = float(raw_input("Enter a number: "))
> y = float(raw_input("And a second number: "))
> print x + y
> def subtract():
> x = float(raw_input("Enter a number: "))
> y = float(raw_input("And a second number: "))
> print x - y
>
>
> commands = {"add": add(), "subtract": subtract()}
>
>
>  
> Now, before I could even get to writing the while loop that would take 
> a command and call the function associated with that command in the 
> commands dictionary, I ran this bit of code and, to my dismay, both 
> add() and subtract() were called. So I tried the following:
>  
> def add(x, y):
> x = float(raw_input("Enter a numer: "))
> y = float(raw_input("And a second number: "))
> add = add()
>  
> When I ran this, add() was called. I don't understand why, though. 
> Surely I didn't call add(), I merely stored the function call in the 
> name add. I would expect the following code to call add:
>  
> def add(x, y):
> x = float(raw_input("Enter a numer: "))
> y = float(raw_input("And a second number: "))
> add = add()
> add
>  
> Can someone clear up my misunderstanding here? I don't want to end up 
> writing a long while loop of conditional statements just to effect a 
> command-line interface.
"stored the function call" NO - this mixing 2 things. What you want is 
to store a reference to the function, then call the function thru its 
reference in response to user input. add is a reference to the function. 
add() calls (runs) the function.

commands = {"add": add, "subtract": subtract} # stores function references
command = raw_input("Cmd > ")
if command in commands:
commands[command]() # retrieve a function reference and calls it.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] n00b question: dictionaries and functions.

2006-04-12 Thread Danny Yoo


On Wed, 12 Apr 2006, Jesse wrote:

> def add():
>x = float(raw_input("Enter a number: "))
>y = float(raw_input("And a second number: "))
>print x + y
> def subtract():
>x = float(raw_input("Enter a number: "))
>y = float(raw_input("And a second number: "))
>print x - y
>
>
> commands = {"add": add(), "subtract": subtract()}
>
>
> Now, before I could even get to writing the while loop that would take a 
> command and call the function associated with that command in the 
> commands dictionary, I ran this bit of code and, to my dismay, both 
> add() and subtract() were called.


Hi Jesse,


Ah!  Yes, that's happening because there are parens in there that are 
causing the functions to fire off prematurely.


For example, let's say we have defined a function:

##
>>> def test_function(x):
... return x * x
...
##

(I should give it a better name like square(), but let's ignore that for 
the moment.)  If we just name the function, we'll get back a function 
value:

##
>>> test_function

##

This is a value that can be stored in containers, just like any other 
Python value.


But as soon as we do use parentheses, Python will try to call the 
function:

##
>>> test_function()
Traceback (most recent call last):
   File "", line 1, in 
TypeError: test_function() takes exactly 1 argument (0 given)
##


If we go back to the place where the commands dictionary is being built:

 commands = {"add": add(), "subtract": subtract()}

do you see what needs to be fixed to associate those strings to function 
values?


Best of wishes!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Problems when displaying numbers

2006-04-12 Thread Patricia
Hi,

This is my code:

conn =  MySQLdb.connect(host = "localhost", user = "root", passwd = "",
db ="mydb")
cursor = conn.cursor()
cursor.execute("""SELECT h, k, l, m, s, t
FROM targets WHERE target_name = %s""", (target))
result = cursor.fetchone()

alist = helperfunc.calc_numbers(list(result)) # read below

cursor.close()
conn.close()

for li in alist:
if li == '':
 s = s + "" 
 else:
 s = s + "%s" % li   # problem here


calc_numbers is a method in helperfunc.py that takes the list of values
that I retrieved from the database and then does some calculations 
(addition & division) and also replaces a specific number with ''.
 
When I display the results, most of the times everything looks right, BUT
sometimes I get i.e.  15%% instead of 15. I don't understand why %% is 
added to some of the numbers being displayed. I've noticed that the numbers 
that show %% are the ones that have been modified in the calc_numbers 
method. The numbers that are not touched in that method, don't show it. 
When I printed the list obatined from the calc_numbers method, the 
numbers that have not been touched have an L at the end (i'm assuming 
it stands for long). As I said these numbers are displayed correctly 
all the time. I'm really hoping someone can point me to the right direction
because I've tried different things and nothing seems to work.

Another quick question, my page shows several drop down boxes with 
pre-selected values. When I submit the form or open the page, the 
preselected values appear, but when I press the reload button, 
they don't. (Mozilla)

Thanks,
Patricia





___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] failing to learn python

2006-04-12 Thread Alan Gauld
> can I use Python. Everyone says it is a "general programming language", 
> but what in the world is a "general programming language"?

Others have already answered this. I'll add a few other comments.
A general purpose language is one that in theory means you don't 
need any others. It can do anything. It may not do everything as 
well as special purppose tools like sed but it can do anything.

Where sys admins typically use tools like Python is in producing 
well formatted reports, particularly nowadays on web pages. 
Or maybe you have to do a lot of SQL admin on a database 
and python's database links will allow you to write a single script 
which is easier to maintain than lots of separate ones.

Where python is likely to be more useful to you is where you 
have long shell scripts rather than long awk/sed scripts. Shell 
scripts are fine as application launchers but if you need  to process 
the output of commands and have long multi way if/else chains 
the Python may offer better facilities.

But if you are working exclusively on Unix and you know the 
400+ Unix commands well you may very well have little use 
for Python. I certainly don;t use it for much sys admin stuff, 
I tend to use it to write GUI front ends for the tools, or for 
writing networking applications or testing new protocols.

One example where a tool like Python may be of use to 
you would be in building an interactive diff tool. The standard 
diff tools in Unix only allow comparison of 3 files, but if you 
have 6 or 8 versions you need to compare then using python 
you can build your own diff tool to compare 8 files if needed.
And with the low cost of disk space file management of 
concurrent versions is becoming an issue for many admins...

> The Python video said that one can take this language to good level in 1 
> afternoon, for me it has been 2 months and more. What is wrong?

Probably nothing. That claim refers to someone who is already 
fluent in another general purpose language like C or Java. Such a
programmer can indeed get to the point where they can write 
a reasonable program in Python after a few hours with the 
official tutorial. A beginner will take more like 4-6 months to 
get really comfortable. You probably fit somewhere in the middle
depending on your awk or shell skill level.

If your awk action clauses run to 10s of lines then you probably 
do know enough to learn Python quickly but if you typically only 
write 3 or 4 lines in an action clause then Python will be more 
challenging.

HTH,

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


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] failing to learn python

2006-04-12 Thread Alan Gauld
> the best tools. If you know shell, egrep and awk, they are probably better 
> than Python at doing the things they do.
>
> For me, I don't know those specialized tools and I have chosen not to 
> learn them because I don't often need their capabilities and Python can do 
> what they do.

I must admit I use a myriad of tools, including several text editors.
Its one of the few areas where I disagree with Hunt & Thomas
in "the Pragmatic Programmer", they advocate choosing one editor
and using it exclusively, I use emacs, vim, xedit and even ed on
a daily basis (OK ed only once a month or so!) But I also use
awk and sed weekly.

I've also don't think I've ever worked on a production project
that used less than 5 languages and some have used 12 or more.

Awk in particular is one that I think every programmer should know,
at least at a basic level, in the same way as everyone should learn a
little Tcl and a little Lisp(*). These languages are sufficiently different
to mainstream in structure that we can learn a lot about how to
create programs by looking at their approach. It's fair to say that we
probably wouldn't have ElementTree, BeautifulSoup, SAX or any
other event driven parsers today if it weren't for awk and its elegant
approach to working with text files.

(*)For those building business apps I'd add COBOL to the list. It's
not just history that makes it still the most widely used language on the
planet according to Infoweek.

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


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] String question.

2006-04-12 Thread Carlos Benevides
All,

I have a problem/question I'd like to pose to you guys on how best to 
accomplish the following.  I have a string that will vary in size, what 
I would like to do is split into n size chunks.  I am also not sure how 
best to represent the chunks.  For example, say I have a len(s) = 200 
chars.  I'd like to get one chunk with 160 of those chars and the 
remaining 40 in a second.  Likewise, if I have a len(s) = 350, I'd like 
two chunks of 160 and a 3rd with the remainder.

I don't know what it would best way to accomplish this.  I have the idea 
of converting the string to a list of chars loop through it until size 
is met, create a new string with s=s[:160], then start again, and so 
on.  Is this the only way to accomplish this? Or is there a more 
elegant/clever way?

Thank you  :)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] String question.

2006-04-12 Thread Kent Johnson
Carlos Benevides wrote:
> All,
> 
> I have a problem/question I'd like to pose to you guys on how best to 
> accomplish the following.  I have a string that will vary in size, what 
> I would like to do is split into n size chunks.  I am also not sure how 
> best to represent the chunks.  For example, say I have a len(s) = 200 
> chars.  I'd like to get one chunk with 160 of those chars and the 
> remaining 40 in a second.  Likewise, if I have a len(s) = 350, I'd like 
> two chunks of 160 and a 3rd with the remainder.
> 
> I don't know what it would best way to accomplish this.  I have the idea 
> of converting the string to a list of chars loop through it until size 
> is met, create a new string with s=s[:160], then start again, and so 
> on.  Is this the only way to accomplish this? Or is there a more 
> elegant/clever way?

Here is a good way and links to more ideas:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425044

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problems when displaying numbers

2006-04-12 Thread w chun
hi patricia,

it would be really helpful to see an example of 'result' before and
after the call to calc_numbers() as well as the code for calc_numbers
if possible.

this will likely reveal the problem that you are having.

thanks,
-wesley


On 4/12/06, Patricia <[EMAIL PROTECTED]> wrote:
> Hi,
>
> This is my code:
>
> conn =  MySQLdb.connect(host = "localhost", user = "root", passwd = "",
> db ="mydb")
> cursor = conn.cursor()
> cursor.execute("""SELECT h, k, l, m, s, t
> FROM targets WHERE target_name = %s""", (target))
> result = cursor.fetchone()
>
> alist = helperfunc.calc_numbers(list(result)) # read below
>
> cursor.close()
> conn.close()
>
> for li in alist:
> if li == '':
>  s = s + ""
>  else:
>  s = s + "%s" % li   # problem here
>
>
> calc_numbers is a method in helperfunc.py that takes the list of values
> that I retrieved from the database and then does some calculations
> (addition & division) and also replaces a specific number with ''.
>
> When I display the results, most of the times everything looks right, BUT
> sometimes I get i.e.  15%% instead of 15. I don't understand why %% is
> added to some of the numbers being displayed. I've noticed that the numbers
> that show %% are the ones that have been modified in the calc_numbers
> method. The numbers that are not touched in that method, don't show it.
> When I printed the list obatined from the calc_numbers method, the
> numbers that have not been touched have an L at the end (i'm assuming
> it stands for long). As I said these numbers are displayed correctly
> all the time. I'm really hoping someone can point me to the right direction
> because I've tried different things and nothing seems to work.
>
> Another quick question, my page shows several drop down boxes with
> pre-selected values. When I submit the form or open the page, the
> preselected values appear, but when I press the reload button,
> they don't. (Mozilla)
>
> Thanks,
> Patricia
>
>
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


--
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python video?

2006-04-12 Thread Hoffmann
Hi,

I read this week on this forum about a kind of Python
video in its website. Which view is that, and where
could I find it? I search in Python website, but I
didn't find it. Is it a 'demo' of the language?
Thanks,
Hoffmann

__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor