Re: [Tutor] Beginner Question

2013-10-23 Thread Albert-Jan Roskam

On Wed, 10/23/13, Steven D'Aprano st...@pearwood.info wrote:

 Subject: Re: [Tutor] Beginner Question
 To: tutor@python.org
 Date: Wednesday, October 23, 2013, 5:27 AM
 
 On Tue, Oct 22, 2013 at 04:25:59PM
 +0200, Sven Hennig wrote:
   Hello, I would like to learn a programming
 language and have decided to use
  Python. I have some programming experience and doing
 well in Python. What
  really causes me problems is OOP.
  I'm just dont get it... I'm missing a really Practical
 example. In every
  book I've read are the examples of such Class Dog and
 the function is bark. Has
  anyone an OOP example for me as it is really used in
 real code, so I can
  better understand the concept? I do not know why this
 is so hard for me.
 
 I can sympathise. You wouldn't believe how long it took me
 to really 
 grok object-oriented programming. I just didn't get it,
 until I started 
 thinking of OOP as being just syntax for keeping functions
 (called 
 methods) close to the data they belong with. There is more
 to OOP than 
 that, but that was my first step: OOP helps you keep your
 functions 
 close to the data they work with.
 
snip
 
 That's all you need to know to start using object oriented
 programming 
 in Python! Many operations are implemented as methods, for
 instance 
 strings have upper and lower methods, lists have append and
 remove 
 methods, and many more. You'll soon learn the operations
 like len() that 
 aren't methods, but old-school functions.
 
== This reminded me of a text by Guido van Rossum (I can't find the original 
page): 
http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm

So the built-in 'len()' is *really* a function, but calls to  len()  
implemented by __len__ are method calls *disguised* as function calls? I 
sometimes find it easier to write calls to special methods the normal way, 
e.g. instead of x + y just write it like x.__add__(y) This makes special 
methods more like other methods and therefore easier to understand, to me at 
least.

Albert-Jan

PS: sorry about the lack of quoting. Yahoo mail was upgraded and now all 
sorts of stuff stops working, times out, etc. 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Beginner Question

2013-10-23 Thread Oscar Benjamin
On 23 October 2013 08:58, Albert-Jan Roskam fo...@yahoo.com wrote:
 So the built-in 'len()' is *really* a function, but calls to  len()  
 implemented by __len__ are method calls *disguised* as function calls? I 
 sometimes find it easier to write calls to special methods the normal way, 
 e.g. instead of x + y just write it like x.__add__(y) This makes special 
 methods more like other methods and therefore easier to understand, to me at 
 least.

Please don't do that. Firstly it looks horrible. Secondly they're not
equivalent. The equivalent of x + y is operator.add(x, y) but don't
use that either. It's not easier to understand and it's less
efficient.

When you wrate a+b the interpreter actually calls a bunch of different
methods: a.__add__(b), b.__radd__(a), a.__coerce__(b) etc. I don't
know the full sequence and it's not consistent across Python
implementations. Eryksun recently posted a good example showing how a
== b is handled:
https://mail.python.org/pipermail/tutor/2013-July/097110.html


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


Re: [Tutor] Beginner question on classes

2013-10-23 Thread Alan Gauld

On 23/10/13 08:25, Corinne Landers wrote:

Hi guys,

I need a bit of help.
I'm writing a class, and in the main function I'm trying to say if this
method gets called, do this.


What you are actually doing is if the method returns
a truth-like value do this. Not quite the same thing,
but much easier!


I'm trying things like:

program = AnimalClass(x,y,z)
for i in range(x):
for j in range(y):
   for k in range(z):
   animal = program.animal()
   if animal:
   if isinstance(animal,moose):
   print(There is a moose here)


The block below for k... needs more indentation and
The final print needs yet another level of indentation...


It's clearly not correct because it's giving me all sorts of grief,


Could you be more specific? What kind of grief?
Error messages? Then send the full message here.
Your computer crashes?
It doesn't print a message you expected?

While you are at it which Python version and OS are you using?


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

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


Re: [Tutor] Beginner question on classes

2013-10-23 Thread Oscar Benjamin
On 23 October 2013 08:25, Corinne Landers corinne.land...@live.com wrote:
 Hi guys,

Hi Corrine,

 I need a bit of help.
 I'm writing a class, and in the main function I'm trying to say if this
 method gets called, do this.
 I'm trying things like:

 program = AnimalClass(x,y,z)
 for i in range(x):
for j in range(y):
   for k in range(z):
   animal = program.animal()
   if animal:
   if isinstance(animal,moose):
   print(There is a moose here)

 It's clearly not correct because it's giving me all sorts of grief, but if
 anyone knows how to do this correctly I'd very much appreciate it!

I'm sure someone will help you but you haven't really given enough
information yet.

Is the code you posted the whole of your program? If so please say so
explicitly because it looks like only part of a program to me and you
should show the whole code for anyone to understand what you're doing.

Also you say that it is giving you grief but we need more than that.
Is it showing an error message? If so please copy/paste the whole
error message and traceback. Here's an example showing what happens
when I run your program as shown above (saved into a file called
tmp.py):

$ python tmp.py
  File tmp.py, line 5
animal = program.animal()
 ^
IndentationError: expected an indented block

What that error means is that you need to indent everything inside the
3rd for loop on line 5.


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


Re: [Tutor] Beginner question on classes

2013-10-23 Thread Dave Angel
On 23/10/2013 03:25, Corinne Landers wrote:


 --/style/head
 body class='hmmessage'div dir='ltr'Hi guys,nbsp;divbr/divdivI 
 need a bit of help.nbsp;/divdivI'm writing a class, and in the main 
 function I'm trying to say if this method gets called, do 
 this.nbsp;/divdivI'm trying things 
 like:/divdivbr/divdivprogram = AnimalClass(x,y,z)/divdivfor i 
 in range(x):/divdivnbsp; nbsp;for j in range(y):/divdivnbsp; 
 nbsp; nbsp; for k in range(z):/divdivnbsp; nbsp; nbsp; animal = 
 program.animal()/divdivnbsp; nbsp; nbsp; if 
 animal:nbsp;/divdivnbsp; nbsp; nbsp; nbsp; nbsp; if 
 isinstance(animal,moose):/divdivnbsp; nbsp; nbsp; nbsp; nbsp; 
 print(There is a moose here)/divdivbr/divdivIt's clearly not 
 correct because it's giving me all sorts of grief, but if anyone knows how to 
 do this correctly I'd very much appreciate 
 it!/divdivbr/divdivCorrine/divdivbr/div 
  /div/body
 /html


Hi, and welcome to Python, and to the Python tutor list.

Please start by telling us what Python version you're using, and what
OS.

