Re: [Tutor] Python Editor to Start Out WithTutor Digest, Vol 92, Issue 123

2011-10-31 Thread Alan Gauld

On 31/10/11 04:40, cyclicf...@yahoo.com wrote:

With reference to a beginning editor,


I agree with most of this but...


... scripting in vim has many similarities to various types

> in python. The python forloop is definitely very similar

Thats probably because you have a vim that has been compiled with Python 
scripting built in. There are various scripting options

for vim and the original scripting language was not like Python
at all! So it will depend on which vim scripting engine you have installed.


with a click or few clicks provide syntax+highlighting+syntax
error-checking setup. This can be difficult in the traditional text
editors vim+ emacs,(I know vim) have to be compiled with certain
support, as well as then have plugins installed/created,


It shouldn't be the case. The latest versions of both vim and emacs come 
with syntax highlighting set up by default and auto recognize
many languages (based on file extension). So this should not be a 
deciding factor.


Much more of an issue for a newbie is, in both vim and emacs, the 
completely non standard keybindings. Neither use the "normal"
keys for movement, cut n paste, searching etc And its adapting to the 
keybindings that will (a) take time and (b) be a source of frustration 
while learning. And both editors are only really efficient if you drive 
them from the keyboard, they do support mice/menus etc but they are not 
optimised for that.


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

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


Re: [Tutor] importing modules and packages

2011-10-31 Thread Steven D'Aprano

neubyr wrote:

Is it possible to tell whether import statement is importing a module
or package?  I am going through some example code with some import
statements - like 'import os, sys, time', 'import packed'. I know os,
sys and time are (built-in) modules and 'packed' is a package here .
But can I determine whether it's a package or module using any
command/method or by following some naming convention?


Consider:

>>> import curses  # A package.
>>> curses.__file__
'/usr/lib/python2.5/curses/__init__.pyc'
>>> curses.__path__
['/usr/lib/python2.5/curses']


Compare to:

>>> import string  # A plain module.
>>> string.__file__
'/usr/lib/python2.5/string.pyc'
>>> string.__path__
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'module' object has no attribute '__path__'



Does this help?



--
Steven

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


Re: [Tutor] Tutor Digest, Vol 92, Issue 123

2011-10-31 Thread Rinu Boney
I Use Windows.I Already Know C/C++ which makes python syntax seem very easy.
Maybe Setting Up Emacs With Python Will Make Me Productive.
I Have Eclipse With PyDev.
Why Is There Not A Pythonic Emacs?

On Mon, Oct 31, 2011 at 8:23 AM,  wrote:

> Send Tutor mailing list submissions to
>tutor@python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
>http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
>tutor-requ...@python.org
>
> You can reach the person managing the list at
>tutor-ow...@python.org
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
>
>
> Today's Topics:
>
>   1. Setting Up Emacs (Rinu Boney)
>   2. Re: Setting Up Emacs (Steven D'Aprano)
>   3. Re: Setting Up Emacs (Tim Johnson)
>   4. Re: Setting Up Emacs (Alan Gauld)
>   5. Re: Setting Up Emacs (Tim Johnson)
>   6. Re: Method to create small and simple database (Joel M.)
>   7. Re: Setting Up Emacs (Bill Allen)
>
>
> --
>
> Message: 1
> Date: Sun, 30 Oct 2011 18:53:04 +0530
> From: Rinu Boney 
> To: tutor@python.org
> Subject: [Tutor] Setting Up Emacs
> Message-ID:
> >
> Content-Type: text/plain; charset="iso-8859-1"
>
> I am New To Python.
> I Would Like To Setup Emacs As A Python IDE.
> I Don't Know Anything About Emacs!
> Can Someone Help Me ?
> Thanks.
> -- next part --
> An HTML attachment was scrubbed...
> URL: <
> http://mail.python.org/pipermail/tutor/attachments/20111030/ad7f346e/attachment-0001.html
> >
>
> --
>
> Message: 2
> Date: Mon, 31 Oct 2011 02:25:23 +1100
> From: Steven D'Aprano 
> To: tutor@python.org
> Subject: Re: [Tutor] Setting Up Emacs
> Message-ID: <4ead6c63.6020...@pearwood.info>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> Rinu Boney wrote:
> > I am New To Python.
> > I Would Like To Setup Emacs As A Python IDE.
> > I Don't Know Anything About Emacs!
>
> If you don't know anything about emacs, and you don't know anything
> about Python, why do you want to make things ten times more difficult by
> learning a new language AND the most heavyweight, complex editor at the
> same time?
>
> I recommend you use a more friendly editor. You haven't mentioned what
> operating system you are using. If you are using Linux with the KDE
> desktop, I recommend you use a good, modern GUI editor like Kate as your
> editor. Other people might prefer different editors, but I've come to
> like Kate the best.
>
> Personally, I recommend against IDEs. I find that they are
> over-complicated and get in the way. I've seen too many people
> struggling because their IDE changes the way their code works. I
> recommend you keep your code open in an editor, an interactive session
> open in a good xterm, and a second xterm tab open for running your
> script. That's my preference.
>
> But, if you still want to use Emacs as a Python IDE, have you tried
> searching for "python emacs ide"?
>
> https://duckduckgo.com/html/?q=python%20emacs%20ide
>
>
>
> --
> Steven
>
>
> --
>
> Message: 3
> Date: Sun, 30 Oct 2011 07:53:15 -0800
> From: Tim Johnson 
> To: tutor@python.org
> Subject: Re: [Tutor] Setting Up Emacs
> Message-ID: <20111030155315.gb10...@akwebsoft.com>
> Content-Type: text/plain; charset=us-ascii
>
> * Steven D'Aprano  [111030 07:40]:
> > Rinu Boney wrote:
> > >I am New To Python.
> > >I Would Like To Setup Emacs As A Python IDE.
> > >I Don't Know Anything About Emacs!
> >
> > If you don't know anything about emacs, and you don't know anything
> > about Python, why do you want to make things ten times more difficult by
> > learning a new language AND the most heavyweight, complex editor at the
> > same time?
> >
> > I recommend you use a more friendly editor. You haven't mentioned what
> > operating system you are using. If you are using Linux with the KDE
> > desktop, I recommend you use a good, modern GUI editor like Kate as your
> > editor. Other people might prefer different editors, but I've come to
> > like Kate the best.
>
>  I've used emacs extensively in the past and now use vim.  They are
>  both rewarding to use, but to support Steven, it could be a
>  nightmare for Rinu to to learn both python and emacs or vim.
>
>  I believe that idle is part of the python distro on both linux and
>  darwin (Mac OSX). That is worth consideration, I would think.
>
>  If Rinu is on windows, there is pythonwin and there is an
>  extremely good, well supported and easy-to-learn shareware editor
>  called Boxer. I would recommend either to any programmer in a
>  windows environment.
>
> > Personally, I recommend against IDEs. I find that they are
> > over-complicated and get in the way. I've seen too many people
> > struggling because their IDE changes the way their code works. I
> > recommend you keep your code

[Tutor] Paper Rock Scissors game - User's choice not returned properly

2011-10-31 Thread Joel Montes de Oca

Hello everyone,

I am having a little trouble with a block of code that isn't behaving 
the way I would expect. Maybe you can give me a hand and point where it 
is going wrong.


The function that is not working correctly belongs to a Paper Rock 
Scissor game I am making.


This particular function is responsible to:
  a) Get the user's choice (Paper, Rock, or Scissors)
  b) Return the user's choice within the variable choice to the 
function that called it.


The function works correctly as long as the user _does not try to enter 
a string other than_ 'P', 'R', or 'S'.


Logic:
Take the user's string and put it in the variable choice.
If choice is not 'P', 'R', or 'S'then pass a message to the user 
and call the function again.
If the choice is 'P', 'R', or 'S'then return choice to where it was 
called from.


The problem is this.

When the user enters a string other than the valid ones, the if 
statements catches it and calls the same function again so the user can 
enter a valid string. But the variable choice does not get assigned the 
new string entered by the user, instead it is empty.


I would expect if the function runs again, the variable choice would be 
updated to the last value given by the user.


