Re: [Tutor] [OT] Programming practice was: Re: string list in alphabetical!

2013-10-22 Thread ALAN GAULD
The interesting thing however is that the schools have not taught
>>any kind of approach to problem solving, they just give a homework assignment 
>>and expect them to produce code.
>
>
>I feel like we've had this conversation a long, long time ago.  :P
>
>
>This is the sort of thing that we should be expect out of math classes.  |
>Polya's "How to Solve It" gives an approachYou're right Danny, we have had 
>similar discussions a while back. 
In fact I bought Polya's book after your recommendation :-)
But in my friend's case he does not do math at his school - they have 
made it an optional subject after second grade apparently! 
Add to this the fact that English is not his first language and 
that his old school was a year behind his current school and 
you can see why computing science is a challenge for him!
Another place where I'm seeing the act of problem solving being explicitly 
taught is in "How to Design Programs":
>
>
>
>    http://www.ccs.neu.edu/home/matthias/HtDP2e/
>Yes I really like this, even though their approach does rely 
on recursion (being based in Scheme) so doesn't always work
for other languages. It's also very math oriented in the problems 
they solve which wouldn't work for my young mathless friend..

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


Re: [Tutor] Fwd: Re: Passing arguments?

2013-10-22 Thread Jenny Allar
Thank you all for your help with this program. Each of your answers helped
me piece together an understanding of the assignment. After several days
and clearly over-thinking the entire process, I ended up using the
following code:

def main ():
name = input("Please enter the name of the product: ")
weight = float(input("Please enter the weight of the product in pounds:
"))

cal_shiprate (name, weight)

def cal_shiprate(product_name, product_weight):

if product_weight < 10:
   ship_rate = 1.5
elif product_weight >= 10 and product_weight < 25:
   ship_rate = 1.45
else:
ship_rate = 1.4

total = product_weight * ship_rate

print("")
print(product_name, "weight in pounds  ", format
(product_weight, '9,.2f'))
print ("Your total to ship", product_name, "is:  $", format (total,
'9,.2f'))




main ()




On Sun, Oct 20, 2013 at 6:01 PM, Ricardo Aráoz  wrote:

>  Sorry, I sent this answer to the OP directly and not to the list.
>
>  Mensaje original   Asunto: Re: [Tutor] Passing arguments?  
> Fecha:
> Sun, 20 Oct 2013 11:25:52 -0300  De: Ricardo Aráoz 
>   A:
> Jenny Allar  
>
>
> El 20/10/13 01:20, Jenny Allar escribió:
>
>  I've written the code below the assignment, and I think I have
> everything covered in terms of asking the user for the information I need
> and somehow calculating costs, but I'm just ridiculously confused on the
> order and placement of the functions and components of this program-
> specifically the shiprate variable. Thank you in advance for any help.
>
>
> Ok, just a couple of things first.
>
> - Your assignment specifically says 'always use "while loops" to validate'
> but I see no loop at all in your code. You might want to look into it.
>
> - What your assignment points to when it says to use "while loops" is
> that you should validate that what the user inputs is a valid number. If
> the user will input something else than a number as the weight then when
> you apply the int() function an exception will be flagged and your program
> will terminate ungracefully. You may validate input using "exceptions" and
> "while loops" (look it up).
>
> - Your functions should do what their name imply, and preferably do only
> one thing. Having a function named calc_weight_large() that also prints the
> shipping cost is not good.
>
> - Your if asks for >= 10 and your elif for <= 10 when the "= 10" case was
> already handled by the first if, that is a mistake. Besides which it might
> be better looking (though this is a matter of personal preference) if you ::
> if weight > 25
> # do something
> elif weight > 10
> # do something else
> else
> # do something entirely different
>
> - I would structure the program in the following way ::
> def main():
> product = in_product()
> weight = in_weight()
>
> if weight > 25
> total = calc_shipping(1.40, weight)
> elif weight > 10
> total = calc_shipping(1.45, weight)
> else
> total = calc_shipping(1.50, weight)
> print_data(product, weight, total)
>
>  This is my assignment:
>
> Write a program that asks a user for the name of a product that they are
> ordering online and its weight.  The program must calculate the cost of
> shipping the product using the following cost structure.  If it weighs less
> than 10 pounds the cost is $1.50 per pound, if it is 10 pounds or more and
> less than 25 pounds then the cost is $1.45 per pound.  If the weight is 25
> pounds or more the cost is $1.40 per pound.  You may get the data from the
> user in main.  You must print the name of the product, the weight and the
> cost of shipping in a separate function.
>
>
>
> **NOTE:  ALWAYS USE “WHILE LOOPS” To Validate
> # This program uses an if-else statement
>
> # It asks for the name of a product and the weight of that product.
> # It then determines the shipping cost as defined by the weight.
> #
> # Variable  Type  Purpose
> # product   string  hold for name of product
> # weight float   hold for weight of product
> #
>
> def main ():
> product = input("Please enter the name of the product: ")
> weight = int(input("Please enter the weight of the product: "))
>
> print('Product:', product)
> print('Weight:', weight)
>
> if weight <= 10:
> shiprate = 1.5
> calc_weight_small(weight, shiprate)
> elif weight >= 10 and weight <= 25:
> shiprate = 1.45
> calc_weight_medium(weight, shiprate)
> else:
> shiprate = 1.4
> calc_weight_large(weight, shiprate)
>
> # Calculate shipping cost for product less than 10 pounds
> def cacl_weight_small(weight, shiprate):
> shiprate = 1.5
> total = weight * shiprate
>
>
>  # Calculate shipping cost for product betw

Re: [Tutor] [OT] Programming practice was: Re: string list in alphabetical!

2013-10-22 Thread Sydney Shall

On 22/10/2013 00:42, Alan Gauld wrote:

On 22/10/13 00:07, Steven D'Aprano wrote:


I'd like to upgrade that process :D ...

1) think about your problem
2) if there are some heplful libraries that can make it way easier, 
use them

