[Tutor] factorial of anumber

2012-02-04 Thread Debashish Saha
*PROGRAM TO FIND FACTORIAL OF A NUMBER(I HAVE WRITTEN IT ON GEDIT)*
x=1
n=input('enter a positive integer no:')
for i in range(1,1+n):
x=x*i
print x


*ERROR:*

enter a positive integer
no:---
EOFError  Traceback (most recent call last)
C:\Python27\lib\site-packages\IPython\utils\py3compat.pyc in
execfile(fname, glob, loc)
166 else:
167 filename = fname
--> 168 exec compile(scripttext, filename, 'exec') in glob, loc
169 else:
170 def execfile(fname, *where):

C:\Users\as\mnb.py in ()
  1 x=1
> 2 n=input('enter a positive integer no:')
  3 for i in range(1,1+n):
  4 x=x*i
  5 print x

EOFError: EOF when reading a line

*QUESTION*:
HOW TO ASK INPUT FROM USER THEN?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Importing libraries

2012-02-04 Thread Blockheads Oi Oi

On 04/02/2012 05:37, Michael Lewis wrote:

Why don't I have to import str or list to access their attributes like I
do with the math or random or any other library?

--
Michael J. Lewis
mjole...@gmail.com 
415.815.7257



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


They're built in to Python so...

PythonWin 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit 
(Intel)] on win32.
Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' 
for further copyright information.

>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'pywin']
>>> help(__builtins__)
Help on built-in module __builtin__:

NAME
__builtin__ - Built-in functions, exceptions, and other objects.

FILE
(built-in)

DESCRIPTION
Noteworthy: None is the `nil' object; Ellipsis represents `...' in 
slices.


CLASSES
object
basestring
str
str
unicode
buffer
etc.

--
Cheers.

Mark Lawrence.

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


Re: [Tutor] factorial of anumber

2012-02-04 Thread Blockheads Oi Oi

On 04/02/2012 10:11, Debashish Saha wrote:

_PROGRAM TO FIND FACTORIAL OF A NUMBER(I HAVE WRITTEN IT ON GEDIT)_
x=1
n=input('enter a positive integer no:')
for i in range(1,1+n):
 x=x*i
print x


_ERROR:_

enter a positive integer
no:---
EOFError  Traceback (most recent call last)
C:\Python27\lib\site-packages\IPython\utils\py3compat.pyc in
execfile(fname, glob, loc)
 166 else:
 167 filename = fname
--> 168 exec compile(scripttext, filename, 'exec') in glob, loc
 169 else:
 170 def execfile(fname, *where):

C:\Users\as\mnb.py in ()
   1 x=1
> 2 n=input('enter a positive integer no:')
   3 for i in range(1,1+n):
   4 x=x*i
   5 print x

EOFError: EOF when reading a line

*QUESTION*:
HOW TO ASK INPUT FROM USER THEN?


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


It works fine for me.

>>> enter a positive integer no:>>> 6
720

And please DO NOT USE CAPITAL LETTERS or people may stop answering your 
questions.


--
Cheers.

Mark Lawrence.

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


Re: [Tutor] Importing libraries

2012-02-04 Thread Steven D'Aprano

Michael Lewis wrote:

Why don't I have to import str or list to access their attributes like I do
with the math or random or any other library?



Because they are built-in. That means they live inside the Python 
compiler/interpreter itself.


They are built-in because str, list, etc. are fundamental data types, used by 
the core Python interpreter, so they need to be available from the moment 
Python starts up, even before your code starts to run.


Other built-in objects include:

None
True and False
Ellipsis
NotImplemented
int
float
tuple
dict
many different exceptions such as ValueError, TypeError, etc.
many different functions, such as len, chr, abs, enumerate, etc.


Some of these are built-in because the interpreter won't run without them.

Some are built-in for convenience and speed: although the interpreter will run 
without them, they are so useful that it makes sense to treat them as 
critical, core objects.


And some are built-in just because they were built-in many years ago, and for 
backwards compatibility they have to stay built-in. (I'm thinking of functions 
like compile and eval.)