Please post here using a text message, not html, as many email programs
(apparently including yours) cannot correctly convert the html to
text. Your entire program fragment appears on one line in my
newsreader.  And people like me can see the html, but not display it. 
This is a text newsgroup.

Studying other people's responses that do have html abilities, I can see
that you did post an indented code fragment, so I'll copy that here
and comment on it.

 program = AnimalClass(x,y,z)
 for i in range(x):
 for j in range(y):
for k in range(z):
animal = program.animal()
if animal:
if isinstance(animal,moose):
print(There is a moose here)

Your problem statement was:  if this method gets called, do this

No idea which of these is this method, nor what you intend by do
this.  And you needn't test whether it's being called, since presumably
you're calling it.  Usually, you test the return value of a method, but
that's not what you're saying.

Just looking at the code in isolation, I can see that you'll get an
indentation error on the line assigning to animal.  You have to indent
the body of any for statement.

Next, it appears you don't use i, j and k.  So are you intending to just
do the same thing x*y*z times?  If so, then you just should use one
loop, and multiple them together.

Does program.animal() return the same value each time, or is it somehow
supposed to guess the values of i, j, and k ?

Is moose a class name, defined elsewhere that you didn't include?  Then
it ought to be capitalized, to make that obvious.  It's just a
convention, but following conventions will make your code easier to
read.  I know that many classes in the standard lib are not capitalized,
but that's mostly because the names were established many many years
ago, some perhaps before there was the ability to write user classes. 
Pep-8 is the place where such conventions are described.

-- 
DaveA


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


[Tutor] Beginner Question

2013-10-22 Thread Sven Hennig
 Hello, I would like to learn a programming language and have decided to use
Python. I have some programming experience and doing well in Python. What
really causes me problems is OOP.
I'm just dont get it... I'm missing a really Practical example. In every
book I've read are the examples of such Class Dog and the function is bark. Has
anyone an OOP example for me as it is really used in real code, so I can
better understand the concept? I do not know why this is so hard for me.

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


Re: [Tutor] Beginner Question

2013-10-22 Thread Alan Gauld

On 22/10/13 15:25, Sven Hennig wrote:

Hello, I would like to learn a programming language and have decided to
use Python. I have some programming experience and doing well in Python.
What really causes me problems is OOP.


Don't worry this is common.
The problem with OOP is that it only really becomes useful when you get 
to bigger programs than a beginner has typically met. So its value is 
not obvious.


For some (slightly) more real world examples try the OOP page in my 
tutorial with examples using shapes and bank accounts. (see .sig)


The other big area where it is used is in GUI programming. On-screen 
widgets like buttons, menus, sliders etc are naturally modelled as 
objects. You can then attach methods like onPress to a button
or onMove() or position() to a slider. Then as you build your GUI screen 
you will have klots of instanmces of the objects, multiple buttons, 
labels, text fields etc.




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

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


Re: [Tutor] Beginner Question

2013-10-22 Thread Andy McKenzie
On Tue, Oct 22, 2013 at 10:25 AM, Sven Hennig shenni...@googlemail.comwrote:

 Hello, I would like to learn a programming language and have decided to
 use Python. I have some programming experience and doing well in Python.
 What really causes me problems is OOP.
 I'm just dont get it... I'm missing a really Practical example. In every
 book I've read are the examples of such Class Dog and the function is bark
 . Has anyone an OOP example for me as it is really used in real code, so
 I can better understand the concept? I do not know why this is so hard for
 me.

 Greetings
 Sven


The actual code I have is in PHP, so it's not exactly useful to post here,
but I can give you an outline of a class I used and found useful.  The
class was created to help me manipulate network subnets in an interface to
handle DHCP and DNS on a server.

class subnet:

   def __init__(cidr):
  # Do some stuff with the CIDR notation of the subnet (1.2.3.0/24syntax)

  def netmask:
 # Calculate the netmask and return it (ie, 255.255.255.0)

   def first_ip:
  # Calculate and return the first IP in the range.

   def last_ip:
  # Calculate and return the last IP in the range

   def number_of_addresses:
  # Calculate the number of usable addresses in the range and return
that value

The benefit to me was that I could create an instance of the subnet object
for a group (say, lab_1), and then pull out various information.  Calling
lab_1.first_ip() returns the first possible IP address.  That was a lot
more readable and a lot more concise than something like first_ip(
1.2.3.0/24).


I hope this helps!

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


Re: [Tutor] Beginner Question

2013-10-22 Thread Dave Angel
On 22/10/2013 10:25, Sven Hennig wrote:

  Hello, I would like to learn a programming language and have decided to use
 Python. I have some programming experience and doing well in Python. What
 really causes me problems is OOP.
 I'm just dont get it... I'm missing a really Practical example. In every
 book I've read are the examples of such Class Dog and the function is bark. 
 Has
 anyone an OOP example for me as it is really used in real code, so I can
 better understand the concept? I do not know why this is so hard for me.


What you may not realize is you're already doing OOP, just by using the
standard library.  When you open a file (or many other things that can
produce a stream of bytes), you get an instance of class file.  When you
use that instance, you're calling methods of that instance.  So when you
say:

infile = open(myfile.txt,r)
data = infile.readline()

you're doing object oriented programming.  You don't have to know what
kind of thing infile is, you just have to know it has methods read(),
readline(), close(), etc.

When you want to write your own classes, or when you want to make a new
class that's related but different from one of the thousands that are
standard, that's when it gets interesting.  As Alan says, GUI is one
place where you'll be wrting your own classes, usually by deriving from
one of the GUI library classes.

At its most fundamental, a class is a description of how to create and
how to manipulate instances.  An instance has methods (functions), and
attributes (data).  When one class is derived from another, it can share
some or most of the attributes and behavior of the parent class, but
make changes.  This helps avoid duplicating code when two things are
similar.

You're familiar with list and tuple.  Those are built-in
collection classes, supported explicitly by the language. But if you
want your own collection, you may want to make a class for it.  The Dog
bark() example may seem silly, but a Dog has lots of other methods
besides that one, and has lots of attributes (color, breed, health
state, owner, etc.).  In a sense those attributes are like a list within
the Dog, but you want them to have nice names, instead of remembering
that the 3rd one is owner.


-- 
DaveA


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


Re: [Tutor] Beginner Question

2013-10-22 Thread Sven Hennig
Thank you! You guys helped me out alot.

@Alan your website is great! Really clearly written. Especially the Things
to remember part.

If you have exercises for me or have a Website with exercises, bring it on. I
think this is the best way to learn.