3) write some code
4) fix the bugs until it'll run
5) write unittests
6) test if it works correctly and if unittests pass
7) repeat until done



Heh, very true! But the most important step is step 1,


I agree. I've recently started coaching the son of a friend in 
computing for his new school (he is effectively a year behind

his new classmates). They use VB6 but at a level I can cope with! :-)

The interesting thing however is that the schools have not taught
any kind of approach to problem solving, they just give a homework 
assignment and expect them to produce code. My friend wants to

dive into Vuisual Studio to start work immediately. I've been
trying to get him to adopt a workflow where he writes on paper
an informal "use case" description of the solution and if
necessary a pseudo code design. But it's been a real challenge
to get him to slow down and understand exactly what he is being
asked to do before diving into code. (Some of that is just
natural youthful impatience, but mostly it's lack of instruction
in an alternative! :-)


Alan,
I am a newcomer to Python programing.
Could you please explain exactly what you mean by 'an informal "use 
case" description of the solution ..'?

I am not clear how this differs from pseudo code design.
Thanks to you all for your generous and always invaluable help.
Sydney

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


Re: [Tutor] [OT] Programming practice was: Re: string list in alphabetical!

2013-10-22 Thread bob gailer
I am glad we are having this discussion. It helps me understand the 
plight of some of our posters.


I had the benefit of a good school system, plus attending a technical 
high school and a college of engineering.


In the early 90's I was an adjunct professor at the University of 
Denver's "University College" - evening school for adults seeking an 
MBA. Each class met for 2 hours once a week for 5 weeks. No labs. My job 
was to teach Pascal as a first programming language. My students had 
taken one prerequisite - Introduction To Programming. I built my class 
based on the students' having met the prerequisite. One class of mine 
were struggling with certain fundamental concepts. Turns out the Intro 
class had failed to do its job! One outcome is that I was fired for 
failing to teach Pascal.


BTW Python did not exist then, and I have always disliked Pascal.