--
Steven

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


[Tutor] (no subject)

2012-02-04 Thread Debashish Saha
*input:*
import numpy as np
def f(y):
return (y/5)*2*(np.pi)*0.2


*results:*
f(11)
Out[109]: 2.5132741228718345

f(11.0)
Out[110]: 2.7646015351590183

*question:*
why did i get different values for the same input?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] SEE THE QUESTION AT THE BOTTOM

2012-02-04 Thread Steven D'Aprano

Debashish Saha wrote:

INPUT:



*for n in range(2, 1000):*

*for x in range(2, n):*

*if n % x == 0:*



Please don't add junk characters to your code. There is no need to add 
asterisks to each line, we can recognise Python code when we see it. Your code 
cannot run because of the junk added to the start and end of each line.


[...]


:QUESTION:

BUT I COULD NOT UNDERSTAND HOW THE COMMAND ELSE CAN WORK,THOUGH IT IS IN
THE OUTSIDE OF THE FOR LOOP IN WHICH IF COMMAND LIES.


Please do not SHOUT in ALL CAPITALS, it is considered rude.

In Python, "else" is not just for "if" statements:


if condition:
do_true_condition
else:
do_false_condition


Python also has "else" for for-loops and while-loops:


for x in sequence:
...
else:
# this part runs after the for loop is done


while condition:
...
else:
# this part runs after the while loop is done


In both cases, "break" inside the loop will skip past the "else" block without 
executing it.



Try blocks also have an else:


try:
...
except TypeError:
# code that runs if TypeError occurs
except ValueError:
# code that runs if ValueError occurs
else:
# code that runs if no error occurs
finally:
# code that runs no matter what


See the tutorial:

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

Start here:

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

(Although the site seems to be done just at the moment.)



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


Re: [Tutor] (no subject)

2012-02-04 Thread Steven D'Aprano

Debashish Saha wrote:

[...]

why did i get different values for the same input?


Please choose a sensible subject line when posting.

The problem is with the division. Watch:


py> 21/2
10
py> 21.0/2
10.5


By default, division in Python 2 is integer division: any remainder is 
ignored. To use floating point division, you need to make one of the arguments 
be a float.


In your function, you have division y/5. When y is 11, 11/5 gives 2 exactly. 
If y is 11.0, you get 2.2 (and a tiny bit, due to rounding).


This is confusing, so in Python 3 division works more like you expect, and you 
don't have to worry about this nonsense. Also, starting in Python 2.4, you can 
get the new, calculator-like behaviour by using a special command to change 
the interpreter:


py> 11/5
2
py> from __future__ import division
py> 11/5
2.2002


My advice is to always use "from __future__ import division" at the start of 
your programs.




--
Steven

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


Re: [Tutor] factorial of anumber

2012-02-04 Thread Steven D'Aprano

Debashish Saha wrote:

*PROGRAM TO FIND FACTORIAL OF A NUMBER(I HAVE WRITTEN IT ON GEDIT)*


This program is irrelevant. Your question has nothing to do with factorial of 
numbers. It is about getting input from the user. As you ask:



HOW TO ASK INPUT FROM USER THEN?


The answer is:

Do not use input, as it is dangerous and should not used. Use raw_input instead.

py> answer = raw_input("what is your name? ")
what is your name? Steven
py> print answer
Steven


This works fine. See if you can work out what is going on here, and understand 
why I say input is dangerous and should be avoided:


py> answer = input("what is your name? ")
what is your name? Steven
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1, in 
NameError: name 'Steven' is not defined


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


[Tutor] Urgent Help Required

2012-02-04 Thread Zafrullah Syed
Hi,

I need urgent help:

I am unable to commit code to svn, I am getting this warning:

*svn: Commit failed (details follow):*
*svn: Commit blocked by pre-commit hook (exit code 1) with output:*
*:17: Warning: 'with' will become a reserved keyword in Python 2.6*
*writeConf.py:17: invalid syntax*
*Commited Python-Files refused, please check and retry...*