2013/10/22 Dave Angel da...@davea.name

 On 22/10/2013 10:25, Sven Hennig wrote:

   Hello, I would like to learn a programming language and have decided to
 use
  Python. I have some programming experience and doing well in Python. What
  really causes me problems is OOP.
  I'm just dont get it... I'm missing a really Practical example. In every
  book I've read are the examples of such Class Dog and the function is
 bark. Has
  anyone an OOP example for me as it is really used in real code, so I can
  better understand the concept? I do not know why this is so hard for me.
 

 What you may not realize is you're already doing OOP, just by using the
 standard library.  When you open a file (or many other things that can
 produce a stream of bytes), you get an instance of class file.  When you
 use that instance, you're calling methods of that instance.  So when you
 say:

 infile = open(myfile.txt,r)
 data = infile.readline()

 you're doing object oriented programming.  You don't have to know what
 kind of thing infile is, you just have to know it has methods read(),
 readline(), close(), etc.

 When you want to write your own classes, or when you want to make a new
 class that's related but different from one of the thousands that are
 standard, that's when it gets interesting.  As Alan says, GUI is one
 place where you'll be wrting your own classes, usually by deriving from
 one of the GUI library classes.

 At its most fundamental, a class is a description of how to create and
 how to manipulate instances.  An instance has methods (functions), and
 attributes (data).  When one class is derived from another, it can share
 some or most of the attributes and behavior of the parent class, but
 make changes.  This helps avoid duplicating code when two things are
 similar.

 You're familiar with list and tuple.  Those are built-in
 collection classes, supported explicitly by the language. But if you
 want your own collection, you may want to make a class for it.  The Dog
 bark() example may seem silly, but a Dog has lots of other methods
 besides that one, and has lots of attributes (color, breed, health
 state, owner, etc.).  In a sense those attributes are like a list within
 the Dog, but you want them to have nice names, instead of remembering
 that the 3rd one is owner.


 --
 DaveA


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

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


Re: [Tutor] Beginner Question

2013-10-22 Thread Alan Gauld

On 22/10/13 19:18, Sven Hennig wrote:

Thank you! You guys helped me out alot.

@Alan your website is great! Really clearly written. Especially the
Things to remember part.


Glad you like it. Someday (soon!) I'll get round to finishing
the v3 version... So much to do, so little time!


If you have exercises for me


There are exercises but they are buried in the text.
ie suggestions for the reader to try to extend the examples
or to write other parallel examples for themselves.

There is also a page with suggested projects near the end.


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

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


Re: [Tutor] Beginner Question

2013-10-22 Thread Steven D'Aprano
On Tue, Oct 22, 2013 at 04:25:59PM +0200, Sven Hennig wrote:
  Hello, I would like to learn a programming language and have decided to use
 Python. I have some programming experience and doing well in Python. What
 really causes me problems is OOP.
 I'm just dont get it... I'm missing a really Practical example. In every
 book I've read are the examples of such Class Dog and the function is bark. 
 Has
 anyone an OOP example for me as it is really used in real code, so I can
 better understand the concept? I do not know why this is so hard for me.

I can sympathise. You wouldn't believe how long it took me to really 
grok object-oriented programming. I just didn't get it, until I started 
thinking of OOP as being just syntax for keeping functions (called 
methods) close to the data they belong with. There is more to OOP than 
that, but that was my first step: OOP helps you keep your functions 
close to the data they work with.

In conventional procedural languages, if you had a function that 
operates on a string, you would write something like this:

Struct string = ... # define a string here

# later in the file, perhaps many pages later:

function upper(some_string):
result = make a new string
for char in some_string:
if char = 'a': add 'A' to result
if char = 'b': add 'B' to result
...
if char = 'z': add 'Z' to result
else add char to result
return result

(Aside: don't program uppercase like that! There are more efficient 
ways, and in Python, it is already provided!)

So the problem with this is that your data (say, strings) and the 
functions that operate on your data (say, upper, lower, and many others) 
can end up being defined far away from each other, which makes editing 
the code painful.

With OOP, the first change is that the syntax is changed to bring the 
functions (called methods) together with their data:

class string:
# put code here to define the string data class
# now define all the functions that work on strings
def upper(self):
# code for upper goes here

def lower(self):
# code for lower goes here

# any other string methods go here


Then, later, instead of writing:

mystring = blah blah blah
print upper(mystring)  # this doesn't work since upper is a method

we have a slightly different syntax:

print mystring.upper()  # use this instead


That's all you need to know to start using object oriented programming 
in Python! Many operations are implemented as methods, for instance 
strings have upper and lower methods, lists have append and remove 
methods, and many more. You'll soon learn the operations like len() that 
aren't methods, but old-school functions.

As I said, there is a lot more to OOP than just making it easier to 
organise your program files, but that was the realisation that helped me 
get OOP.


The next step is to understand inheritance. Inheritance means that you 
can create a new class (the subclass) which inherits -- borrows -- data 
and methods from another class (the super class). Here is a stupid 
example:

class StupidStr(str):  # inherit from str
def upper(self):
return ***


This class StupidStr is exactly like the ordinary string, except the 
upper() method has been replaced to do something trivial and stupid:

py s = StupidStr(Hello World)
py s.lower()  # inherits the behaviour of normal str
'hello world'
py s.upper()  # overrides the normal upper method for my stupid one
'***'


Why would you do this? Well, obviously you wouldn't do something so 
stupid except as an exercise. It's hard to give *simple* real life 
examples that aren't contrived, but here's one that works for me:

Suppose you're writing software to control a model car. You might start 
off by collecting some basic defaults:

class DefaultModelCar:
model = Unknown

BRAKE_COMMAND = B
FORWARD_COMMAND = F
REVERSE_COMMAND = R
ACCELERATE_COMMAND = A
TURN_LEFT_COMMAND = TL
TURN_RIGHT_COMMAND = TR

def send_command(self, command):
# Send a command to the model car.
# Put the code here to actually communicate with the car.
...

def forward(self):
# Drive forward.
if self.direction == Reverse:
# Brake first, then move forward.
self.stop()
self.send_command(self.FORWARD_COMMAND)
self.send_command(self.ACCELERATE_COMMAND)
self.direction = Forward

def reverse(self):
if self.direction == Forward:
self.stop()
self.send_command(self.REVERSE_COMMAND)
self.send_command(self.ACCELERATE_COMMAND)
self.direction = Reverse

def stop(self):
self.send_command(self.BRAKE_COMMAND)
self.direction = Stopped



and so on. Now, this default set of commands probably won't work for any 
actual model car, but at least you can run it and test that it works as 
you expect:


car = DefaultModelCar()  # Create a car instance

Re: [Tutor] Beginner question

2013-08-12 Thread Ciaran Mooney