As adjunct professor for a similar program at Regis University (Denver) 
I was given an Analysis class to teach. My supervisor created a brand 
new course. The first time I saw the materials was the first night of 
the class! No one had a chance to examine the materials beforehand! That 
class was -`difficult for me and the students.


On the bright side in the 80's I taught daytime adult classes in 
computing for the Boeing company. I was free to change classes that had 
poor materials to (IMHO) good materials. It was almost always fun and I 
almost always got really good evaluations.


I recall one student struggling with his first Basic program. I 
recommended he walk thru it line by line, and I demonstrated that 
technique. Amazed he exclaimed "In that much detail?".


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

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


Re: [Tutor] Fwd: Re: Passing arguments?

2013-10-22 Thread Alan Gauld

On 22/10/13 03:23, Jenny Allar wrote:

I ended up using the following code:


One wee improvement you could consider:


def cal_shiprate(product_name, product_weight):
 if product_weight < 10:
ship_rate = 1.5
 elif product_weight >= 10 and product_weight < 25:
ship_rate = 1.45
 else:
 ship_rate = 1.4

 total = product_weight * ship_rate

 print("")
 print(product_name, "weight in pounds  ", format
(product_weight, '9,.2f'))
 print ("Your total to ship", product_name, "is:  $", format
(total, '9,.2f'))


The function is called cal_shiprate but it does more than that it prints 
it out too.
Its usually a bad idea to mix calculations and display in the same 
function so maybe you could just return the total and do the printing in 
the main function? That way you don't need to pass in the product name, 
which is not required for the calculation.


Also for the printing part the string formatting mechanism in Python 
doesn't work quite the way you have it. format() is a method of the 
string not a separate function. So your main() would end up looking 
something like:



def main ():
name = input("Please enter the name of the product: ")
weight = float(input("Enter weight of product in pounds: "))

cost = cal_shiprate (weight)

print("{} weight in pounds {:<9.2f}".format(
   product_name,product_weight))
print("Your total to ship {} is: {:>10}{:<9.2f}".format(
   product_name, '$', cost))



Just a minor tweak.

--
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] Fwd: Re: Passing arguments?

2013-10-22 Thread Ricardo Aráoz
- Did you notice your assignment specifically asks for a "while" loop 
for validation? That means you are expected to validate input. Run your 
program and when the program asks "Please enter the weight of the 
product in pounds: " answer "123...this is a mistake", what does it 
happen? Your program should answer "That is not a valid weight" and ask 
for the weight again. Does it? (tip: you should be using "while" and "on 
error")


- You have a function named cal_shiprate(), according to it's name this 
function should calculate the shipping rate NO MORE. But your function 
also prints not only the shipping rate but some other info too. So you 
either name your function 
cal_shiprate_and_print_with_prodname_and_weightf() or your function 
should ONLY calculate the shipping rate and you should have ANOTHER 
function to print the info. The recommended approach would be the second 
one.



El 21/10/13 23:23, Jenny Allar escribió:
Thank you all for your help with this program. Each of your answers 
helped me piece together an understanding of the assignment. After 
several days and clearly over-thinking the entire process, I ended up 
using the following code:


def main ():
name = input("Please enter the name of the product: ")
weight = float(input("Please enter the weight of the product in 
pounds: "))


cal_shiprate (name, weight)

def cal_shiprate(product_name, product_weight):

if product_weight < 10:
   ship_rate = 1.5
elif product_weight >= 10 and product_weight < 25:
   ship_rate = 1.45
else:
ship_rate = 1.4

total = product_weight * ship_rate

print("")
print(product_name, "weight in pounds  ", format 
(product_weight, '9,.2f'))
print ("Your total to ship", product_name, "is:  $", format 
(total, '9,.2f'))



main ()




On Sun, Oct 20, 2013 at 6:01 PM, Ricardo Aráoz > wrote:


Sorry, I sent this answer to the OP directly and not to the list.

 Mensaje original 
Asunto: Re: [Tutor] Passing arguments?
Fecha:  Sun, 20 Oct 2013 11:25:52 -0300
De: Ricardo Aráoz  
A:  Jenny Allar  



El 20/10/13 01:20, Jenny Allar escribió:

I've written the code below the assignment, and I think I have
everything covered in terms of asking the user for the
information I need and somehow calculating costs, but I'm just
ridiculously confused on the order and placement of the functions
and components of this program- specifically the shiprate
variable. Thank you in advance for any help.



Ok, just a couple of things first.

- Your assignment specifically says 'always use "while loops" to
validate' but I see no loop at all in your code. You might want to
look into it.

- What your assignment points to when it says to use "while
loops" is that you should validate that what the user inputs is a
valid number. If the user will input something else than a number
as the weight then when you apply the int() function an exception
will be flagged and your program will terminate ungracefully. You
may validate input using "exceptions" and "while loops" (look it up).

- Your functions should do what their name imply, and preferably
do only one thing. Having a function named calc_weight_large()
that also prints the shipping cost is not good.

- Your if asks for >= 10 and your elif for <= 10 when the "= 10"
case was already handled by the first if, that is a mistake.
Besides which it might be better looking (though this is a matter
of personal preference) if you ::
if weight > 25
# do something
elif weight > 10
# do something else
else
# do something entirely different

- I would structure the program in the following way ::
def main():
product = in_product()
weight = in_weight()

if weight > 25
total = calc_shipping(1.40, weight)
elif weight > 10
total = calc_shipping(1.45, weight)
else
total = calc_shipping(1.50, weight)
print_data(product, weight, total)


This is my assignment:

Write a program that asks a user for the name of a product that
they are ordering online and its weight.  The program must
calculate the cost of shipping the product using the following
cost structure.  If it weighs less than 10 pounds the cost is
$1.50 per pound, if it is 10 pounds or more and less than 25
pounds then the cost is $1.45 per pound.  If the weight is 25
pounds or more the cost is $1.40 per pound.  You may get the data
from the user in main.  You must print the name of the product,
the weight and the cost of shipping in a separate function.

*_*

Re: [Tutor] [OT] Programming practice was: Re: string list in alphabetical!

2013-10-22 Thread Alan Gauld

On 22/10/13 13:42, Sydney Shall wrote:


trying to get him to adopt a workflow where he writes on paper
an informal "use case" description of the solution and if
necessary a pseudo code design.



Could you please explain exactly what you mean by 'an informal "use
case" description of the solution ..'?
I am not clear how this differs from pseudo code design.


OK, a use case is a requirements capture technique frequently used by 
software engineers to capture the behaviour of systems from the users 
perspective. There are whole books written on this stuff so for my 
student I've greatly simplified the technique.


A normal use case is written like a dialog between the
user and system, like so:

1)User starts system
2)System presents login screen
3)User enters name and password
4)System presents main screen
5)User Select File->New
6)System presents list of templates
7)User selects New Blodgit
8)System resents blodgit config screen
...

And so on.

It doesn't say anything about how the system will do these
things but it presents a visualisation of how the system
should present itself and interact wit the user.

In the industrialised version we would also list alternate
steps after the "happy path" case has been described such as

4a) System displays error message and login scren
4b) User logs in with correct data
4c) continue at 4

I haven't tried that aspect with my student yet.

Once you have the interaction clear you can look at each
step the computer does and design it in pseudo code.

Search wikipedia for lots more on use cases and their
finer points.

--
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] Fwd: Re: Passing arguments?

2013-10-22 Thread Alan Gauld

On 22/10/13 14:21, Ricardo Aráoz wrote:

- Did you notice your assignment specifically asks for a "while" loop
for validation? ... (tip: you should be using "while" and "on
error")


on error?
You're not thinking of VB by any chance? :-)

In Python it would be a try/except block or maybe a straight if/else 
test for a beginner.


--
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] Fwd: Re: Passing arguments?

2013-10-22 Thread Ricardo Aráoz

El 22/10/13 10:44, Alan Gauld escribió:

On 22/10/13 14:21, Ricardo Aráoz wrote:

- Did you notice your assignment specifically asks for a "while" loop
for validation? ... (tip: you should be using "while" and "on
error")


on error?
You're not thinking of VB by any chance? :-)

In Python it would be a try/except block or maybe a straight if/else 
test for a beginner.




LOL and blush.
Sorry, meant try/except (I was thinking VFP).
Wouldn't if/else be more difficult when validating if an input is a 
valid float? I find try/except easier.


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


Re: [Tutor] Fwd: Re: Passing arguments?

2013-10-22 Thread Mark Lawrence

On 22/10/2013 03:23, Jenny Allar wrote:

Plenty of sound advice as always so I'll just point out that...


 elif product_weight >= 10 and product_weight < 25:


can be written as

elif 10 <= product_weight < 25:

--
Python is the second best programming language in the world.
But the best has yet to be invented.  Christian Tismer

Mark Lawrence

___
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] Fwd: Re: Passing arguments?

2013-10-22 Thread Alan Gauld

On 22/10/13 14:55, Ricardo Aráoz wrote:


Sorry, meant try/except (I was thinking VFP).
Wouldn't if/else be more difficult when validating if an input is a
valid float? I find try/except easier.


Maybe, but typical programming classes don't teach try/except
till much later in the course.

Since the OP is evidently a very new beginner I doubt if
they've covered it yet...


--
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 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 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.
>
> 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


[Tutor] comma in an assignment

2013-10-22 Thread Key, Gregory E (E S SF RNA FSF 1 C)
I understand that a comma in Python is a separator and not an operator. In some 
of the MatPlotLib examples I see code like this:

line1, = ax1.plot(t, y1, lw=2, color='red', label='1 HZ')

What does the comma do in an assignment statement?

Greg Key


This message and any attachments are solely for the use of intended recipients. 
The information contained herein may include trade secrets, protected health or 
personal information, privileged or otherwise confidential information. 
Unauthorized review, forwarding, printing, copying, distributing, or using such 
information is strictly prohibited and may be unlawful. If you are not an 
intended recipient, you are hereby notified that you received this email in 
error, and that any review, dissemination, distribution or copying of this 
email and any attachment is strictly prohibited. If you have received this 
email in error, please contact the sender and delete the message and any 
attachment from your system. Thank you for your cooperation
___
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 

> 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


[Tutor] Howto handle pictures with pyqt

2013-10-22 Thread Ulrich Goebel

Hello,

for my first python program I try to build a user interface for a litle 
address database. Therefor I use pyqt to build the formular, and later I 
will connect it to an existing SQLite DB, using APSW.


Besides the "normal" things as name, address, email and others I want to 
store an image. Normaly that will be given as a file (.jpg, .png, or 
other type). I would let the user find the picture with a 
QFileDialog.getOpenFileName() dialog. But what to do after that? Here 
are my questions:


Which widget is able to show the picture?

How to show the picture? That means: howto put the picture from the file 
into the widget?


How to put the picture data into an blob(?) column in the database?

How to get the data back from there and bring it in the widget?

May be there is a tutorial which I didn't find yet?

Thank's a lot for any help!

Greetings
Ulrich

--
Ulrich Goebel
Paracelsusstr. 120, 53177 Bonn
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] comma in an assignment

2013-10-22 Thread Alan Gauld

On 22/10/13 20:20, Key, Gregory E (E S SF RNA FSF 1 C) wrote:

I understand that a comma in Python is a separator and not an operator.
In some of the MatPlotLib examples I see code like this:
line1, = ax1.plot(t, y1, lw=2, color='red', label='1 HZ')
What does the comma do in an assignment statement?


Caveat: I know nothing about MatPlotLib...

But a comma after a name like that usually means its part of a
tuple (a single element tuple) so you could rewrite it like:

(line1,) = ax1.plot(t, y1, lw=2, color='red', label='1 HZ')

But I've no idea why you'd want to do that or why MatPlotLib
apparently does. Maybe someone who uses MatPlotLib will reveal
all...

A wee bit of experimenting suggests ou can use it to unpack
a single valued tuple. So presumably ax1.plot() returns a
single value tuple. Without the comma line1 would also be
a tuple but with the comma it takes on the value inside
instead...

--
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 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] Howto handle pictures with pyqt

2013-10-22 Thread Alan Gauld

On 22/10/13 22:21, Ulrich Goebel wrote:


for my first python program I try to build a user interface for a litle
address database. Therefor I use pyqt to build the formular, and later I
will connect it to an existing SQLite DB, using APSW.


This list is for beginners to the python language and standard library.
Your question is mainly about Qt so will likely get a better response on 
a Qt or pyQt list/forum.


However, I know some readers here do use Qt so you may be in luck...


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


[Tutor] How to Terminate a Popen call?

2013-10-22 Thread SM
Hello!
I am trying to terminate a Popen session using Popen.terminate() ( using
the info at http://docs.python.org/library/subprocess.html and some
relevant answers from Stack Overflow). But it doesn't seem to work for me.

I am calling Popen to run a command (which runs for a long time) from one
thread (thread1) and trying to stop the execution from another thread
(thread2) which is running in a loop. In response to a pushButton, the
second thread (thread2) invokes the stop method of the first thread which
in turn, invokes the terminate() call.
Here is the code snippet:

class thread1(threading.Thread):
def __init__(self, ):
...
...
super(bcThread_allrep_all, self).__init__()
self.stoprequest = threading.Event()
self.process = None


def stopped(self):
return self.stoprequest.isSet()

def run(self):
(process, err) = Popen(self.fwcmd, stdout=PIPE,
stderr=PIPE).communicate()if len(err) >  0:
# print("Error")
# Error handling code
else:
# print("Success")

def stop(self):
if self.process is not None:
print("TERMINATING THREAD")
self.process.terminate()
#Popen.terminate(self.process)
else:
print("process IS NONE ")


>From thread2 I am invoking thread1.stop() method, in order to terminate
the Popen call. So thread1.stop() is getting invoked, but I see that
self.process (which is the value Popen has to return) will have "None"
before it finishes.

The python.org document suggests to use Popen.terminate() call.
So I also tried calling Popen.terminate (as in the commented line above),
but it returns the following error (due to the same reason that
self.process is None):

  File "bc_reports_tab.py", line 1733, in stop
Popen.terminate(self.process)
  File "/usr/lib/python3.2/subprocess.py", line 1581, in terminate
self.send_signal(signal.SIGTERM)
  AttributeError: 'NoneType' object has no attribute 'send_signal'

So how would I terminate Popen before it has finished executing??

Appreciate any help.
Thanks!
-Sm
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] comma in an assignment

2013-10-22 Thread eryksun
On Tue, Oct 22, 2013 at 3:20 PM, Key, Gregory E (E S SF RNA FSF 1 C)
 wrote:
> I understand that a comma in Python is a separator and not an operator. In

The comma operator creates a tuple. It has low precedence, so you
usually need parentheses. But sometimes the parentheses are redundant
such as with a return statement like `return (x, y, z)` vs `return x,
y, z`, or on the right-hand side of an assignment:

>>> y = 1, 2, 3
>>> y
(1, 2, 3)


> some of the MatPlotLib examples I see code like this:
>
> line1, = ax1.plot(t, y1, lw=2, color='red', label='1 HZ')
>
> What does the comma do in an assignment statement?

For an assignment target list, CPython doesn't actually create a
tuple. It's a notational tuple used by the compiler. It's present in
the abstract syntax tree (creating an AST is an intermediate step in
the compilation process); however, the final bytecode does sequence
unpacking directly to the target names. Here's the AST for `y, = x`:

>>> print ast.dump(ast.parse('y, = x').body[0])
Assign(targets=[Tuple(elts=[Name(id='y', ctx=Store())], ctx=Store())],
value=Name(id='x', ctx=Load()))

The AST Tuple in the assignment consists of one item, a Name with a
Store context. In this case, the compiler generates bytecode to unpack
a length 1 sequence and store the item to the name "y".

In practice this is pretty simple and intuitive:

>>> y, = [1]
>>> y
1

>>> x, y, z = 1, 2, 3
>>> x, y, z
(1, 2, 3)

You can use compile() and dis to see the bytecode itself:

>>> dis.dis(compile('y, = x', '', 'exec'))
  1   0 LOAD_NAME0 (x)
  3 UNPACK_SEQUENCE  1
  6 STORE_NAME   1 (y)
  9 LOAD_CONST   0 (None)
 12 RETURN_VALUE

The argument in UNPACK_SEQUENCE(1) is the number of items to unpack to
the frame's stack. For stack-based operations, think of using an RPN
calculator. An operator -- in this case a bytecode instruction -- pops
its operands off the stack and then pushes the result back on in their
place. The more complex the expression, the bigger the stack needs to
grow (think of a stack of plates) in order to hold temporary results.

Unpacking can also handle more complex structures such as `t, (x, y) = z`:

>>> z = [1, [2, 3]]
>>> t, (x, y) = z
>>> t, x, y
(1, 2, 3)

If you prefer, you can use square brackets on the left-hand side. The
compiled bytecode is the same, whether the left-hand side has Tuple or
List types in the AST:

>>> [t, [x, y]] = z
>>> t, x, y
(1, 2, 3)

Bytecode comparison:

>>> dis.dis(compile('t, (x, y) = z', '', 'exec'))
  1   0 LOAD_NAME0 (z)
  3 UNPACK_SEQUENCE  2
  6 STORE_NAME   1 (t)
  9 UNPACK_SEQUENCE  2
 12 STORE_NAME   2 (x)
 15 STORE_NAME   3 (y)
 18 LOAD_CONST   0 (None)
 21 RETURN_VALUE

>>> dis.dis(compile('[t, [x, y]] = z', '', 'exec'))
  1   0 LOAD_NAME0 (z)
  3 UNPACK_SEQUENCE  2
  6 STORE_NAME   1 (t)
  9 UNPACK_SEQUENCE  2
 12 STORE_NAME   2 (x)
 15 STORE_NAME   3 (y)
 18 LOAD_CONST   0 (None)
 21 RETURN_VALUE

After the first unpack, item 0 is popped off the stack and stored to
t. Next item 1 (a length 2 sequence) is popped, unpacked, and stored
to x and y.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] comma in an assignment

2013-10-22 Thread Steven D'Aprano
On Tue, Oct 22, 2013 at 07:20:25PM +, Key, Gregory E (E S SF RNA FSF 1 C) 
wrote:

> I understand that a comma in Python is a separator and not an 
> operator. In some of the MatPlotLib examples I see code like this:
> 
> line1, = ax1.plot(t, y1, lw=2, color='red', label='1 HZ')
> 
> What does the comma do in an assignment statement?

It does "sequence unpacking".

On the right hand side, commas create a tuple:

py> x = 100, 200, 300
py> print(x, type(x))
(100, 200, 300) 


On the left hand side, you can think of it as if it creates a tuple of 
names, then assigns to each name with the corresponding item from the 
other side:

py> a, b, c = 100, 200, 300
py> print(a, b, c)
100 200 300

So this example is conceptually like:

# make a tuple of names
(a, b, c)
# line them up with a sequence on the right hand side
(a, b, c) = (100, 200, 300)
# unpack the sequence on the right and assign item-by-item
a <-- item 0 = 100
b <-- item 1 = 200
c <-- item 2 = 300


So a single comma on the left, like this:

a, = function(args, more_args)

is equivalent to this:

temp <-- function(args, more_args)
a<-- temp[0]
delete temp

except of course the name "temp" isn't literally used.

The values on the right don't have to be a tuple, any sequence will do, 
such as strings, lists, or iterators:

py> a, b, c = "XYZ"
py> print(a, b, c)
X Y Z

However, there does have to be the same number of items on both sides:

py> a, b, c = "xy"
Traceback (most recent call last):
  File "", line 1, in 
ValueError: need more than 2 values to unpack


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


Re: [Tutor] How to Terminate a Popen call?

2013-10-22 Thread eryksun
On Tue, Oct 22, 2013 at 9:04 PM, SM  wrote:
> def run(self):
> (process, err) = Popen(self.fwcmd, stdout=PIPE,
> stderr=PIPE).communicate()
> if len(err) >  0:
> # print("Error")
> # Error handling code
> else:
> # print("Success")

Store the Popen() instance before calling its communicate() method:

p = self.process = Popen(self.fwcmd, stdout=PIPE, stderr=PIPE)
out, err = p.communicate()
if p.returncode:
raise CalledProcessError(p.returncode, self.fwcmd, (out, err))

communicate() sets returncode; an error is indicated by a non-zero
value. Some programs write non-error information to stderr, so use the
return code to detect an error.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] comma in an assignment

2013-10-22 Thread eryksun
On Tue, Oct 22, 2013 at 9:50 PM, Steven D'Aprano  wrote:
> However, there does have to be the same number of items on both sides:
>
> py> a, b, c = "xy"
> Traceback (most recent call last):
>   File "", line 1, in 
> ValueError: need more than 2 values to unpack

3.x extends sequence unpacking to support starred expressions:

>>> a, b, *c = 'xy'
>>> a, b, c
('x', 'y', [])

>>> a, b, *c = 'xyz'
>>> a, b, c
('x', 'y', ['z'])

>>> a, b, c, *rest = 'xyzpdq'
>>> a, b, c, rest
('x', 'y', 'z', ['p', 'd', 'q'])

http://www.python.org/dev/peps/pep-3132
___
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 = D