How do i surpass this and commit my code??

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


Re: [Tutor] factorial of anumber

2012-02-04 Thread bob gailer

I for one prefer plain text rather than HTML for email.

Please in the future post plain text. No colors, no unusual fonts.

Makes it a LOT easier to read.

--
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] Tutor Digest, Vol 96, Issue 8

2012-02-04 Thread Zafrullah Syed
Hi,

I need urgent help:

I am unable to commit code to svn, I am getting this warning:

*svn: Commit failed (details follow):*
*svn: Commit blocked by pre-commit hook (exit code 1) with output:*
*:17: Warning: 'with' will become a reserved keyword in Python 2.6*
*writeConf.py:17: invalid syntax*
*Commited Python-Files refused, please check and retry...*

How do i surpass this and commit my code??

-- 
Regards,
Zafrullah Syed

On Sat, Feb 4, 2012 at 12:00 PM,  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. Re: SEE THE QUESTION AT THE BOTTOM (Steve Willoughby)
>   2. factorial of anumber (Debashish Saha)
>   3. Re: Importing libraries (Blockheads Oi Oi)
>   4. Re: factorial of anumber (Blockheads Oi Oi)
>
>
> --
>
> Message: 1
> Date: Fri, 03 Feb 2012 21:53:03 -0800
> From: Steve Willoughby 
> To: tutor@python.org
> Subject: Re: [Tutor] SEE THE QUESTION AT THE BOTTOM
> Message-ID: <4f2cc7bf.1090...@alchemy.com>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> On 03-Feb-12 21:38, Debashish Saha wrote:
> > BUT I COULD NOT UNDERSTAND HOW THE COMMAND ELSE CAN WORK,THOUGH IT IS IN
> > THE OUTSIDE OF THE FOR LOOP IN WHICH IF COMMAND LIES.
>
> The part that's confusing you is that it is not outside the for loop.
> It is PART of the for loop syntax.  The loop construct used is:
>
> for  in :
>
> else:
>
>
> This means you run , executing
>  once for each iteration, and a statement in that body may
> elect to break out of the loop prematurely.  If nothing breaks out of
> the loop (i.e., you exit the loop because the  was exhausted),
> then and only then execute .
>
> It's a handy mechanism to handle the case where the for loop failed to
> find whatever it was searching for.  Most other languages I've used
> don't have this, and you end up doing messier manual logic steps to
> accomplish the same thing.
>
> Tip:  Please don't type a message IN ALL CAPITAL LETTERS; it gives the
> impression you are shouting at your audience.
>
> HTH,
> HAND
>
> --
> Steve Willoughby / st...@alchemy.com
> "A ship in harbor is safe, but that is not what ships are built for."
> PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C
>
>
> --
>
> Message: 2
> Date: Sat, 4 Feb 2012 15:41:46 +0530
> From: Debashish Saha 
> To: tutor@python.org
> Subject: [Tutor] factorial of anumber
> Message-ID:
> >
> Content-Type: text/plain; charset="iso-8859-1"
>
> *PROGRAM TO FIND FACTORIAL OF A NUMBER(I HAVE WRITTEN IT ON GEDIT)*
> x=1
> n=input('enter a positive integer no:')
> for i in range(1,1+n):
>x=x*i
> print x
>
>
> *ERROR:*
>
> enter a positive integer
>
> no:---
> EOFError  Traceback (most recent call last)
> C:\Python27\lib\site-packages\IPython\utils\py3compat.pyc in
> execfile(fname, glob, loc)
>166 else:
>167 filename = fname
> --> 168 exec compile(scripttext, filename, 'exec') in glob, loc
>169 else:
>170 def execfile(fname, *where):
>
> C:\Users\as\mnb.py in ()
>  1 x=1
> > 2 n=input('enter a positive integer no:')
>  3 for i in range(1,1+n):
>  4 x=x*i
>  5 print x
>
> EOFError: EOF when reading a line
>
> *QUESTION*:
> HOW TO ASK INPUT FROM USER THEN?
> -- next part --
> An HTML attachment was scrubbed...
> URL: <
> http://mail.python.org/pipermail/tutor/attachments/20120204/6b70ebd8/attachment-0001.html
> >
>
> --
>
> Message: 3
> Date: Sat, 04 Feb 2012 10:18:07 +
> From: Blockheads Oi Oi 
> To: tutor@python.org
> Subject: Re: [Tutor] Importing libraries
> Message-ID: 
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> On 04/02/2012 05:37, Michael Lewis wrote:
> > Why don't I have to import str or list to access their attributes like I