On 10 Aug 2013, at 04:30, eschneide...@comcast.net wrote:

 I've been learning python from the website 'inventwithpython.com', and I'm on 
 a chapter that covers the following code:
 
 import random
 import time
 def displayIntro():
 print('You are in a land full of dragons. In front of you,')
 print('you see two caves. In one cave, the dragon is friendly')
 print('and will share his treasure with you. The other dragon')
 print('is greedy and hungry, and will eat you on sight.')
 print()
 def chooseCave():
 cave = ''
 while cave != '1' and cave != '2':
 print('Which cave will you go into? (1 or 2)')
 cave = input()
  return cave
 def checkCave(chosenCave):
 print('You approach the cave...')
 time.sleep(2)
 print('It is dark and spooky...')
 time.sleep(2)
 print('A large dragon jumps out in front of you! He opens his jaws 
 and...')
 print()
 time.sleep(2)
 friendlyCave = random.randint(1, 2)
 if chosenCave == str(friendlyCave):
 print('Gives you his treasure!')
 else:
 print('Gobbles you down in one bite!')
 playAgain = 'yes'
 while playAgain == 'yes' or playAgain == 'y':
 displayIntro()
 caveNumber = chooseCave()
 checkCave(caveNumber)
 print('Do you want to play again? (yes or no)')
 playAgain = input()
 
 I'm confused about what the line 'checkCave(caveNumber)' does and how it 
 works. I would appreciate any help with this
 
 Thank you,
 
 Eric
 

Hi Eric,

This line calls the method 'checkCave()'. This method takes the argument 
caveNumber (checkCave(caveNumber) , which is a string returned from user input 
generated in the method chooseCave().

In checkCave method, the value (caveNumber) is then used in a if/else statement 
to compare with a random integer (parsed to a string str(frindlyCave))  to 
determine whether you will be eaten or given treasure ;)

Hope that was of some help. 

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


Re: [Tutor] Beginner question

2013-08-12 Thread Jim Mooney
On 12 August 2013 02:14, Karim Liateni kliat...@gmail.com wrote:

 5ÿt5ÿ6hhhyyyfrrtr

 eschneide...@comcast.net a écrit :

 I've been learning python from the website 'inventwithpython.com', and
 I'm on a chapter that covers the following code:


Just a quick note - not on the algorithm itself. If you run that in some
IDEs, such as Wing101, all the time.sleep()s will concatenate, and all the
prints will then print at once with no delay ;')  If that happens, run it
from the command line or try a different IDE.

Jim
-- 

If you don't know it's impossible, it's easier to do. --Neil Gaiman
The Process is not the Picture...Reality can only be proved to be
weakly-objective. Strong objectivity is a myth. --Bernardo Kastrup
You cannot use logic to justify logic, so logic itself has no basis other
than faith. --Agrippa
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Beginner question

2013-08-12 Thread Krishnan Shankar
def checkCave(chosenCave):
print('You approach the cave...')
time.sleep(2)
print('It is dark and spooky...')
time.sleep(2)
print('A large dragon jumps out in front of you! He opens his jaws
and...')
print()
   time.sleep(2)
friendlyCave = random.randint(1, 2)
if chosenCave == str(friendlyCave):
   print('Gives you his treasure!')
else:
print('Gobbles you down in one bite!')
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
displayIntro()
caveNumber = chooseCave()
checkCave(caveNumber)
print('Do you want to play again? (yes or no)')
playAgain = input()

Hi,

- Here we are passing the chosen integer (1 or 2) got from chooseCave()
method to checkCave as arguement
- When called in while loop inside checkCave the following happens;
- The statements of approaching the cave and seeing the dragon are
printed with a time interval of 2 secs between each
- Randomly either 1 or 2 is generated by the randint() method of random
module in python.
- That randomly generated integer (1 0r 2) is compared with our integer
input (1 or 2)
- If they match dragon gives us gold. Or else
- We will be eaten by dragon :)

But in the code there is a flaw. input() will evaluate your user input.
i.e. If you give an integer expression it will tell the answer. And when
you provide a number it will take it as int type. See below.

 var = input()
1+2+3
 var
6
 var = input()
2
 type(var)
type 'int'
 var = input()
s
Traceback (most recent call last):
  File stdin, line 1, in module
  File string, line 1, in module
NameError: name 's' is not defined
 var = input()

So since the integer number is checked with string in Line 13, it will run
into infinite loop. If you use raw_input() instead of input() you will be
able to run the example.

Regards,
Krishnan


On Mon, Aug 12, 2013 at 10:25 PM, Jim Mooney cybervigila...@gmail.comwrote:

 On 12 August 2013 02:14, Karim Liateni kliat...@gmail.com wrote:

 5ÿt5ÿ6hhhyyyfrrtr

 eschneide...@comcast.net a écrit :

 I've been learning python from the website 'inventwithpython.com', and
 I'm on a chapter that covers the following code:


 Just a quick note - not on the algorithm itself. If you run that in some
 IDEs, such as Wing101, all the time.sleep()s will concatenate, and all the
 prints will then print at once with no delay ;')  If that happens, run it
 from the command line or try a different IDE.

 Jim
 --

 If you don't know it's impossible, it's easier to do. --Neil Gaiman
 The Process is not the Picture...Reality can only be proved to be
 weakly-objective. Strong objectivity is a myth. --Bernardo Kastrup
 You cannot use logic to justify logic, so logic itself has no basis other
 than faith. --Agrippa


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


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


Re: [Tutor] Beginner question

2013-08-12 Thread Krishnan Shankar
But in the code there is a flaw. input() will evaluate your user input.
i.e. If you give an integer expression it will tell the answer. And when
you provide a number it will take it as int type. See below.

Hi,

Ignore my above statements if using Python 3. Sorry my bad. Had a doubt and
went to the site to see the version of python used. My statement above is
correct only if run in Python 2 and not in 3.

Regards,
Krishnan


On Mon, Aug 12, 2013 at 11:01 PM, Krishnan Shankar
i.am.song...@gmail.comwrote:

 def checkCave(chosenCave):
 print('You approach the cave...')
 time.sleep(2)
 print('It is dark and spooky...')
 time.sleep(2)
 print('A large dragon jumps out in front of you! He opens his jaws
 and...')
 print()
time.sleep(2)
 friendlyCave = random.randint(1, 2)
 if chosenCave == str(friendlyCave):
print('Gives you his treasure!')
 else:
 print('Gobbles you down in one bite!')
 playAgain = 'yes'
 while playAgain == 'yes' or playAgain == 'y':
 displayIntro()
 caveNumber = chooseCave()
 checkCave(caveNumber)
 print('Do you want to play again? (yes or no)')
 playAgain = input()

 Hi,

 - Here we are passing the chosen integer (1 or 2) got from chooseCave()
 method to checkCave as arguement
 - When called in while loop inside checkCave the following happens;
 - The statements of approaching the cave and seeing the dragon are
 printed with a time interval of 2 secs between each
 - Randomly either 1 or 2 is generated by the randint() method of
 random module in python.
 - That randomly generated integer (1 0r 2) is compared with our
 integer input (1 or 2)
 - If they match dragon gives us gold. Or else
 - We will be eaten by dragon :)

 But in the code there is a flaw. input() will evaluate your user input.
 i.e. If you give an integer expression it will tell the answer. And when
 you provide a number it will take it as int type. See below.

  var = input()
 1+2+3
  var
 6
  var = input()
 2
  type(var)
 type 'int'
  var = input()
 s
 Traceback (most recent call last):
   File stdin, line 1, in module
   File string, line 1, in module
 NameError: name 's' is not defined
  var = input()

 So since the integer number is checked with string in Line 13, it will run
 into infinite loop. If you use raw_input() instead of input() you will be
 able to run the example.

 Regards,
 Krishnan


 On Mon, Aug 12, 2013 at 10:25 PM, Jim Mooney cybervigila...@gmail.comwrote:

 On 12 August 2013 02:14, Karim Liateni kliat...@gmail.com wrote:

 5ÿt5ÿ6hhhyyyfrrtr

 eschneide...@comcast.net a écrit :

 I've been learning python from the website 'inventwithpython.com', and
 I'm on a chapter that covers the following code:


 Just a quick note - not on the algorithm itself. If you run that in some
 IDEs, such as Wing101, all the time.sleep()s will concatenate, and all the
 prints will then print at once with no delay ;')  If that happens, run it
 from the command line or try a different IDE.

 Jim
 --

 If you don't know it's impossible, it's easier to do. --Neil Gaiman
 The Process is not the Picture...Reality can only be proved to be
 weakly-objective. Strong objectivity is a myth. --Bernardo Kastrup
 You cannot use logic to justify logic, so logic itself has no basis
 other than faith. --Agrippa


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



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


[Tutor] Beginner question

2013-08-11 Thread eschneider92
I've been learning python from the website 'inventwithpython.com', and I'm on a 
chapter that covers the following code: 



import random 
import time 
def displayIntro(): 
print('You are in a land full of dragons. In front of you,') 
print('you see two caves. In one cave, the dragon is friendly') 
print('and will share his treasure with you. The other dragon') 
print('is greedy and hungry, and will eat you on sight.') 
print() 
def chooseCave(): 
cave = '' 
while cave != '1' and cave != '2': 
print('Which cave will you go into? (1 or 2)') 
cave = input() 
return cave 
def checkCave(chosenCave): 
print('You approach the cave...') 
time.sleep(2) 
print('It is dark and spooky...') 
time.sleep(2) 
print('A large dragon jumps out in front of you! He opens his jaws and...') 
print() 
time.sleep(2) 
friendlyCave = random.randint(1, 2) 
if chosenCave == str(friendlyCave): 
print('Gives you his treasure!') 
else: 
print('Gobbles you down in one bite!') 
playAgain = 'yes' 
while playAgain == 'yes' or playAgain == 'y': 
displayIntro() 
caveNumber = chooseCave() 
checkCave(caveNumber) 
print('Do you want to play again? (yes or no)') 
playAgain = input() 

I'm confused about what the line 'checkCave(caveNumber)' does and how it works. 
I would appreciate any help with this 

Thank you, 

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


Re: [Tutor] Beginner question

2013-08-11 Thread Alan Gauld

On 10/08/13 04:30, eschneide...@comcast.net wrote:

I've been learning python from the website 'inventwithpython.com', and
I'm on a chapter that covers the following code:

import random
import time



def displayIntro():
  print('You are in a land full of dragons. In front of you,')
  print('you see two caves. In one cave, the dragon is friendly')
  print('and will share his treasure with you. The other dragon')
  print('is greedy and hungry, and will eat you on sight.')
  print()




def chooseCave():
 cave = ''
 while cave != '1' and cave != '2':
 print('Which cave will you go into? (1 or 2)')
 cave = input()
  return cave




def checkCave(chosenCave):
 print('You approach the cave...')
 time.sleep(2)
 print('It is dark and spooky...')
 time.sleep(2)
 print('A large dragon jumps out in front of you! He opens his jaws
and...')
 print()
 time.sleep(2)
 friendlyCave = random.randint(1, 2)
 if chosenCave == str(friendlyCave):
 print('Gives you his treasure!')
 else:
 print('Gobbles you down in one bite!')




playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
 displayIntro()
 caveNumber = chooseCave()
 checkCave(caveNumber)
 print('Do you want to play again? (yes or no)')
 playAgain = input()




I'm confused about what the line 'checkCave(caveNumber)' does and how it
works. I would appreciate any help with this


It calls the checkCave function defined above. It passes in the cave 
'number' as an argument. The function basically decides whether the 
monster inside is friendly or not and prints an appropriate message.

It then returns control to the main while loop.

Does that help?

--
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] beginner question

2011-11-01 Thread Mayo Adams
When writing a simple for loop like so:

 for x in f

where f is the name of a file object, how does Python know to interpret
the variable x as a line of text, rather than,say, an individual character
in the file? Does it automatically
treat text files as sequences of lines?

-- 
Mayo Adams


287 Erwin Rd.
Chapel Hill, NC 27514
(919)-968-7889
mayoad...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] beginner question