The function: ( http://dpaste.com/644857/)

def  UserChoice  ():# The function that returns the choice from the user
print  'Please select (P) for paper, (R) for Rock, or (S) for Scissors.'
choice  =  raw_input('What is your selection?:')

if  choice.lower()  not  in  ('p',  'r','s'):   # Converts the user's 
choice to lowercase and confirms the choice is valid
print  'I am sorry, you entered\''  +  choice.upper()  +  '\'  
which is an invalid response. Please try again.'
raw_input('Press Enter to try again.')
UserChoice  ()  # If the choice is not valid, run the 
function over
else:
return  choice



Output with no problems: ( http://dpaste.com/644866/) 



Welcome to the PRS game.

Please select (P) for paper, (R) for Rock, or (S) for Scissors.
What is your selection?: s

You threw down Scissors while the computer threw down Rock

LOOSE

Output with problems: ( http://dpaste.com/644868/)

Welcome to the PRS game.

Please select (P) for paper, (R) for Rock, or (S) for Scissors.
What is your selection?: L
I am sorry, you entered 'L' which is an invalid response. Please try again.
Press Enter to try again.
Please select (P) for paper, (R) for Rock, or (S) for Scissors.
What is your selection?: s

You threw down None while the computer threw down Paper

LOOSE

Here's the full source code in case the problem is outside of the 
function: ( http://dpaste.com/644873/)


import  random  # Import the random library

def  main  ():  # The main function that gets called from main()
print  '\nWelcome to the PRS game.\n'

choice  =  UserChoice  ()   # Gets the choice from the user
cchoice  =  ComputerChoice  ()  # Gets the choice from the 
computer

PrintOutcome  (choice,  cchoice)# Passes both choices to the 
PrintChoice function for display


return  0

def  UserChoice  ():# The function that returns the choice from the user
print  'Please select (P) for paper, (R) for Rock, or (S) for Scissors.'
choice  =  raw_input('What is your selection?:')

if  choice.lower()  not  in  ('p',  'r','s'):   # Converts the user's 
choice to lowercase and confirms the choice is valid
print  'I am sorry, you entered\''  +  choice.upper()  +  '\'  
which is an invalid response. Please try again.'
raw_input('Press Enter to try again.')
UserChoice  ()  # If the choice is not valid, run the 
function over
else:
return  choice

def  ComputerChoice  ():# The function that returns the choice 
from the computer
PRS  =  ['Rock',  'Paper',  'Scissors'] # A list of choices

cchoice  =  random.choice(PRS)  # Choose a random item from the list

return  cchoice # Return the function

def  PrintOutcome  (UC,  CC):   # Function responsable to display the 
choices and results
PRS  =  ['Rock',  'Paper',  'Scissors']

# Convert the letters to words
if  UC  ==  'r':
UC  =  PRS[0]
elif  UC  ==  'p':
UC  =  PRS[1]
elif  UC  ==  's':
UC  =  PRS[2]

print  '\n\tYou threw down',  UC,  'while the computer threw down',  CC 
 +'\n'

# find the outcome of the game
if  UC  ==  CC:
print  'We have a tie, both players gain a point!'
elif  UC  ==  'Rock'  and  CC  ==  'Scissors':
print  'WIN'
elif  UC  ==  'Paper'  and  CC  ==  'Rock':
print  'WIN'
  

Re: [Tutor] Tutor Digest, Vol 92, Issue 127

2011-10-31 Thread Asokan Pichai
> From: Joel Montes de Oca 
> To: Tutor Python 
> Subject: [Tutor] Paper Rock Scissors game - User's choice not returned
>properly
> Message-ID: <4eaec191.3060...@gmail.com>
> Content-Type: text/plain; charset="iso-8859-1"; Format="flowed"
>
> Hello everyone,
>
>
> The function: ( http://dpaste.com/644857/)
>
> def  UserChoice  ():# The function that returns the choice from the
> user
>print  'Please select (P) for paper, (R) for Rock, or (S) for
> Scissors.'
>choice  =  raw_input('What is your selection?:')
>
>if  choice.lower()  not  in  ('p',  'r','s'):   # Converts the
> user's choice to lowercase and confirms the choice is valid
>print  'I am sorry, you entered\''  +  choice.upper()  +
>  '\'  which is an invalid response. Please try again.'
>raw_input('Press Enter to try again.')
>
   UserChoice  ()  # If the choice is not valid, run
> the function over
>

You should use
return UserChoice()


>else:
>return  choice
>
>
Asokan Pichai
SVP - Learning and Development

“Faith consists in believing when it is beyond the power of reason to
believe. "
 Voltaire 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 92, Issue 127

2011-10-31 Thread Joel Montes de Oca

On Mon 31 Oct 2011 11:59:47 AM EDT, Asokan Pichai wrote:


From: Joel Montes de Oca mailto:joelmonte...@gmail.com>>
To: Tutor Python mailto:tutor@python.org>>
Subject: [Tutor] Paper Rock Scissors game - User's choice not returned
   properly
Message-ID: <4eaec191.3060...@gmail.com
>
Content-Type: text/plain; charset="iso-8859-1"; Format="flowed"

Hello everyone,


The function: ( http://dpaste.com/644857/)

def  UserChoice  ():# The function that returns the choice
from the user
   print 'Please select (P) for paper, (R) for Rock, or (S)
for Scissors.'
   choice  =  raw_input('What is your selection?:')

   if  choice.lower()  not  in  ('p', 'r','s'):   # Converts
the user's choice to lowercase and confirms the choice is valid
   print 'I am sorry, you entered\''  +
 choice.upper()  + '\'  which is an invalid response. Please try
again.'
   raw_input('Press Enter to try again.')

   UserChoice  ()  # If the choice is not
valid, run the function over


You should use
return UserChoice()

   else:
   return  choice


Asokan Pichai
SVP - Learning and Development

“Faith consists in believing when it is beyond the power of reason to 
believe. "

Voltaire 





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


I am not sure if I understand, why doesn't my way work and what do you 
mean I should return UserChoice()?


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


Re: [Tutor] Paper Rock Scissors game - User's choice not returned properly

2011-10-31 Thread Hugo Arts
On Mon, Oct 31, 2011 at 4:41 PM, Joel Montes de Oca
 wrote:
> Hello everyone,
>
> I am having a little trouble with a block of code that isn't behaving the
> way I would expect. Maybe you can give me a hand and point where it is going
> wrong.
>
> The function that is not working correctly belongs to a Paper Rock Scissor
> game I am making.
>
> This particular function is responsible to:
>   a) Get the user's choice (Paper, Rock, or Scissors)
>   b) Return the user's choice within the variable choice to the function
> that called it.
>
> The function works correctly as long as the user does not try to enter a
> string other than 'P', 'R', or 'S'.
>
> Logic:
>     Take the user's string and put it in the variable choice.
>     If choice is not 'P', 'R', or 'S' then pass a message to the user and
> call the function again.
>     If the choice is 'P', 'R', or 'S' then return choice to where it was
> called from.
>
> The problem is this.
>
> When the user enters a string other than the valid ones, the if statements
> catches it and calls the same function again so the user can enter a valid
> string. But the variable choice does not get assigned the new string entered
> by the user, instead it is empty.
>
> I would expect if the function runs again, the variable choice would be
> updated to the last value given by the user.
>
> The function: ( http://dpaste.com/644857/)
>
> def UserChoice ():# The function that returns the choice from the user
>   print 'Please select (P) for paper, (R) for Rock, or (S) for Scissors.'
>   choice = raw_input('What is your selection?: ')
>
>   if choice.lower() not in ('p', 'r','s'):# Converts the user's 
> choice to
> lowercase and confirms the choice is valid
>   print 'I am sorry, you entered \'' + choice.upper() + '\' which 
> is an
> invalid response. Please try again.'
>   raw_input('Press Enter to try again.')
>   UserChoice ()   # If the choice is not valid, run the 
> function over
>   else:
>   return choice
>

Your problem is that you don't quite understand recursion.

When a function calls itself, it's not actually any different from
when a function A calls another function B. Once function B is done
running and returns, control goes back to function A. It doesn't
matter if function B is actually the same function as A. In fact, even
if A and B are the same function, they don't "share" any variables and
are totally separate as if they were two different functions that just
happened to do the same thing.

So, how does this apply to your function? Let's go through a run of
it. We call UserChoice (this is function A) and we input a wrong
letter. So, A calls UserChoice again (this is function B), and this
time we input something valid. So, function B runs the line "return
choice."

Control now returns to function A, right at the point where we called
function B. So what do we do here with the choice that was just
returned from function B? Well, looking at the line where it's called,
it's just "UserChoice()". So we do nothing. We just throw it away.
Then, we continue on with function A, move out of the if statement,
and "fall off the end" of the function. And when that happens, Python
returns None from function A to show you that nothing was returned.

If you understood all that, you should be able to fix your problem.

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


Re: [Tutor] importing modules and packages

2011-10-31 Thread neubyr
On Mon, Oct 31, 2011 at 4:38 AM, Steven D'Aprano  wrote:
> neubyr wrote:
>>
>> Is it possible to tell whether import statement is importing a module
>> or package?  I am going through some example code with some import
>> statements - like 'import os, sys, time', 'import packed'. I know os,
>> sys and time are (built-in) modules and 'packed' is a package here .
>> But can I determine whether it's a package or module using any
>> command/method or by following some naming convention?
>
> Consider:
>
 import curses  # A package.
 curses.__file__
> '/usr/lib/python2.5/curses/__init__.pyc'
 curses.__path__
> ['/usr/lib/python2.5/curses']
>
>
> Compare to:
>
 import string  # A plain module.
 string.__file__
> '/usr/lib/python2.5/string.pyc'
 string.__path__
> Traceback (most recent call last):
>  File "", line 1, in 
> AttributeError: 'module' object has no attribute '__path__'
>
>
>
> Does this help?
>
>

That's helpful. Thanks a lot..

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


Re: [Tutor] Paper Rock Scissors game - User's choice not returned properly

2011-10-31 Thread Joel Montes de Oca

On Mon 31 Oct 2011 12:14:40 PM EDT, Hugo Arts wrote:


On Mon, Oct 31, 2011 at 4:41 PM, Joel Montes de Oca
 wrote:


Hello everyone,

I am having a little trouble with a block of code that isn't behaving the
way I would expect. Maybe you can give me a hand and point where it 
is going

wrong.

The function that is not working correctly belongs to a Paper Rock 
Scissor

game I am making.

This particular function is responsible to:
a) Get the user's choice (Paper, Rock, or Scissors)
b) Return the user's choice within the variable choice to the function
that called it.

The function works correctly as long as the user does not try to enter a
string other than 'P', 'R', or 'S'.

Logic:
Take the user's string and put it in the variable choice.
If choice is not 'P', 'R', or 'S' then pass a message to the user and
call the function again.
If the choice is 'P', 'R', or 'S' then return choice to where it was
called from.

The problem is this.

When the user enters a string other than the valid ones, the if 
statements
catches it and calls the same function again so the user can enter a 
valid
string. But the variable choice does not get assigned the new string 
entered

by the user, instead it is empty.

I would expect if the function runs again, the variable choice would be
updated to the last value given by the user.

The function: ( http://dpaste.com/644857/)

def UserChoice (): # The function that returns the choice from the user
print 'Please select (P) for paper, (R) for Rock, or (S) for Scissors.'
choice = raw_input('What is your selection?: ')

if choice.lower() not in ('p', 'r','s'): # Converts the user's choice to
lowercase and confirms the choice is valid
print 'I am sorry, you entered \'' + choice.upper() + '\' which is an
invalid response. Please try again.'
raw_input('Press Enter to try again.')
UserChoice () # If the choice is not valid, run the function over
else:
return choice




Your problem is that you don't quite understand recursion.

When a function calls itself, it's not actually any different from
when a function A calls another function B. Once function B is done
running and returns, control goes back to function A. It doesn't
matter if function B is actually the same function as A. In fact, even
if A and B are the same function, they don't "share" any variables and
are totally separate as if they were two different functions that just
happened to do the same thing.

So, how does this apply to your function? Let's go through a run of
it. We call UserChoice (this is function A) and we input a wrong
letter. So, A calls UserChoice again (this is function B), and this
time we input something valid. So, function B runs the line "return
choice."

Control now returns to function A, right at the point where we called
function B. So what do we do here with the choice that was just
returned from function B? Well, looking at the line where it's called,
it's just "UserChoice()". So we do nothing. We just throw it away.
Then, we continue on with function A, move out of the if statement,
and "fall off the end" of the function. And when that happens, Python
returns None from function A to show you that nothing was returned.

If you understood all that, you should be able to fix your problem.

Hugo


Hey Hugo,

I think I understand your explanation. Let me see if I get it.

The code:

def  UserChoice  ():  *# I WILL CALL THIS FUNCTION A*
print  'Please select (P) for paper, (R) for Rock, or (S) for Scissors.'
choice  =  raw_input('What is your selection?:')

if  choice.lower()  not  in  ('p',  'r','s'):
print  'I am sorry, you entered\''  +  choice.upper()  +  '\'  which is 
an invalid response. Please try again.'
raw_input('Press Enter to try again.')
UserChoice  ()  *# I WILL CALL THIS FUNCTION B*
else:
return  choice*# I WILL CALL THE ORIGINAL CALLING FUNCTION, FUNCTION 
MAIN*


OK so when the user uses a valid letter, the variable choice gets 
returned to FUNCTION MAIN. Everything works fine.


When the user enters an invalid letter, FUNCTION B calls FUNCTION A. 
FUNCTION A returns choice to FUNCTION B. FUNCTION B does nothing with 
the return, FUNCTION MAIN gets nothing to returned to it, thus choice is 
NONE.


FUN MAIN
  |
  |
  |__ FUN A
  |
  |
  |_ FUN B

This is how I understand it. So if I want this to work, I need FUN B to 
give something back to FUN A so that FUN A will have something to give 
back to FUN MAIN but that doesn't feel right.


Is there a way to say GO TO FUN A instead of calling the function?



I also found this Youtube video on the topic of recursion in python. 
http://www.youtube.com/watch?v=72hal4Cp_2I


--
-Joel M.

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


Re: [Tutor] Tutor Digest, Vol 92, Issue 128

2011-10-31 Thread Asokan Pichai
Hugo's explanation is nice and clear.

You may also want to look at this way
Consider the most simplified form of the issue

def alpha():
  if  X:
   beta()
  else:
   return q

Here in the* if branch* nothing is returned
while in the *else branch *something is being returned.

That is  whenever X is True nothing is returned from alpha().
Even if beta() returns something that is not being used.

But when X is False something (q in this simplistic example)
is being returned

So this is a bug.

HTH

Asokan Pichai
SVP - Learning and Development

“Faith consists in believing when it is beyond the power of reason to
believe. "
 Voltaire 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Paper Rock Scissors game - User's choice not returned properly

2011-10-31 Thread Joel M.
On Mon, Oct 31, 2011 at 1:09 PM, Joel Montes de Oca
wrote:

>  On Mon 31 Oct 2011 12:14:40 PM EDT, Hugo Arts wrote:
>
>
> On Mon, Oct 31, 2011 at 4:41 PM, Joel Montes de Oca
>   wrote:
>
>
> Hello everyone,
>
> I am having a little trouble with a block of code that isn't behaving the
> way I would expect. Maybe you can give me a hand and point where it is
> going
> wrong.
>
> The function that is not working correctly belongs to a Paper Rock Scissor
> game I am making.
>
> This particular function is responsible to:
> a) Get the user's choice (Paper, Rock, or Scissors)
> b) Return the user's choice within the variable choice to the function
> that called it.
>
> The function works correctly as long as the user does not try to enter a
> string other than 'P', 'R', or 'S'.
>
> Logic:
> Take the user's string and put it in the variable choice.
> If choice is not 'P', 'R', or 'S' then pass a message to the user and
> call the function again.
> If the choice is 'P', 'R', or 'S' then return choice to where it was
> called from.
>
> The problem is this.
>
> When the user enters a string other than the valid ones, the if statements
> catches it and calls the same function again so the user can enter a valid
> string. But the variable choice does not get assigned the new string
> entered
> by the user, instead it is empty.
>
> I would expect if the function runs again, the variable choice would be
> updated to the last value given by the user.
>
> The function: ( http://dpaste.com/644857/)
>
> def UserChoice (): # The function that returns the choice from the user
> print 'Please select (P) for paper, (R) for Rock, or (S) for Scissors.'
> choice = raw_input('What is your selection?: ')
>
> if choice.lower() not in ('p', 'r','s'): # Converts the user's choice to
> lowercase and confirms the choice is valid
> print 'I am sorry, you entered \'' + choice.upper() + '\' which is an
> invalid response. Please try again.'
> raw_input('Press Enter to try again.')
> UserChoice () # If the choice is not valid, run the function over
> else:
> return choice
>
>
>
> Your problem is that you don't quite understand recursion.
>
> When a function calls itself, it's not actually any different from
> when a function A calls another function B. Once function B is done
> running and returns, control goes back to function A. It doesn't
> matter if function B is actually the same function as A. In fact, even
> if A and B are the same function, they don't "share" any variables and
> are totally separate as if they were two different functions that just
> happened to do the same thing.
>
> So, how does this apply to your function? Let's go through a run of
> it. We call UserChoice (this is function A) and we input a wrong
> letter. So, A calls UserChoice again (this is function B), and this
> time we input something valid. So, function B runs the line "return
> choice."
>
> Control now returns to function A, right at the point where we called
> function B. So what do we do here with the choice that was just
> returned from function B? Well, looking at the line where it's called,
> it's just "UserChoice()". So we do nothing. We just throw it away.
> Then, we continue on with function A, move out of the if statement,
> and "fall off the end" of the function. And when that happens, Python
> returns None from function A to show you that nothing was returned.
>
> If you understood all that, you should be able to fix your problem.
>
> Hugo
>
>
> Hey Hugo,
>
> I think I understand your explanation. Let me see if I get it.
>
> The code:
>
> def UserChoice (): *# I WILL CALL THIS FUNCTION A*
>
>
> print 'Please select (P) for paper, (R) for Rock, or (S) for Scissors.'
> choice = raw_input('What is your selection?: ')
>
> if choice.lower() not in ('p', 'r','s'):
>
> print 'I am sorry, you entered \'' + choice.upper() + '\' which is an 
> invalid response. Please try again.'
> raw_input('Press Enter to try again.')
>
> UserChoice () *# I WILL CALL THIS FUNCTION B*
> else:
> return choice *# I WILL CALL THE ORIGINAL CALLING FUNCTION, FUNCTION 
> MAIN*
>
>
> OK so when the user uses a valid letter, the variable choice gets
> returned to FUNCTION MAIN. Everything works fine.
>
> When the user enters an invalid letter, FUNCTION B calls FUNCTION A.
> FUNCTION A returns choice to FUNCTION B. FUNCTION B does nothing with the
> return, FUNCTION MAIN gets nothing to returned to it, thus choice is NONE.
>
> FUN MAIN
>   |
>   |
>   |__ FUN A
>   |
>   |
>   |_ FUN B
>
> This is how I understand it. So if I want this to work, I need FUN B to
> give something back to FUN A so that FUN A will have something to give back
> to FUN MAIN but that doesn't feel right.
>
> Is there a way to say GO TO FUN A instead of calling the function?
>
>
>
> I also found this Youtube video on the topic of recursion in python.
> http://www.youtube.com/watch?v=72hal4Cp_2I
>
> --
> -Joel M.
>
>
After a little digg

Re: [Tutor] Paper Rock Scissors game - User's choice not returned properly

2011-10-31 Thread Joel Montes de Oca

On 10/31/2011 11:41 AM, Joel Montes de Oca wrote:

Hello everyone,

I am having a little trouble with a block of code that isn't behaving 
the way I would expect. Maybe you can give me a hand and point where 
it is going wrong.


The function that is not working correctly belongs to a Paper Rock 
Scissor game I am making.


This particular function is responsible to:
  a) Get the user's choice (Paper, Rock, or Scissors)
  b) Return the user's choice within the variable choice to the 
function that called it.


The function works correctly as long as the user _does not try to 
enter a string other than_ 'P', 'R', or 'S'.


Logic:
Take the user's string and put it in the variable choice.
If choice is not 'P', 'R', or 'S'then pass a message to the user 
and call the function again.
If the choice is 'P', 'R', or 'S'then return choice to where it 
was called from.


The problem is this.

When the user enters a string other than the valid ones, the if 
statements catches it and calls the same function again so the user 
can enter a valid string. But the variable choice does not get 
assigned the new string entered by the user, instead it is empty.


I would expect if the function runs again, the variable choice would 
be updated to the last value given by the user.


The function: ( http://dpaste.com/644857/)

def  UserChoice  ():# The function that returns the choice from the user
print  'Please select (P) for paper, (R) for Rock, or (S) for Scissors.'
choice  =  raw_input('What is your selection?:')

if  choice.lower()  not  in  ('p',  'r','s'):   # Converts the user's 
choice to lowercase and confirms the choice is valid
print  'I am sorry, you entered\''  +  choice.upper()  +  '\'  
which is an invalid response. Please try again.'
raw_input('Press Enter to try again.')
UserChoice  ()  # If the choice is not valid, run the 
function over
else:
return  choice


Output with no problems: ( http://dpaste.com/644866/) 


Welcome to the PRS game.

Please select (P) for paper, (R) for Rock, or (S) for Scissors.
What is your selection?: s

You threw down Scissors while the computer threw down Rock

LOOSE
Output with problems: ( http://dpaste.com/644868/)

Welcome to the PRS game.

Please select (P) for paper, (R) for Rock, or (S) for Scissors.
What is your selection?: L
I am sorry, you entered 'L' which is an invalid response. Please try again.
Press Enter to try again.
Please select (P) for paper, (R) for Rock, or (S) for Scissors.
What is your selection?: s

You threw down None while the computer threw down Paper

LOOSE
Here's the full source code in case the problem is outside of the 
function: ( http://dpaste.com/644873/)


import  random  # Import the random library

def  main  ():  # The main function that gets called from main()
print  '\nWelcome to the PRS game.\n'

choice  =  UserChoice  ()   # Gets the choice from the user
cchoice  =  ComputerChoice  ()  # Gets the choice from the 
computer

PrintOutcome  (choice,  cchoice)# Passes both choices to the 
PrintChoice function for display


return  0

def  UserChoice  ():# The function that returns the choice from the user
print  'Please select (P) for paper, (R) for Rock, or (S) for Scissors.'
choice  =  raw_input('What is your selection?:')

if  choice.lower()  not  in  ('p',  'r','s'):   # Converts the user's 
choice to lowercase and confirms the choice is valid
print  'I am sorry, you entered\''  +  choice.upper()  +  '\'  
which is an invalid response. Please try again.'
raw_input('Press Enter to try again.')
UserChoice  ()  # If the choice is not valid, run the 
function over
else:
return  choice

def  ComputerChoice  ():# The function that returns the choice 
from the computer
PRS  =  ['Rock',  'Paper',  'Scissors'] # A list of choices

cchoice  =  random.choice(PRS)  # Choose a random item from the list

return  cchoice # Return the function

def  PrintOutcome  (UC,  CC):   # Function responsable to display the 
choices and results
PRS  =  ['Rock',  'Paper',  'Scissors']

# Convert the letters to words
if  UC  ==  'r':
UC  =  PRS[0]
elif  UC  ==  'p':
UC  =  PRS[1]
elif  UC  ==  's':
UC  =  PRS[2]

print  '\n\tYou threw down',  UC,  'while the computer threw down',  CC 
 +'\n'

# find the outcome of the game
if  UC  ==  CC:
print  'We have a tie, both players gain a point!'
elif  UC  ==  'Rock'  and  CC  ==  'Scissors':
print  'WIN'
elif  UC  ==  'Paper'  and  

Re: [Tutor] Paper Rock Scissors game - User's choice not returned properly

2011-10-31 Thread Marc Tompkins
On Mon, Oct 31, 2011 at 10:57 AM, Joel Montes de Oca
 wrote:
>
>  I came up with this to solve the problem.
>
> def UserChoice ():    # The function that returns the choice from the user
>     while 1:
>
>         print 'Please select (P) for paper, (R) for Rock, or (S) for 
> Scissors.'
>         choice = raw_input('What is your selection?: ')
>         if choice.lower() in ('p', 'r','s'):    # Converts the user's choice 
> to lowercase and confirms the choice is valid
>             return choice
>             break
>         else:
>             print 'Try again.'
>
> It puts the choice into a loop and only exits when the user enters a valid 
> value. It works and it's so much easier to read too!
>

You could simplify it even further by actually using the "while":

> def UserChoice ():    # The function that returns the choice from the user
>    choice = ''
>    attempt = 0
>    while choice.lower() not in ('p', 'r','s'):
>        if attempt > 0: print 'Please try again.'
>        print 'Please select (P) for paper, (R) for Rock, or (S) for Scissors.'
>        choice = raw_input('What is your selection?: ')
>        attempt +=1
>    return choice.lower()

It's a matter of personal preference, but I try to avoid "while 1" or
"while True" loops if at all possible.  For one thing, it seems
counter-productive to set up a loop that doesn't exit, and then to
have to use 'break' to get out of it!

One last thing:  HTML formatting is pretty, but it tends to screw
things up.  Someone else is bound to say it if I don't, so:  please
use plain text only when submitting code to the list.  Thanks!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Paper Rock Scissors game - User's choice not returned properly

2011-10-31 Thread Prasad, Ramit
Just a minor note, this break is redundant. Breaks are used to exit (for/while) 
loops but keep control in the function. A return exits the function 
immediately. 

if choice.lower() in ('p', 'r','s'):# Converts the user's choice to 
lowercase and confirms the choice is valid
return choice
break


There is also a "continue" which is similar to a break, but instead of exiting 
the loop, it will start the loop code over for the next value (thus 
"continuing" the loop).

>>> t = [ 'not this', 'do this', 'not this either', 'most definitely do this' ]
>>> for string in t:
... if string.startswith( 'not' ):
... continue # I want to keep working with the other elements in the 
list
... print string
... 
do this
most definitely do this
>>> for string in t:
... if string.startswith( 'not' ):
... break # I want to abort the entire loop now
... print string
... 
>>>




Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 92, Issue 123

2011-10-31 Thread Alan Gauld

On 31/10/11 12:56, Rinu Boney wrote:

I Use Windows.I Already Know C/C++ which makes python syntax seem very easy.
Maybe Setting Up Emacs With Python Will Make Me Productive.


If you learn emacs then it will.
But learning emacs is almost as big a task as learning Python, it is a 
complete user environment not just a text editor.



I Have Eclipse With PyDev.


Then you will have most of the features you would get from emacs just in 
a more Windows-like style.



Why Is There Not A Pythonic Emacs?


There is, in that there is a python mode plug-in that provides an 
interactive prompt, syntax highlighting, auto-completion, debugging 
support etc. but it's all integrated with the standard emacs way of 
working because thats what emacs users expect. Python works just like 
perl, C++, Lisp, Smalltalk and all the other languages that are 
supported on emacs. But that is the point, emacs makes everything look 
like emacs. emacs does not try to look like every other Windows IDE.

And emacs looks a lot more like Unix than it does like Windows...

And there is no python macro language for emacs because emacs is a macro 
language. The original emacs was just a set of macros for the Teco 
editor. That got rewritten in lisp to become emacs as we know it but 99% 
of what you see in emacs is implemented in lisp macros over a very small 
core of C code. That's what gives it its power and its complexity 
because users have written macros to read mail, usenet, browse the web, 
do ftp transfers etc etc... And writing Python programs is just one more 
set of macros.



On Mon, Oct 31, 2011 at 8:23 AM, mailto:tutor-requ...@python.org>> wrote:

Send Tutor mailing list submissions to
tutor@python.org 



BTW please do not send the entire contents of the digest with your 
mails. Its not good for those who pay by the byte... or have small 
memory devices(like smart phones).


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

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


Re: [Tutor] Paper Rock Scissors game - User's choice not returned properly

2011-10-31 Thread Joel Montes de Oca

On 10/31/2011 02:13 PM, Prasad, Ramit wrote:

Just a minor note, this break is redundant. Breaks are used to exit (for/while) 
loops but keep control in the function. A return exits the function immediately.

 if choice.lower() in ('p', 'r','s'):# Converts the user's choice 
to lowercase and confirms the choice is valid
 return choice
 break


There is also a "continue" which is similar to a break, but instead of exiting the loop, 
it will start the loop code over for the next value (thus "continuing" the loop).


t = [ 'not this', 'do this', 'not this either', 'most definitely do this' ]
for string in t:

... if string.startswith( 'not' ):
... continue # I want to keep working with the other elements in the 
list
... print string
...
do this
most definitely do this

for string in t:

... if string.startswith( 'not' ):
... break # I want to abort the entire loop now
... print string
...



Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Awesome, thanks for the tip. I removed the break from the code.

Thanks again.

--
-Joel M.

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


Re: [Tutor] Paper Rock Scissors game - User's choice not returned properly

2011-10-31 Thread Alan Gauld

On 31/10/11 17:09, Joel Montes de Oca wrote:


FUN MAIN
   |
   |
   |__ FUN A
   |
   |
   |_ FUN B

This is how I understand it. So if I want this to work, I need FUN B to
give something back to FUN A so that FUN A will have something to give
back to FUN MAIN but that doesn't feel right.


It is right. You need to add a return statement to your code like so:

def UserChoice ():  

if choice.lower() not in ('prs'): # NB use a single string
...
raw_input('Press Enter to try again.')
return UserChoice ()   # must return the value to caller
else:
return choice# just as you do here

But this is not the best way to use recursion...


Is there a way to say GO TO FUN A instead of calling the function?


Yes, in a while loop. As a later post shows you figured  out!
That's a much better solution. But this shows that you could have used 
recursion if you really wanted to.


HTH,

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

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


Re: [Tutor] Paper Rock Scissors game - User's choice not returned properly

2011-10-31 Thread Joel Montes de Oca

On 10/31/2011 02:14 PM, Marc Tompkins wrote:

On Mon, Oct 31, 2011 at 10:57 AM, Joel Montes de Oca
  wrote:

  I came up with this to solve the problem.

def UserChoice ():# The function that returns the choice from the user
 while 1:

 print 'Please select (P) for paper, (R) for Rock, or (S) for Scissors.'
 choice = raw_input('What is your selection?: ')
 if choice.lower() in ('p', 'r','s'):# Converts the user's choice 
to lowercase and confirms the choice is valid
 return choice
 break
 else:
 print 'Try again.'

It puts the choice into a loop and only exits when the user enters a valid 
value. It works and it's so much easier to read too!


You could simplify it even further by actually using the "while":


def UserChoice ():# The function that returns the choice from the user
choice = ''
attempt = 0
while choice.lower() not in ('p', 'r','s'):
if attempt>  0: print 'Please try again.'
print 'Please select (P) for paper, (R) for Rock, or (S) for Scissors.'
choice = raw_input('What is your selection?: ')
attempt +=1
return choice.lower()

It's a matter of personal preference, but I try to avoid "while 1" or
"while True" loops if at all possible.  For one thing, it seems
counter-productive to set up a loop that doesn't exit, and then to
have to use 'break' to get out of it!

One last thing:  HTML formatting is pretty, but it tends to screw
things up.  Someone else is bound to say it if I don't, so:  please
use plain text only when submitting code to the list.  Thanks!
Things for the tip Mark, I have set up Thunderbird to send text only 
when emailing the python.org domain.


--
-Joel M.

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


[Tutor] Use of subject line [Was: Re: Tutor Digest, Vol 92, Issue 127]

2011-10-31 Thread Alan Gauld

On 31/10/11 15:59, Asokan Pichai wrote:


From: Joel Montes de Oca mailto:joelmonte...@gmail.com>>
To: Tutor Python mailto:tutor@python.org>>
Subject: [Tutor] Paper Rock Scissors game - User's choice not returned
properly


If replying via the digest please change the subject line to something 
meaningful - preferably the same as the original!


Alan G.
List moderator


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


Re: [Tutor] Paper Rock Scissors game - User's choice not returned properly

2011-10-31 Thread Wayne Werner
On Mon, Oct 31, 2011 at 1:14 PM, Marc Tompkins wrote:

>
> You could simplify it even further by actually using the "while":
>
> > def UserChoice ():# The function that returns the choice from the
> user
> >choice = ''
> >attempt = 0
> >while choice.lower() not in ('p', 'r','s'):
> >if attempt > 0: print 'Please try again.'
> >print 'Please select (P) for paper, (R) for Rock, or (S) for
> Scissors.'
> >choice = raw_input('What is your selection?: ')
> >attempt +=1
> >return choice.lower()
>
> It's a matter of personal preference, but I try to avoid "while 1" or
> "while True" loops if at all possible.  For one thing, it seems
> counter-productive to set up a loop that doesn't exit, and then to
> have to use 'break' to get out of it!
>

As a slight aside, I came up with a (fairly) simple recipe for this sort of
occasion:

def prompt(choices):
try:
for choice, desc in choices:
print("%2s. %s" % (choice, desc))
prompt.choice = input("Choice: ") #use raw_input in Python 2.x
print()
return prompt.choice
except TypeError:
raise ValueError("prompt expects collection of pairs")

Then you can do something like this:

while prompt([("P", "Paper"), ("R", "Rock"), ("S", "Scissors)]).lower() not
in ('p', 'r', 's'):
print("Error: ", prompt.choice, " is not a valid choice!")

#do something with prompt.choice here

It handles keeping track of whatever the last choice was for you, and all
you have to do is pass it a collection of pairs. If you wanted to make it
specifically for your application, you could just change it to this:

def prompt():
   print("(P)aper")
   print("(R)ock")
   print("or (S)cissors?")
   prompt.choice = raw_input("Choice: ")
   return prompt.choice

while prompt().lower() not in ('p', 'r', 's'):
   #print error message

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


Re: [Tutor] Tutor Digest, Vol 92, Issue 123

2011-10-31 Thread Tim Johnson
* Rinu Boney  [111031 07:03]:
> I Use Windows.I Already Know C/C++ which makes python syntax seem very easy.
> Maybe Setting Up Emacs With Python Will Make Me Productive.
> I Have Eclipse With PyDev.
> Why Is There Not A Pythonic Emacs?
  Rinu, by this time I believe that Alan has addressed your question
  above. He has also (wisely) provided caveats regarding the
  difficulty of learning emacs itself. 

  I'll take a reverse of Alan's comments, not to contradict him, but
  to give a possible different perspective:

  If you learn to use emacs with python, you will essentially be
  learning *two* programming languages: Python _and_ elisp, which is
  the internal programming language of emacs. Emacs is essentially
  an elisp interpreter. There may be advantages to learning two
  languages simultaneously. 

  This will take time. A lot of time. Do you have the time? Will you
  be compensated for the time? :) having two additional programming
  languages "under your belt" may be considered compensation.

  In case you do not know this: Emacs has the ability to run the
  python or language-your-choice interpreter asynchronous within the
  editor, in it's own window. There could be great advantages to
  this. I have in the past, written elisp code that allows me two
  write code in one window and have it evaluated in the 'python
  window' or 'language-of-your-choice window'.

  I'll reiterate what I said earlier, I no longer use emacs, but
  have great respect for it. I use vim linked against the python
  binary so that I can use python code to enhance my (hand-rolled)
  "IDE".  I much prefer python code to elisp code.

  I hope my comments are of some help. I'm sure that you have been
  well informed as to what you would be getting youself into. :)
  regards
-- 
Tim 
tim at tee jay forty nine dot com or akwebsoft dot com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Paper Rock Scissors game - User's choice not returned properly

2011-10-31 Thread Peter Otten
Alan Gauld wrote:

> if choice.lower() not in ('prs'): # NB use a single string

That's not a good idea. If a user accidentally enters PR (for example) your 
version will mistake that for a valid choice. 


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


Re: [Tutor] Paper Rock Scissors game - User's choice not returned properly

2011-10-31 Thread Peter Otten
Joel Montes de Oca wrote:

> def  UserChoice  (): # The function that returns the choice from the
> user
>  while  1:
> 
>  print  'Please select (P) for paper, (R) for Rock, or (S) for
>  Scissors.'
>  choice  =  raw_input('What is your selection?:')
>  if  choice.lower()  in  ('p',  'r','s'): # Converts the
>  user's choice to lowercase and confirms the choice is valid
>  return  choice
>  break
>  else:
>  print  'Try again.'

There's a problem with this code that I think nobody has addressed yet: if 
you enter a lowercase letter, say "p", your function returns "p", if you 
enter an uppercase "P" it returns "P". The calling code in

http://dpaste.com/644873/copy/

# Convert the letters to words
if UC == 'r':
UC = PRS[0]
elif UC == 'p':
UC = PRS[1]
elif UC == 's':
UC = PRS[2]

doesn't handle this case correctly. The best way is of course to normalize 
the code returned by the UserChoice() function

...
choice  =  raw_input('What is your selection?:').lower()
if  choice  in  ('p',  'r', 's'):
return choice
...


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


Re: [Tutor] Tutor Digest, Vol 92, Issue 128

2011-10-31 Thread Steven D'Aprano

Asokan Pichai wrote:

Hugo's explanation is nice and clear.

[...]

Who are you replying to, and what was the question?

Thank you for NOT quoting the entire digest, hundreds and hundreds of 
lines! You would be amazed at how many people do that. But in future, 
could you please quote *just enough* so that we can see who you are 
replying to, and what the context of your comments are? Because I have 
no idea what you are talking about in your email.


And finally, please change the subject line to something meaningful, not 
"Re Tutor Digest". This is especially important because replying to a 
digest breaks email threading.


You may prefer to change to individual emails instead of digest mode. In 
my opinion, digest mode is only useful when you want to read other 
people's comments without commenting yourself.




--
Steven

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


Re: [Tutor] Paper Rock Scissors game - User's choice not returned properly

2011-10-31 Thread Alan Gauld

On 31/10/11 20:22, Peter Otten wrote:

Alan Gauld wrote:


if choice.lower() not in ('prs'): # NB use a single string


That's not a good idea. If a user accidentally enters PR (for example) your
version will mistake that for a valid choice.


Good point, although  you could test the first character only...

if choice[0].lower() not in ('prs'): # NB use a single string


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

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


Re: [Tutor] Tutor Digest, Vol 92, Issue 128

2011-10-31 Thread Alan Gauld

On 31/10/11 20:55, Steven D'Aprano wrote:


You may prefer to change to individual emails instead of digest mode. In
my opinion, digest mode is only useful when you want to read other
people's comments without commenting yourself.


It depends, I've used digests from other lists that delivered
the mails as embedded messages that you could open individually
and replies then followed the original. I think that requires
MIME encoding in the digest. But I've never tried it on the
tutor list so I don't know if it works here.

And digests are useful if you are on a tariff that limits the
number of messages received because they see the digest as
one message. But OTOH I haven't seen anyone offering message
based access for a quite a few years now.

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

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


Re: [Tutor] Tutor Digest, Vol 92, Issue 128

2011-10-31 Thread Dave Angel

On 10/31/2011 06:09 PM, Alan Gauld wrote:

On 31/10/11 20:55, Steven D'Aprano wrote:


You may prefer to change to individual emails instead of digest mode. In
my opinion, digest mode is only useful when you want to read other
people's comments without commenting yourself.


It depends, I've used digests from other lists that delivered
the mails as embedded messages that you could open individually
and replies then followed the original. I think that requires
MIME encoding in the digest. But I've never tried it on the
tutor list so I don't know if it works here.

And digests are useful if you are on a tariff that limits the
number of messages received because they see the digest as
one message. But OTOH I haven't seen anyone offering message
based access for a quite a few years now.

I used digest mode (here and in python-list) up until a few weeks ago.  
It worked fine (in Thunderbird) replying to one of the embedded messages.


I don't remember just what digest mode I had picked, but not all choices 
worked this way.  Anyway, when I got a new email address, I also 
switched to individual emails.


--

DaveA

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


Re: [Tutor] Tutor Digest, Vol 92, Issue 128

2011-10-31 Thread bob gailer

On 10/31/2011 1:26 PM, Asokan Pichai wrote:

Hugo's explanation is nice and clear.

You may also want to look at this way
Consider the most simplified form of the issue

def alpha():
  if  X:
   beta()
  else:
   return q

Here in the*if branch* nothing is returned


None is returned, not nothing.

while in the *else branch *something is being returned.

That is  whenever X is True nothing is returned from alpha().
Even if beta() returns something that is not being used.

But when X is False something (q in this simplistic example)
is being returned

So this is a bug.

HTH

Asokan Pichai
SVP - Learning and Development

"Faith consists in believing when it is beyond the power of reason to 
believe. "

Voltaire 




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



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

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


Re: [Tutor] Paper Rock Scissors game - User's choice not returned properly

2011-10-31 Thread Steven D'Aprano

Alan Gauld wrote:

On 31/10/11 20:22, Peter Otten wrote:

Alan Gauld wrote:


if choice.lower() not in ('prs'): # NB use a single string


That's not a good idea. If a user accidentally enters PR (for example) 
your

version will mistake that for a valid choice.


Good point, although  you could test the first character only...

if choice[0].lower() not in ('prs'): # NB use a single string


Why would you do that? If the user is supposed to enter a single letter, 
why would you accept (for example) "screw you hippy, I hate this game!" 
as the valid response "s"?




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


Re: [Tutor] Paper Rock Scissors game - User's choice not returned properly

2011-10-31 Thread Steven D'Aprano

Joel Montes de Oca wrote:

When the user enters an invalid letter, FUNCTION B calls FUNCTION A. 
FUNCTION A returns choice to FUNCTION B. FUNCTION B does nothing with 
the return, FUNCTION MAIN gets nothing to returned to it, thus choice is 
NONE.


FUN MAIN
  |
  |
  |__ FUN A
  |
  |
  |_ FUN B

This is how I understand it. So if I want this to work, I need FUN B to 
give something back to FUN A so that FUN A will have something to give 
back to FUN MAIN but that doesn't feel right.


But that's exactly right.

Think of people at a dinner table. Fred turns to Barney and says "Pass 
me the salt please." Barney can't reach the salt, so he turns to Wilma 
and asks the same thing. Wilma hands Barney the salt. Now Barney has to 
actually hand the salt to Fred or else Fred doesn't get anything.


So if you care about getting a value back from something, and passing it 
on elsewhere, you MUST use return.



Is there a way to say GO TO FUN A instead of calling the function?


No. That's what a function call is: it's a safe goto. (Technically, it's 
more like GOSUB if you remember your BASIC.)




--
Steven

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


[Tutor] Help

2011-10-31 Thread Chris Kavanagh
This code is from the book 'Invent your own computer games with Python' 
2nd edition. Great book so far. . .


My question comes on the 2nd game (dragon game). Just a simple little 
program that lets you choose to enter 'cave one' or 'cave two' by using 
the random module, radnom.randint. If you choose the 'wrong' cave, you 
get a message saying 'sorry you've been eaten'. Choose the correct cave 
and you get a message that 'you get the treasure. Pretty simple. .


However, I'm confused on Line 30 {if chosenCave== str(friendlyCave)}. 
Here's the description of this line the author gives:


"Here we check if the integer of the cave we chose ('1' or '2') is equal 
to the cave

randomly selected to have the friendly dragon"

My question is, we saved the integer of the cave we chose in the 
variable {cave}in line 15, not {chosenCave}. So, what the heck am I 
missing?? How is the {chosenCave} variable now holding the choice I made 
in the {cave} variable??


Keep in mind I'm a beginner, but geez, I should understand this easily! 
I'm very frustrated right now, I should easily know this. But, I don't, 
lol. Thanks in advance for any help!! Code below:






dragon.py
This code can be downloaded from http://inventwithpython.com/dragon.py
If you get errors after typing this code in, compare it to the book's 
code with the online

diff tool at http://inventwithpython.com/diff or email the author at
a...@inventwithpython.com

1. import random
2. import time
3.
4. def displayIntro():
5. print('You are on a planet full of dragons. In front
of you,')
6. print('you see two caves. In one cave, the dragon is
friendly')
7. print('and will share his treasure with you. The
other dragon')
8. print('is greedy and hungry, and will eat you on
sight.')
9. print()
10.
11. def chooseCave():
12. cave = ''
13. while cave != '1' and cave != '2':
14. print('Which cave will you go into? (1 or 2)')
15. cave = input()
16.
17. return cave
18.
19. def checkCave(chosenCave):
20. print('You approach the cave...')
21. time.sleep(2)
22. print('It is dark and spooky...')
23. time.sleep(2)
24. print('A large dragon jumps out in front of you! He
opens his jaws and...')
25. print()
26. time.sleep(2)
27.
28. friendlyCave = random.randint(1, 2)
29.
30. if chosenCave == str(friendlyCave):
31. print('Gives you his treasure!')
32. else:
33. print('Gobbles you down in one bite!')
34.
35. playAgain = 'yes'
36. while playAgain == 'yes' or playAgain == 'y':
37.
38. displayIntro()
58
39.
40. caveNumber = chooseCave()
41.
42. checkCave(caveNumber)
43.
44. print('Do you want to play again? (yes or no)')
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple Question On A Method (in subclass)

2011-10-31 Thread Steven D'Aprano

Marc Tompkins wrote:

It can be a little hard to wrap your head around how Python handles
variables/objects; in other languages you create a variable and assign a
value to it, while in Python you create an object and assign a name to it -
the name can change while the object remains unchanged.  Here's a very
simplified demo of what Dave is talking about:

[...]

It's extremely logical, but almost entirely backward from the way most other
languages do things.  Possibly it's because Guido is Dutch.


Fortunately, that is untrue.

I'm not sure where the myth that "Python is different from other 
languages" comes from. I suppose it is true only so far as *every* 
language is different from any other language (otherwise they would be 
the same language!). But Python is not so different from other common 
languages.


In particular, I don't know of any language where assignment means 
aliasing. Take the example Marc gave earlier:


t = 'this'
s = 'that'
group = [t, s]
print group  # => "['this', 'that']
s = 'the other'
print group  # => "['this', 'that']

I don't know of any language where the second item of group would now 
equal 'the other'. Pascal certainly isn't one:


program example (input, output);
var
  t,s: String(10);
  group: array[1..2] of String(10);
begin
  t:='this';
  s:='that';
  group[1]:=t;
  group[2]:=s;
  writeln(group[1], ' ', group[2]);
  s:='the other';
  writeln(group[1], ' ', group[2]);
end.


Running that program gives the equivalent output to Python:

this that
this that


PHP is the same. Using the PHP interactive shell:

php > $t = 'this';
php > $s = 'that';
php > $group[0] = $t;
php > $group[1] = $s;
php > print_r($group);
Array
(
[0] => this
[1] => that
)
php > $t = 'the other';
php > print_r($group);
Array
(
[0] => this
[1] => that
)


This myth of Python being radically different from other languages is 
especially mysterious since many of the most popular and common modern 
languages use *exactly* the same name binding execution model as Python, 
e.g. Java and Ruby. (In the case of Java, that only applies to boxed 
objects, and not unboxed low-level ints and similar. If this means 
nothing to you, feel fortunate.)





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


Re: [Tutor] Help

2011-10-31 Thread Steven D'Aprano

Chris Kavanagh wrote:

However, I'm confused on Line 30 {if chosenCave== str(friendlyCave)}. 
Here's the description of this line the author gives:


"Here we check if the integer of the cave we chose ('1' or '2') is equal 
to the cave

randomly selected to have the friendly dragon"

My question is, we saved the integer of the cave we chose in the 
variable {cave}in line 15, not {chosenCave}. So, what the heck am I 
missing?? How is the {chosenCave} variable now holding the choice I made 
in the {cave} variable??


Unfortunately, the indentation of your code is completely mangled for 
me, which makes it difficult to be sure which parts of the code are 
inside functions and which are not. So I will be forced to guess.


I can tell that line 15 is inside the function chooseCave(), and so the 
variable "cave" is a local variable. Local variables only exist inside 
the function that creates them. In this case, the chooseCave() function 
returns the value of "cave" to the caller.


That is, at the end of your code, you call the functions you earlier 
created:


caveNumber = chooseCave()
checkCave(caveNumber)


These two lines cause the following to happen:

The function chooseCave() gets called. Execution shifts into the 
function chooseCave:


  1 you are asked for a cave number
  2 your response is stored temporarily in the local variable "cave"
  3 and then returned to the caller

At this point, Python clears up the local variables, reclaiming their 
memory ready for next time they are needed, and stores your response in 
the global (top level) variable "caveNumber".


Next, you call the checkCave function with "caveNumber" as an argument. 
This gets passed to the checkCave function, which sees it under the 
local variable name "chosenCave". *Inside* the checkCave function, the 
value which is known *outside* as "caveNumber" is known as "chosenCave". 
And so inside the function, the line:


if chosenCave== str(friendlyCave)

works and the chosen cave number (known as "caveNumber" on the outside 
and "chosenCave" on the inside) is compared to the friendly cave.


This might seem a bit confusing at first, but stick with it, it will 
soon become completely natural.


Having different names for the same value in different contexts is a 
good thing. It's a bit like how the same person might be called:


Mr President
Barrack Obama
Mr Obama
Barrack
Dad
Son
POTUS
Bazza

depending on who is referring to him and under what circumstances. (That 
last one might only be in Australia...)


The important thing to remember is this:


*Outside* of a function, all variables are *global*. You can't have two 
global variables called "x" at the same time:


x = 1
x = 2

The second line replaces the value of x with a new value.

*Inside* a function, all variable assignments are *local*. (You can 
change that with the "global" keyword, but you shouldn't.) A bit like 
going to Los Angeles, what happens inside a function stays inside the 
function. Local variable "x" doesn't interfere with global variable "x", 
or with local "x" of any other function. The only way to get the value 
of local "x" out and pass it to another function is with the return 
statement.



I hope this helps.



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


Re: [Tutor] Paper Rock Scissors game - User's choice not returned properly

2011-10-31 Thread Joel Montes de Oca

On 10/31/2011 07:10 PM, Steven D'Aprano wrote:

Alan Gauld wrote:

On 31/10/11 20:22, Peter Otten wrote:

Alan Gauld wrote:


if choice.lower() not in ('prs'): # NB use a single string


That's not a good idea. If a user accidentally enters PR (for 
example) your

version will mistake that for a valid choice.


Good point, although  you could test the first character only...

if choice[0].lower() not in ('prs'): # NB use a single string


Why would you do that? If the user is supposed to enter a single 
letter, why would you accept (for example) "screw you hippy, I hate 
this game!" as the valid response "s"?




I agree, I am not sure that I see the benefit of using a single string. 
If anything, it makes it a bit harder to read by someone other than the 
person who wrote it.


   if choice.lower() in ('p', 'r','s'):

I think the code above is a lot clearer.

--
-Joel M.

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


Re: [Tutor] Help

2011-10-31 Thread Chris Kavanagh
Yes Steven, that solved my question(s). It also cleared up what was to 
be my next question! Thanks so much. You might not realize how grateful 
I am to be able to have you & others on the list answer my questions. 
Just trust me when I say, I am grateful. And I apologize for the code 
being mangled on your end. I'm not sure why this happened, but you were 
correct in your assumptions. . .


One thing I'm curious about. If the code is read by the Interpreter or 
Compiler from the top down, why in this case, does it not get confused 
(cause an error) when it hits line 30, if it doesn't yet know that 
{caveNumber=chooseCave()} and checkCave(caveNumber)}?? It seems to me in 
my limited experience, those last two lines should've come before line 
30. It seems as though it would've made more sense to somehow put them 
before. In other languages, ala C++, don't global variables have to be 
declared at the 'top' of the code??


On 10/31/2011 9:55 PM, Steven D'Aprano wrote:

Chris Kavanagh wrote:


However, I'm confused on Line 30 {if chosenCave== str(friendlyCave)}.
Here's the description of this line the author gives:

"Here we check if the integer of the cave we chose ('1' or '2') is
equal to the cave
randomly selected to have the friendly dragon"

My question is, we saved the integer of the cave we chose in the
variable {cave}in line 15, not {chosenCave}. So, what the heck am I
missing?? How is the {chosenCave} variable now holding the choice I
made in the {cave} variable??


Unfortunately, the indentation of your code is completely mangled for
me, which makes it difficult to be sure which parts of the code are
inside functions and which are not. So I will be forced to guess.

I can tell that line 15 is inside the function chooseCave(), and so the
variable "cave" is a local variable. Local variables only exist inside
the function that creates them. In this case, the chooseCave() function
returns the value of "cave" to the caller.

That is, at the end of your code, you call the functions you earlier
created:

caveNumber = chooseCave()
checkCave(caveNumber)


These two lines cause the following to happen:

The function chooseCave() gets called. Execution shifts into the
function chooseCave:

1 you are asked for a cave number
2 your response is stored temporarily in the local variable "cave"
3 and then returned to the caller

At this point, Python clears up the local variables, reclaiming their
memory ready for next time they are needed, and stores your response in
the global (top level) variable "caveNumber".

Next, you call the checkCave function with "caveNumber" as an argument.
This gets passed to the checkCave function, which sees it under the
local variable name "chosenCave". *Inside* the checkCave function, the
value which is known *outside* as "caveNumber" is known as "chosenCave".
And so inside the function, the line:

if chosenCave== str(friendlyCave)

works and the chosen cave number (known as "caveNumber" on the outside
and "chosenCave" on the inside) is compared to the friendly cave.

This might seem a bit confusing at first, but stick with it, it will
soon become completely natural.

Having different names for the same value in different contexts is a
good thing. It's a bit like how the same person might be called:

Mr President
Barrack Obama
Mr Obama
Barrack
Dad
Son
POTUS
Bazza

depending on who is referring to him and under what circumstances. (That
last one might only be in Australia...)

The important thing to remember is this:


*Outside* of a function, all variables are *global*. You can't have two
global variables called "x" at the same time:

x = 1
x = 2

The second line replaces the value of x with a new value.

*Inside* a function, all variable assignments are *local*. (You can
change that with the "global" keyword, but you shouldn't.) A bit like
going to Los Angeles, what happens inside a function stays inside the
function. Local variable "x" doesn't interfere with global variable "x",
or with local "x" of any other function. The only way to get the value
of local "x" out and pass it to another function is with the return
statement.


I hope this helps.




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


Re: [Tutor] Help

2011-10-31 Thread Chris Kavanagh
I'm going to thank Steven once again, and answer my own question in the 
2nd paragraph directly below (Steven hasn't had a chance to respond yet).


I just learned that the Function definitions are not read by the 
interpreter UNTIL they are called. I was reading them and assuming they 
were executed from the top down. Obviously I was getting somewhat 
confused because of this. This 'dragon' program makes much more sense to 
me now that I understand that. . .Thanks again Steven & everyone!!!

Happy Halloween!!!

On 10/31/2011 11:07 PM, Chris Kavanagh wrote:

Yes Steven, that solved my question(s). It also cleared up what was to
be my next question! Thanks so much. You might not realize how grateful
I am to be able to have you & others on the list answer my questions.
Just trust me when I say, I am grateful. And I apologize for the code
being mangled on your end. I'm not sure why this happened, but you were
correct in your assumptions. . .

One thing I'm curious about. If the code is read by the Interpreter or
Compiler from the top down, why in this case, does it not get confused
(cause an error) when it hits line 30, if it doesn't yet know that
{caveNumber=chooseCave()} and checkCave(caveNumber)}?? It seems to me in
my limited experience, those last two lines should've come before line
30. It seems as though it would've made more sense to somehow put them
before. In other languages, ala C++, don't global variables have to be
declared at the 'top' of the code??

On 10/31/2011 9:55 PM, Steven D'Aprano wrote:

Chris Kavanagh wrote:


However, I'm confused on Line 30 {if chosenCave== str(friendlyCave)}.
Here's the description of this line the author gives:

"Here we check if the integer of the cave we chose ('1' or '2') is
equal to the cave
randomly selected to have the friendly dragon"

My question is, we saved the integer of the cave we chose in the
variable {cave}in line 15, not {chosenCave}. So, what the heck am I
missing?? How is the {chosenCave} variable now holding the choice I
made in the {cave} variable??


Unfortunately, the indentation of your code is completely mangled for
me, which makes it difficult to be sure which parts of the code are
inside functions and which are not. So I will be forced to guess.

I can tell that line 15 is inside the function chooseCave(), and so the
variable "cave" is a local variable. Local variables only exist inside
the function that creates them. In this case, the chooseCave() function
returns the value of "cave" to the caller.

That is, at the end of your code, you call the functions you earlier
created:

caveNumber = chooseCave()
checkCave(caveNumber)


These two lines cause the following to happen:

The function chooseCave() gets called. Execution shifts into the
function chooseCave:

1 you are asked for a cave number
2 your response is stored temporarily in the local variable "cave"
3 and then returned to the caller

At this point, Python clears up the local variables, reclaiming their
memory ready for next time they are needed, and stores your response in
the global (top level) variable "caveNumber".

Next, you call the checkCave function with "caveNumber" as an argument.
This gets passed to the checkCave function, which sees it under the
local variable name "chosenCave". *Inside* the checkCave function, the
value which is known *outside* as "caveNumber" is known as "chosenCave".
And so inside the function, the line:

if chosenCave== str(friendlyCave)

works and the chosen cave number (known as "caveNumber" on the outside
and "chosenCave" on the inside) is compared to the friendly cave.

This might seem a bit confusing at first, but stick with it, it will
soon become completely natural.

Having different names for the same value in different contexts is a
good thing. It's a bit like how the same person might be called:

Mr President
Barrack Obama
Mr Obama
Barrack
Dad
Son
POTUS
Bazza

depending on who is referring to him and under what circumstances. (That
last one might only be in Australia...)

The important thing to remember is this:


*Outside* of a function, all variables are *global*. You can't have two
global variables called "x" at the same time:

x = 1
x = 2

The second line replaces the value of x with a new value.

*Inside* a function, all variable assignments are *local*. (You can
change that with the "global" keyword, but you shouldn't.) A bit like
going to Los Angeles, what happens inside a function stays inside the
function. Local variable "x" doesn't interfere with global variable "x",
or with local "x" of any other function. The only way to get the value
of local "x" out and pass it to another function is with the return
statement.


I hope this helps.




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

[Tutor] Pickle Class Instances

2011-10-31 Thread Rinu Boney
This Is My Program :
class book:
def __init__(self,bno=100,bname='Book'):
self.book_number=bno
self.book_name=bname
def enter_book(self):
self.book_number=input("Enter Book No : ")
self.book_name=input("Enter Book Name : ")
def display_book(self):
print('Book No : ',self.book_number)
print('Book Name : ',self.book_name)

b1 = book()
b=book()

def add_book(b):
fo=open('books.dat','wb')
pickle.dump(b,fo)
fo.close()

def display_books():
global b1
fi=open('books.dat','rb')
b1=pickle.load(fi)
b1.display_book()
fi.close()

The Display After Unpickling Shows only the last Class Instance.
How To Display All The Data In The File ?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Pickling Class Instances

2011-10-31 Thread Rinu Boney
I have a class 'book' and function for input and display of the class
members
then there are 2 functions for pickling and unpickling class instances from
and to a file.
after unpickling , then displaying it shows only the last class instance
stored in the file!
what can be the possible problems?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pickle Class Instances

2011-10-31 Thread Andreas Perstinger

On 2011-11-01 06:31, Rinu Boney wrote:

def add_book(b):
 fo=open('books.dat','wb')
 pickle.dump(b,fo)
 fo.close()

The Display After Unpickling Shows only the last Class Instance.
How To Display All The Data In The File ?


You haven't shown us the complete program (how to you call "add_book" 
and "display_books"?) but I guess that you call "add_book" with one 
instance (if not, you can ignore the rest). In that case there is no 
more data in the file.


In your "add_book" function you open the file "books.at" and just save 
one instance. The next time you call the function with another instance 
you overwrite the former, because opening the same file with the 
parameter "w" (or in your case "wb") deletes any already existing content.


What you probably want is to put all the instances into a list and save 
this list. When you later read the file, you'll get the list back and 
you can iterate over it for displaying.


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