Re: [Tutor] (no subject)

2012-02-04 Thread Alan Gauld

On 04/02/12 12:08, Debashish Saha wrote:


f(11)
Out[109]: 2.5132741228718345

f(11.0)
Out[110]: 2.7646015351590183

*question:*
why did i get different values for the same input?


Because they are not the same inputs.
11 is an integer and 11.0 is a float and Python (along with many 
programming languages) treats division slightly differently for

ints and floats. You can bypass this by making your divisor a
float:

##
def f(y):
 return (y/5.0)*2*(np.pi)*0.2
##


Now it will return the same result regardless of int or float.

In Python v3 this is the default behavior

--
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] Urgent Help Required

2012-02-04 Thread Dave Angel

On 02/04/2012 08:17 AM, Zafrullah Syed wrote:

Hi,

I need urgent help:

I am unable to commit code to svn, I am getting this warning:

*svn: Commit failed (details follow):*
*svn: Commit blocked by pre-commit hook (exit code 1) with output:*
*:17: Warning: 'with' will become a reserved keyword in Python 2.6*
*writeConf.py:17: invalid syntax*
*Commited Python-Files refused, please check and retry...*

How do i surpass this and commit my code??

Lousy choice of subject.  Please make your subject reflect what your 
problem is, not how important it may or may not be to you.


You're not just running svn.  If you were, you'd not get some python 
error or warning.  So you're running a more complex environment, perhaps 
svn integrated inside some IDE (like komodo, wingware, beans, whatever).


If so, post a question on the forum that supports that particular IDE.  
Or if you must post here, at least give us a clue what environment 
you're using.  For example, i can infer that you're running Python 2.5 
or older.  But it'd be much better to explicitly say what python 
version, which operating system (and version), and what IDE (and 
version), and what svn (get the pattern?).


The svn command to submit changes to a file outside of the ide is  svn 
commit filename.  If the file is new, I believe you have to do an svn add.




--

DaveA

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


Re: [Tutor] Tutor Digest, Vol 96, Issue 8

2012-02-04 Thread col speed
On 4 February 2012 20:29, Zafrullah Syed  wrote:
> Hi,
>
> I need urgent help:
Yes, I think you do.
Take notice of the last replies.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 96, Issue 8

2012-02-04 Thread Dave Angel

On 02/04/2012 08:29 AM, Zafrullah Syed wrote:

Hi,

I need urgent help:

I am unable to commit code to svn, I am getting this warning:

*svn: Commit failed (details follow):*
*svn: Commit blocked by pre-commit hook (exit code 1) with output:*
*:17: Warning: 'with' will become a reserved keyword in Python 2.6*
*writeConf.py:17: invalid syntax*
*Commited Python-Files refused, please check and retry...*

How do i surpass this and commit my code??

1) Once again your subject does not reflect anything useful.  In fact 
one of the first things in the digest is:


When replying, please edit your Subject line so it is more specific

 than "Re: Contents of Tutor digest..."



2) Don't include anything in your message that's irrelevant to the subject at 
hand.  If you must reply to a digest, at least trim out all the messages except 
the one you're replying to. In your case you weren't replying to anything in 
that digest, so it's a lousy starting point.  Just email a new query to the 
list at tutor@python.org

3) Don't ask the same question twice in 12 minutes.  It makes people think 
you're impatient.  Why sometimes, no messages come in a 24 hour period. If you 
need immediate help, go someplace where they take your money in return for 
timely support.  People who reply here are volunteers, in various time zones 
throughout the world, who are trying to be helpful.