2011-11-01 Thread Steve Willoughby

On 01-Nov-11 08:34, Mayo Adams wrote:

When writing a simple for loop like so:

  for x in f

where f is the name of a file object, how does Python know to interpret
the variable x as a line of text, rather than,say, an individual
character in the file? Does it automatically
treat text files as sequences of lines?


Every object defines what its behavior will be when asked to do 
something.  In this case, file objects know that they are capable of 
iterating over a list of their contents by being used in a for x in f 
loop construct.  The file object knows to respond to that by yielding up 
a line from the file for every iteration.


You could, theoretically, write a variation of the file object class 
which iterated over characters, or logical blocks (records of some sort) 
within files, and so forth.


--
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
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] beginner question

2011-11-01 Thread Peter Otten
Steve Willoughby wrote:

 On 01-Nov-11 08:34, Mayo Adams wrote:
 When writing a simple for loop like so:

   for x in f

 where f is the name of a file object, how does Python know to interpret
 the variable x as a line of text, rather than,say, an individual
 character in the file? Does it automatically
 treat text files as sequences of lines?
 
 Every object defines what its behavior will be when asked to do
 something.  In this case, file objects know that they are capable of
 iterating over a list of their contents by being used in a for x in f
 loop construct.  The file object knows to respond to that by yielding up
 a line from the file for every iteration.
 
 You could, theoretically, write a variation of the file object class
 which iterated over characters, or logical blocks (records of some sort)
 within files, and so forth.
 
Here's a simple example of a class derived from file that iterates over 
characters (bytes) instead of lines.

Standard file:

 for line in open(tmp.txt):
... print repr(line)
...
'this\n'
'is but an\n'
'example\n'

Modified file class:

 class MyFile(file):
... def next(self):
... c = self.read(1)
... if not c:
... raise StopIteration
... return c
...
 for c in MyFile(tmp.txt):
... print repr(c)
...
't'
'h'
'i'
's'
'\n'
'i'
's'
' '
'b'
'u'
't'
' '
'a'
'n'
'\n'
'e'
'x'
'a'
'm'
'p'
'l'
'e'
'\n'


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


Re: [Tutor] beginner question

2011-11-01 Thread Steven D'Aprano

Mayo Adams wrote:

When writing a simple for loop like so:

 for x in f

where f is the name of a file object, how does Python know to interpret
the variable x as a line of text, rather than,say, an individual character
in the file? Does it automatically
treat text files as sequences of lines?


Nice question! But the answer is a little bit complicated. The short 
answer is:


File objects themselves are programmed to iterate line by line rather 
than character by character. That is a design choice made by the 
developers of Python, and it could have been different, but this choice 
was made because it is the most useful.


The long answer requires explaining how for-loops work. When you say

for x in THINGY: ...

Python first asks THINGY to convert itself into a iterator. It does that 
by calling the special method THINGY.__iter__(), which is expected to 
return an iterator object (which may or may not be THINGY itself). If 
there is no __iter__ method, then Python falls back on an older sequence 
protocol which isn't relevant to files. If that too fails, then Python 
raises an error.


So what's an iterator object? An iterator object must have a method 
called next (in Python 2), or __next__ (in Python 3), which returns 
the next item. The object is responsible for knowing what value to 
return each time next() is called. Python doesn't need to know anything 
about the internal details of the iterator, all it cares about is that 
when it calls THINGY.next() or THINGY.__next__(), the next item will be 
returned. All the intelligence is inside the object, not in Python.


When there are no more items left to return, next() should raise 
StopIteration, which the for loop detects and treats as loop is now 
finished rather than as an error.


So, the end result of all this is that Python doesn't care what THINGY 
is, so long as it obeys the protocol. So anyone can create new kinds of 
data that can be iterated over. In the case of files, somebody has 
already done that for you: files are built into Python.


Built-in file objects, like you get from f = open(some file, r), 
obey the iterator protocol. We can run over it by hand, doing exactly 
what Python does in a for-loop, only less conveniently.


Suppose we have a file containing fee fi fo fum split over four lines. 
Now let's iterate over it by hand. File objects are already iterators, 
so in Python 3 they have their own __next__ method and there's no need 
to call __iter__ first:


 f = open('temp.txt', 'r')
 f.__next__()
'fee\n'
 f.__next__()
'fi\n'
 f.__next__()
'fo\n'
 f.__next__()
'fum\n'
 f.__next__()
Traceback (most recent call last):
  File stdin, line 1, in module
StopIteration



So the file object itself keeps track of how much of the file has been 
read, and the Python interpreter doesn't need to know anything about 
files. It just needs to know that the file object is iterable. I already 
know this, so I took a short-cut, calling f.__next__() directly. But 
Python doesn't know that, it performs one extra step: it calls 
f.__iter__ to get an iterator object:


 f.__iter__()
_io.TextIOWrapper name='temp.txt' encoding='UTF-8'

In this case, that iterator object is f itself, and now the Python 
interpreter goes on to call __next__() repeatedly.


File objects are actually written in C for speed, but if they were 
written in pure Python, they might look something vaguely like this:



class File(object):
def __init__(self, name, mode='r'):
self.name = name
if mode == 'r':
... # open the file in Read mode
elif mode == 'w':
... # open in Write mode
else:
# actually there are other modes too
raise ValueError('bad mode')

def __iter__(self):
return self  # I am my own iterator.

def read(self, n=1):
# Read n characters. All the hard work is in here.
...

def readline(self):
# Read a line, up to and including linefeed.
buffer = []
c = self.read()
buffer.append(c)
while c != '' and c != '\n':
c = self.read()  # Read one more character.
buffer.append(c)
return ''.join(buffer)

def __next__(self):
line = self.readline()
if line == '':
# End of File
raise StopIteration
else:
return line


--
Steven

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


Re: [Tutor] Beginner question(s)

2006-06-19 Thread David Rock
* Ismael Garrido [EMAIL PROTECTED] [2006-06-18 19:34]:
 Alan Gauld wrote:
  Also, does anyone know of a PDA that would run python?  
  
 
  There was a project called pippy, but I haven't heard anything of it 
  recently so I don't know if its still around or if it runs on modern 
  PDAs - I think it was PalmOS anyhow...
 

 
 Pippy is quite dead. No development done recently. It supposedly runs 
 fine, but runs only Python 1.5.

Last I used it, it worked fine, but it was limited.

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


[Tutor] Beginner question(s)

2006-06-18 Thread Bill Tatum








Hi,



Im working through Python Programming for the
Absolute Beginner. One of the challenges at the end of chapter 4 is to
get a message from the user and then print it out backwards. I have



message = raw_input(Enter your message:)

count = len(message)

print count



which gives me the number of characters in the
message. I tried to use a for loop:



for i in range(len(message)-1,-1, -1):

 print i,



but I just get the numeric values of the string. Can
anyone help?



Also, does anyone know of a PDA that would run python?




TIA








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


Re: [Tutor] Beginner question(s)

2006-06-18 Thread Alan Gauld
 message = raw_input(Enter your message:)
 for i in range(len(message)-1,-1, -1):
print i,
 
 but I just get the numeric values of the string.  Can anyone help?

As an alternative approach consider converting to a list and 
using the reverse method...

 Also, does anyone know of a PDA that would run python?  

There was a project called pippy, but I haven't heard anything of it 
recently so I don't know if its still around or if it runs on modern 
PDAs - I think it was PalmOS anyhow...

There was rumours of a Pocket Windows version too but 
I've never really been interested in that one...

Alan G.

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


Re: [Tutor] Beginner question(s)

2006-06-18 Thread Ismael Garrido
Alan Gauld wrote:
 Also, does anyone know of a PDA that would run python?  
 

 There was a project called pippy, but I haven't heard anything of it 
 recently so I don't know if its still around or if it runs on modern 
 PDAs - I think it was PalmOS anyhow...

   

Pippy is quite dead. No development done recently. It supposedly runs 
fine, but runs only Python 1.5.

If you want it, it's at:
http://sourceforge.net/projects/pippy

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


Re: [Tutor] Beginner Question