As for your question, I posted my reply to it 18 minutes after yours.  Some of 
that may be because my mail program only polls every 10 minutes or so.  Some 
may be because I thought a little about the reply before hitting send.

--

DaveA

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


[Tutor] Failing svn pre-commit hok was Re: Urgent Help Required

2012-02-04 Thread Peter Otten
Zafrullah Syed wrote:

> I need urgent help:

Remember that this isn't paid support. Don't frivolously consume the 
goodwill of volunteers.

> I am unable to commit code to svn, I am getting this warning:
> 
> *svn: Commit failed (details follow):*
> *svn: Commit blocked by pre-commit hook (exit code 1) with output:*
> *:17: Warning: 'with' will become a reserved keyword in Python
> 2.6* *writeConf.py:17: invalid syntax*
> *Commited Python-Files refused, please check and retry...*
> 
> How do i surpass this and commit my code??

You have a pre-commit hook in place that ensures that you commit valid 
Python 2.5 code. To make your file 2.5-compliant you can either replace

with output:
  ...

with something else or add

from __future__ import with_statement

at the top of your file. 

Alternatively you can ask the person responsible for the svn installation to 
remove the hook or replace it with a check that accepts Python 2.6 or 
whatever version you are developing for.


 


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


Re: [Tutor] Tutor Digest, Vol 96, Issue 8

2012-02-04 Thread Alan Gauld

On 04/02/12 13:29, Zafrullah Syed wrote:


I need urgent help:


Then you are going a very bad way of getting it.
If you must post for help

a) pick a forum that ir related to your problem.
This is a python beginners mailing list not an
svn problem list.