2006-06-18 Thread Daniel McQuay
On 6/18/06, Josh F [EMAIL PROTECTED] wrote:
re. Beginner QuestionI'm still in the fairly early stages of learning Python, but I have anintermediate level of HTML, CSS, and VB6 knowledge along with thefundamentals of C and C++ and a very little bit of PERL..
But enough about me...Here's the solution.message = raw_input(Enter your message:)print message[-1::-1]just another noob here.but wouldn't his way work like this:
message = foobarfor i in range(len(message)-1,-1,-1):...  print message[i],...r a b o o fi guess there's lots of ways to do it. that's my 2 cents.
Slicing a string takes three arguments, all of which are optional: The firstcharacter to be sliced, the last character to be sliced, and tio slice every
nth character.In Python strings, -1 refers to the last character in the string and thusbecomes the first argument.You don't specify the second argument because you're printing the stringfrom end to beginning.
Finallly, the -1 in the 3rd argument indicates that you want the string tobe printed in reverse order (i.e. iterate backwards by one character).Message: 1Date: Sun, 18 Jun 2006 05:58:38 -0500
From: Bill Tatum [EMAIL PROTECTED]Subject: [Tutor] Beginner question(s)To: tutor@python.orgMessage-ID: 
[EMAIL PROTECTED]Content-Type: text/plain; charset=us-asciiHi,I'm working through Python Programming for the Absolute Beginner.One of
the challenges at the end of chapter 4 is to get a message from the userandthen print it out backwards. I have.message = raw_input(Enter your message:)
count = len(message)print countwhich gives me the number of characters in the message.I tried to use afor loop:for i in range(len(message)-1,-1, -1):
 print i,but I just get the numeric values of the string.Can anyone help?Also, does anyone know of a PDA that would run python?
TIA___Tutor maillist-Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor-- Daniel McQuay[EMAIL PROTECTED]
boxster.homelinux.orgH: 814.825.0847M: 814-341-6233
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Beginner question(s)

2006-06-18 Thread John Fouhy
 Also, does anyone know of a PDA that would run python?

Some of the new Nokias run python: http://www.forum.nokia.com/python

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


Re: [Tutor] Beginner question (variables, namespaces...) (fwd)

2006-04-08 Thread Kent Johnson
 From: Jesse [EMAIL PROTECTED]
 
 I tried redefining the higher-order variables as functions, but it didn't
 quite work. Here's a simplified example:
 
 
 var1 = 2
 
 def timestwo(x):
 return x*2
 
 
 var2 = timestwo(var1)
 print var1, var2
 var1 = 3
 print var1, var2
 
 This results in the output:
 2, 4
 3,4

You still have to call the function whenever you need the value.
print var1, timestwo(var1)
var1 = 3
print var1, timestwo(var1)

 
 ..which is not what I'm aiming for. Maybe I'll have to follow Bob's advice
 and just store all of the variable assignments in a function, and then call
 the function every time I change one of the variables (based on user input).
 I could still leave the higher-order variables as functions as per your
 advice, but that alone doesn't seem to do the trick. Unless I've missed
 something.

Danny's suggestion of using class properties is a good one, it allows 
you to automate the recalculation of the variables, and also protect 
against directly assigning one of the calculated values.

Here is a class that has two attributes, val and val2. val can be 
assigned normally. val2 is read-only and always equal to twice val.

Whenever a new value is assigned to val, the internal _recalculate() 
method is called. This is slightly more complex than needed for this 
example (_set_val()) could calculate val2 directly) but it extends 
easily to multiple settable and calculated values.

The only problem with this approach is that it is not really beginner 
material, you need some understanding of classes and properties. I don't 
know of any beginner references for properties but you could try this:
http://users.rcn.com/python/download/Descriptor.htm#properties

Anyway here is the code:

#
class AutoCompute(object):
 def __init__(self, val):
 self.val = val

 # Create a property named val
 # Setting val triggers recomputation
 def _set_val(self, val):
 self._val = val
 self._recompute()

 def _get_val(self):
 return self._val

 val = property(_get_val, _set_val)

 # Create a read-only property named val2
 def _get_val2(self):
 return self._val2

 val2 = property(_get_val2)


 def _recompute(self):
 self._val2 = self._val * 2

ac = AutoCompute(3)
print ac.val, ac.val2

# Assigning to ac.val changes ac.val2 also
ac.val = 4
print ac.val, ac.val2

# This raises AttributeError, val2 is read-only
ac.val2 = 5
###

When run, the output is
3 6
4 8
Traceback (most recent call last):
   File F:\Tutor\ComputedProperty.py, line 33, in ?
 ac.val2 = 5
AttributeError: can't set attribute

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


Re: [Tutor] Beginner question (variables, namespaces...) (fwd)

2006-04-08 Thread Danny Yoo

 I tried redefining the higher-order variables as functions, but it
 didn't quite work. Here's a simplified example:


 var1 = 2

 def timestwo(x):
 return x*2

 var2 = timestwo(var1)
 print var1, var2
 var1 = 3
 print var1, var2

Try:

##
print 2, timestwo(2)
print 3, timestwo(3)
##


Alternatively, try:

##
var1 = 2
print var1, timestwo(var1)
var1 = 3
print var1, timestwo(var1)
##


What do you expect to see?



 ..which is not what I'm aiming for. Maybe I'll have to follow Bob's
 advice and just store all of the variable assignments in a function, and
 then call the function every time I change one of the variables (based
 on user input). I could still leave the higher-order variables as
 functions as per your advice, but that alone doesn't seem to do the
 trick. Unless I've missed something.

You're missing something.  *wink*

Play with this a little more.  It's something basic in Python, and you'll
want to get this squared away so it doesn't cause you grief later.

The model you have about how variables behave in Python is slightly off
still: I think you're still thinking of them like math equations.  But
Python's model for assigning variable names to values don't work like
equality: it's more of a this box now contains the value described by the
right hand side at this particular time.

So if we see:

a = 3
b = 4
a = a + b

we can model this as:

[a : 3]   (after stmt: a = 3)

[a : 3,  b : 4]  (after stmt: b = 4)

[a : 7, b : 4](after stmt: a = a + b)

where we keep a list of names and their current values.  (I'm just using
an ad-hoc notation for the stuff in the brackets.)  Assignment erases the
old value and replaces it with a new one as we flow through our program.

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


Re: [Tutor] Beginner question (variables, namespaces...) (fwd)

2006-04-08 Thread Danny Yoo
  ..which is not what I'm aiming for. Maybe I'll have to follow Bob's
  advice and just store all of the variable assignments in a function,
  and then call the function every time I change one of the variables
  (based on user input). I could still leave the higher-order variables
  as functions as per your advice, but that alone doesn't seem to do the
  trick. Unless I've missed something.

 Danny's suggestion of using class properties is a good one, it allows
 you to automate the recalculation of the variables, and also protect
 against directly assigning one of the calculated values.