b) Follow the rules of the forum you are using
eg (1)don't post the same question multiple times, it doesn't elicit 
answers quicker it just annoys people so they don't answer at all.
(2)Pick a sensible subject matter, neither of your posts tell us what 
you want to know (3) provide enough information so that folks can help - 
version numbers, OS, etc etc. (4) Don't post an entire digest to a 
mailing list where some people pay by the byte. (Actually, don't post 
the entire digest even if they don't pay by byte! It just wastes space)


In short think. Think about what people need to know to help you and 
where are the people that can help most likely to be located. Make it 
easy for us to help you and we might respond, make it hard to help and 
we probably won't.



I am unable to commit code to svn, I am getting this warning:

*svn: Commit failed (details follow):*
*svn: Commit blocked by pre-commit hook (exit code 1) with output:*
*:17: Warning: 'with' will become a reserved keyword in Python 2.6*
*writeConf.py:17: invalid syntax*
*Commited Python-Files refused, please check and retry...*


Have you looked at the file in question? Have you looked at the lines 
around the error report? Are you using 'with' in an appropriate way?



How do i surpass this and commit my code??


You fix the error, one way or another. But without sight of your code or 
the svn hook or your local coding standards/environment there's not much 
we can do except guess.



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

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


[Tutor] Return T/F vs print T/F

2012-02-04 Thread Sivaram Neelakantan

While trying out code, I have trouble following the difference between 

return True vs print True and the same with False.  If I use return
for the True/False statements, nothing gets printed.  Why? And if I
add a print before the function call I get an output like 

>>>True
None

--8<---cut here---start->8---
def first(word):
return word[0]
def last(word):
return word[-1]
def middle(word):
return word[1:-1]

def palin(text):
if first(text) == last(text):
# print first(text), last(text), middle(text), len(middle(text))
if len(middle(text)) == 0:
print True
else:
palin(middle(text))
else:
print False


palin("o") 
palin("nxon")
palin("nooxooxoon")
print palin("nabban") 
--8<---cut here---end--->8---



 sivaram
 -- 

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


Re: [Tutor] Return T/F vs print T/F

2012-02-04 Thread bob gailer

On 2/4/2012 9:38 AM, Sivaram Neelakantan wrote:

While trying out code, I have trouble following the difference between

return True vs print True and the same with False.  If I use return
for the True/False statements, nothing gets printed.  Why?


Why did you expect something to be printed?

Perhaps you are confused between what happens in the interactive window 
vs running a program?


Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit 
(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
...   return True
...
>>> f()
True
>>> def g():
... print True
...
>>> g()
True
>>> print f()
True
>>> print g()
True
None

In the interactive window, when you call a function,  Python displays 
the returned value.
When you run a program with a call to a function, Python does NOT 
display the returned value.


A function that does not execute a return will return None; in the 
interactive window nothing is displayed.


Is that sufficient?

--
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] Return T/F vs print T/F

2012-02-04 Thread Sivaram Neelakantan
On Sat, Feb 04 2012,bob gailer wrote:

> On 2/4/2012 9:38 AM, Sivaram Neelakantan wrote:
>> While trying out code, I have trouble following the difference between
>>
>> return True vs print True and the same with False.  If I use return
>> for the True/False statements, nothing gets printed.  Why?
>
> Why did you expect something to be printed?

err...return sends something back as in True or False?


>
> Perhaps you are confused between what happens in the interactive
> window vs running a program?

Possibly.  But I was coding in an Emacs buffer and sending it to the
python subprocess from within Emacs.  Does that have anything to do
with it?

>
> Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
 def f():
> ...   return True
> ...
 f()
> True
 def g():
> ... print True
> ...
 g()
> True
 print f()
> True
 print g()
> True
> None
>
> In the interactive window, when you call a function, Python displays
> the returned value.  When you run a program with a call to a
> function, Python does NOT display the returned value.
>
> A function that does not execute a return will return None; in the
> interactive window nothing is displayed.
>
> Is that sufficient?

Right, thanks for this, will check this thing out again.

 sivaram
 -- 

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


Re: [Tutor] Return T/F vs print T/F

2012-02-04 Thread Steven D'Aprano

Sivaram Neelakantan wrote:
While trying out code, I have trouble following the difference between 
return True vs print True and the same with False.  If I use return
for the True/False statements, nothing gets printed.  Why? 


Probably because you aren't printing anything. Python can't read your mind and 
know what you want printed and what you don't want printed, you have to tell 
it what to print.


It is not clear how you are "trying out code". Are you running code as a 
script? Using IDLE or iPython? Using the standard interactive interpreter? The 
environment will make a difference in the behaviour.


In the interactive interpreter, as a convenience, the result of each line is 
automatically printed for you:



>>> 1+3
4
>>> len("hello world")
11


but this is only in the interactive environment. In a script, nothing is 
printed unless you call print.


Functions should have a return result -- the value they calculate. You can 
then store the value in a variable for later use:


>>> length = len("hello world")  # store the value
>>> print "The length is", length  # and use it later
The length is 11


The print command does not return a value, it just prints the argument. If you 
use print in the function, you cannot capture the result and use it in 
additional calculations.


When writing your own functions, you should always aim for this same 
behaviour: use return inside the function, print outside.




And if I add a print before the function call I get an output like 


True

None


I can't see any possible way your code will give output including ">>>". Would 
you care to explain more carefully what you mean?





--
Steven


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


Re: [Tutor] Return T/F vs print T/F

2012-02-04 Thread Steven D'Aprano

Sivaram Neelakantan wrote:


def palin(text):
if first(text) == last(text):
# print first(text), last(text), middle(text), len(middle(text))
if len(middle(text)) == 0:
print True
else:
palin(middle(text))
else:
print False



Every branch of the function must include a return, or Python will just return 
None by default. You have three branches. Two of them print a flag. It is easy 
enough to fix them by changing print to return. The third branch has no 
return. It needs one.




--
Steven

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


Re: [Tutor] Return T/F vs print T/F

2012-02-04 Thread Brett Ritter
On Sat, Feb 4, 2012 at 11:42 AM, Sivaram Neelakantan
 wrote:
> On Sat, Feb 04 2012,bob gailer wrote:
>
>> On 2/4/2012 9:38 AM, Sivaram Neelakantan wrote:
>>> While trying out code, I have trouble following the difference between
>>>
>>> return True vs print True and the same with False.  If I use return
>>> for the True/False statements, nothing gets printed.  Why?
>>
>> Why did you expect something to be printed?
>
> err...return sends something back as in True or False?

Yes, it returns it to the caller.  It doesn't print it.

When using the interactive mode, the program that creates that mode
prints the return.  When you are using it your program, the caller
decides what to do.

The flip side is that printing a value does NOT return it.

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


Re: [Tutor] Return T/F vs print T/F

2012-02-04 Thread bob gailer

On 2/4/2012 11:53 AM, Steven D'Aprano wrote:
[snip]


In the interactive interpreter, as a convenience, the result of each 
line is automatically printed for you:


Actually the interpreter prints the result of each /statement /that IS 
an /expression/.

>>> 2
2
>>> a = 3
>>> a
3
IOW if the line is blank, start with # or is a statement the interpreter 
does not print anything (unless it is a print statement). For a messy 
example:


>>> if 1:3;a=4;a
...
3
4

--
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] Importing libraries

2012-02-04 Thread Devin Jeanpierre
On Sat, Feb 4, 2012 at 6:35 AM, Steven D'Aprano  wrote:
> Michael Lewis wrote:
>>
>> Why don't I have to import str or list to access their attributes like I
>> do
>> with the math or random or any other library?
>
>
>
> Because they are built-in. That means they live inside the Python
> compiler/interpreter itself.

Blargh, lots of things are built in. The sys module is a built-in
module, but you don't get access to it by default.

It's because they're specially-chosen to be in the "builtin
namespace". This is the namespace of things that are always
accessible. This is different from being built into the interpreter --
hypothetically we could have something in the builtin namespace that
is not part of Python itself. (You can do this by adding things to the
builtin namespace by hand).

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


[Tutor] Pizza panic game

2012-02-04 Thread myles broomes

Im currently using a book called 'Programming in Python for the complete 
beginner' and at the end of each chapter, the reader is given challenges to do. 
The current chapter im on, one of the challenges is to take the source code for 
a 'Pizza Panic' game , and find a way to make the game more difficult. 
Basically, the premise of the game is the player controls a pan and has to try 
and catch falling pizzas that a computer controlled chef is dropping, and 
failure to drop any results in game over. The idea I came up with is as well as 
the chef dropping the pizzas, he also drops hazardous spikey balls that the 
player has to try and avoid. I'll try to explain the part that im having 
trouble with:
 
Heres the code for the 'Spikey ball' class that creates the spikey ball object:
 
class Spikey_ball(games.Sprite):
"""A hazardous spikey ball that falls to the ground."""
image = games.load_image("Spikey_ball.png")
speed = 0.5
 
def __init__(self, x, y = 90):
"""Initialise the spikey ball object."""
super(Spikey_ball, self).__init__(image = Spikey_ball.image,
  x = x, y = y,
  dy = Spikey_ball.speed)
def update(self):
"""Check if botton edge has reached the screen."""
if self.bottom > games.screen.height:
self.destroy()
 
def handle_caught(self):
"""Destroy if caught and end game."""
if self.bottom > Pan.top:
Pizza.end_game()
self.destroy()
 
 
...And heres the code for the pan class:
 
class Pan(games.Sprite):
"""
A pan controlled by player to catch falling pizzas.
"""
image = games.load_image("pan.bmp")
 
def __init__(self):
""" Initialize Pan object and create Text object for score. """
super(Pan, self).__init__(image = Pan.image,
  x = games.mouse.x,
  bottom = games.screen.height)

self.score = games.Text(value = 0, size = 25, color = color.black,
top = 5, right = games.screen.width - 10)
games.screen.add(self.score)
 
def update(self):
""" Move to mouse x position. """
self.x = games.mouse.x

if self.left < 0:
self.left = 0

if self.right > games.screen.width:
self.right = games.screen.width

self.check_catch()
 
def check_catch(self):
""" Check if catch pizzas. """
for pizza in self.overlapping_sprites:
pizza.handle_caught()
 