Just wanted to clarify that this is not my suggestion: Alan proposed this.

But I think we should steer away a little away from full-fledged classes
at the moment.  The professional solution would be to do this, but I'm
not sure how appropriate it is for Jesse to do this yet.  Jesse is still
confused about how variables work.  In which case, suggesting him to look
at classes will just make things worse.  *grin*

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


[Tutor] Beginner question (variables, namespaces...)

2006-04-07 Thread Jesse
Why is it that when one variable is assigned a value in terms of another variable, assigning a new value to the first doesn't change the value of the second? This is giving me a huge headache, since I have a bunch of variables defined in terms of one another, and I want to be able to dynamically update them (I did not include the definitions of the functions overstock and roundup, but they work): 


stock = float(raw_input(Enter stock (in terms of portions: ))container = float(raw_input(Enter portions percontainer: ))price_per_container = float(raw_input(Enter price per container: )) 
weekly_quota = float(raw_input(Enter quota (in terms of portions): ))extra = overstock(stock, weekly_quota) # overstock returns 0 if the first argument is less than the second; otherwise itreturns the 

 difference between the first argument and the second.need = weekly_quota - extrabuy_containers = roundup(need/container) # roundup rounds a non-integer to the next highest integer 
buy_portions = buy_containers * containerleftover = buy_portions - needcost = price_per_container * buy_containers

I would like to write a function that will update the values of the above variables given an increase inonly thestock variable. Otherwise I'd have to repeat a bunch of code...:(

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


Re: [Tutor] Beginner question (variables, namespaces...)

2006-04-07 Thread Danny Yoo


On Fri, 7 Apr 2006, Jesse wrote:

 Why is it that when one variable is assigned a value in terms of another
 variable, assigning a new value to the first doesn't change the value of
 the second?

Hi Jesse,

If you have a variable that depends on the values of other parameters,
that's just begging to be represented as a function.  Let's look at some
of those computations:


 stock = float(raw_input(Enter stock (in terms of portions: ))
 container = float(raw_input(Enter portions per container: ))
 price_per_container = float(raw_input(Enter price per container: ))
 weekly_quota = float(raw_input(Enter quota (in terms of portions): ))

 extra = overstock(stock, weekly_quota)
 need = weekly_quota - extra
 buy_containers = roundup(need/container) # roundup rounds a non-integer to
 the next highest integer
 buy_portions = buy_containers * container
 leftover = buy_portions - need
 cost = price_per_container * buy_containers


Yeah, rather than code these as explicit variables, I'd strongly recommend
rewriting each of these as functions.  Concretely:


def extra(stock, weekly_quota):
return overstock(stock, weekly_quota)

def need(stock, weekly_quota):
return weekly_quota - extra(stock, weekly_quota)

def buy_containers(stock, weekly_quota, container):
return roundup(need(stock, weekly_quota) - extra(stock, weekly_quota))
...


It's a little ugly, but this coding explicitely defines the dependencies
between the inputs into our system and the expected outputs.  When we look
at buy_containers(), we can easily see that any change in the stock,
weekly_quote, or container parameters may have some profound affect on the
output to buy_containers().

That dependency between input and output is what we try to capture when we
write a function.  So if you recode your assignment statements as function
definitions, you should be better able to handle changes to your input.

If we think of the names we use for these concepts, there's something
ironic that functions behave better on varying data than variables.  Oh
well.



As an advanced aside: the equations that you're writing into Python,
unfortunately, aren't treated as real math equations, but as separate,
independent assignment statements.  I think I know what you want, but
Python doesn't provide it out of the box.  What I think you want is called
constraint programming.  Such systems do exist.  For example:

http://www.logilab.org/projects/constraint

I can't vouch for the maturity of logilab's constraint module; I haven't
played with it yet.


But if you're interested, you may want to look at the treatment of simple
constraint systems in the classic textbook Structure and Interpretation
of Computer Programs:

   http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-22.html#%_sec_3.3.5

It should be very possible to adapt the material there into Python,
although it might take a fair bit of work if you're not familiar with
Scheme.


Good luck to you!

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


Re: [Tutor] Beginner question (variables, namespaces...)

2006-04-07 Thread Bob Gailer
Jesse wrote:
 Why is it that when one variable is assigned a value in terms of 
 another variable, assigning a new value to the first doesn't change 
 the value of the second? This is giving me a huge headache, since I 
 have a bunch of variables defined in terms of one another, and I want 
 to be able to dynamically update them (I did not include the 
 definitions of the functions overstock and roundup, but they work):
  
 stock = float(raw_input(Enter stock (in terms of portions: ))
 container = float(raw_input(Enter portions per container: ))
 price_per_container = float(raw_input(Enter price per container: ))
 weekly_quota = float(raw_input(Enter quota (in terms of portions): ))
 extra = overstock(stock, weekly_quota)  # overstock returns 0 if the 
 first argument is less than the second; otherwise it returns the
   
 difference between the first argument and the second.
 need = weekly_quota - extra
 buy_containers = roundup(need/container) # roundup rounds a 
 non-integer to the next highest integer
 buy_portions = buy_containers * container
 leftover = buy_portions - need
 cost = price_per_container * buy_containers
  
 I would like to write a function that will update the values of the 
 above variables given an increase in only the stock variable. 
 Otherwise I'd have to repeat a bunch of code...:(
def recalculate():
global extra, need, buy_containers, buy_portions, leftover, cost
extra = overstock(stock, weekly_quota)
need = weekly_quota - extra
buy_containers = roundup(need/container)
buy_portions = buy_containers * container
leftover = buy_portions - need
cost = price_per_container * buy_containers

That's all there is to it.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Beginner question (variables, namespaces...) (fwd)

2006-04-07 Thread Danny Yoo


-- Forwarded message --
Date: Fri, 7 Apr 2006 21:05:33 -0600
From: Jesse [EMAIL PROTECTED]
To: Danny Yoo [EMAIL PROTECTED]
Subject: Re: [Tutor] Beginner question (variables, namespaces...)

I tried redefining the higher-order variables as functions, but it didn't
quite work. Here's a simplified example:


var1 = 2

def timestwo(x):
return x*2


var2 = timestwo(var1)
print var1, var2
var1 = 3
print var1, var2

This results in the output:
2, 4
3,4

..which is not what I'm aiming for. Maybe I'll have to follow Bob's advice
and just store all of the variable assignments in a function, and then call
the function every time I change one of the variables (based on user input).
I could still leave the higher-order variables as functions as per your
advice, but that alone doesn't seem to do the trick. Unless I've missed
something.

Jesse

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