As you can see, when a sprite overlaps the pan object, the handle_caught 
attribute of said object is invoked. But the weird thing is, when a pizza is 
caught, it works fine and the pizza's handle_caught attribute is invoked 
without complaint. However, when a spikey ball is caught, the game comes up 
with an error and claims that the Spikey_ball object has no handle_caught 
attribute, but as you can see, it clearly does. Can anyone explain this to me?  
 ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pizza panic game

2012-02-04 Thread Alan Gauld

On 04/02/12 23:43, myles broomes wrote:


game comes up with an error and claims that the Spikey_ball object has
no handle_caught attribute, but as you can see, it clearly does. Can
anyone explain this to me?


Please post the entire error message, do not summarize.
There is often important information in the message.

Meantime can you try adding a print line in your last
method to check that the attribute(i.e. method) does
actually exist in the executing code at the point
of use?
ie.

def check_catch(self):
""" Check if catch pizzas. """
for pizza in self.overlapping_sprites:
print (dir(pizza))   #<<< new line
pizza.handle_caught()

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] Pizza panic game

2012-02-04 Thread Dave Angel

On 02/04/2012 06:43 PM, myles broomes wrote:

Im currently using a book called 'Programming in Python for the complete 
beginner' and at the end of each chapter, the reader is given challenges to do. 
The current chapter im on, one of the challenges is to take the source code for 
a 'Pizza Panic' game , and find a way to make the game more difficult. 
Basically, the premise of the game is the player controls a pan and has to try 
and catch falling pizzas that a computer controlled chef is dropping, and 
failure to drop any results in game over. The idea I came up with is as well as 
the chef dropping the pizzas, he also drops hazardous spikey balls that the 
player has to try and avoid. I'll try to explain the part that im having 
trouble with:

Heres the code for the 'Spikey ball' class that creates the spikey ball object:

class Spikey_ball(games.Sprite):
 """A hazardous spikey ball that falls to the ground."""
 image = games.load_image("Spikey_ball.png")
 speed = 0.5

 def __init__(self, x, y = 90):
 """Initialise the spikey ball object."""
 super(Spikey_ball, self).__init__(image = Spikey_ball.image,
   x = x, y = y,
   dy = Spikey_ball.speed)
 def update(self):
 """Check if botton edge has reached the screen."""
 if self.bottom>  games.screen.height:
 self.destroy()

 def handle_caught(self):
 """Destroy if caught and end game."""
 if self.bottom>  Pan.top:
 Pizza.end_game()
 self.destroy()


...And heres the code for the pan class:

class Pan(games.Sprite):
 """
 A pan controlled by player to catch falling pizzas.
 """
 image = games.load_image("pan.bmp")

 def __init__(self):
 """ Initialize Pan object and create Text object for score. """
 super(Pan, self).__init__(image = Pan.image,
   x = games.mouse.x,
   bottom = games.screen.height)

 self.score = games.Text(value = 0, size = 25, color = color.black,
 top = 5, right = games.screen.width - 10)
 games.screen.add(self.score)

 def update(self):
 """ Move to mouse x position. """
 self.x = games.mouse.x

 if self.left<  0:
 self.left = 0

 if self.right>  games.screen.width:
 self.right = games.screen.width

 self.check_catch()

 def check_catch(self):
 """ Check if catch pizzas. """
 for pizza in self.overlapping_sprites:
 pizza.handle_caught()

As you can see, when a sprite overlaps the pan object, the handle_caught 
attribute of said object is invoked. But the weird thing is, when a pizza is 
caught, it works fine and the pizza's handle_caught attribute is invoked 
without complaint. However, when a spikey ball is caught, the game comes up 
with an error and claims that the Spikey_ball object has no handle_caught 
attribute, but as you can see, it clearly does. Can anyone explain this to me?  
   

There is a function handle_caught(), but it's not a method of the class, 
it's a nested function of method __init__()


Unless of course, you haven't posted correctly, and the indentation 
doesn't match what you're really using.



--

DaveA

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