Hello and welcome to CertForums.co.uk, here we host free active certification forums with links to the best free resources for Microsoft's MCSA MCSE MCDBA Cisco's CCNA CCDA and CCNP, and CompTIA's A+ Network+ i-NET+ and Security+ certifications in the UK. If you wish to post or use other advanced features you will need to register first. Registration is absolutely free and takes only a few minutes to complete so sign up today!

If you have any problems with the registration process or your account login, please contact support

Go Back   CertForums > Computing Support Forums > Programming & Scripting
Home Forums Register Search Today's Posts Mark Forums Read

A problem with functions in Python

Post New ThreadReply
 
Thread Tools Display Modes
  #1  
Old 11-Mar-2008, 11:41 PM
tripwire45's Avatar
tripwire45 tripwire45 is offline
Administrator
Posts: 13,466
Points: 4044 tripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 points
Power: 184
None
Join Date: 29 Jun 2003
Location: Boise, ID, USA
Certifications: A+ and Network+
A problem with functions in Python

I had to cheat to complete an assignment in my Python homework (this is from a PDF called Non-Programmers Tutorial For Python by Josh Cogliati). Basically, the instructions are to write a program that defines separate functions to calculate the area of a square, the area of a rectangle, and the area of a circle. The other requirement is that the program present the user with a menu. I imposed another requirement that one of the options should be a "quit" option.

Unfortunately, I couldn't figure it out using the materials presented in this tutorial. I started to search the web for clues to fill in the gaps and stumbled upon enough to let me fill (sort of) the requirements, but not really defining separate functions for the calculations of those areas. Also, because it was what I found, I actually created a program that offers the user the option of calculating the area of a rectangle, circle, or triangle. I did successfully include a "quit" option.

All that said, my sample code is presented below, but I feel defeated because I didn't actually solve the problem in the manner required. Any clues as to how to re-write this to be more in line with the stated requirements?

Code:
def print_options():
    print "Please choose an option:"
    print "======================"
    print " 'P'  Print Options"
    print " 'R'  Rectangle"
    print " 'C'  Circle"
    print " 'T'  Triangle"
    print " 'Q'  Quit"
    print "======================"

option = "P"

while option != "Q":

    if option == "R":
        height = input("Please input the height:")
        width = input("Please enter the width:")
        area = height*width
        print "The area is:", area
        
    elif option == "C":
        radius = input("Please enter the radius:")
        area = 3.14*(radius**2)
        print "The area is:", area
        
    elif option == "T":
        base = input("Please enter the base:")
        height = input("Please enter the height:")
        area = .5*height*base
        print "The area is:", area

    elif option != "Q":
        print_options()
    option = raw_input("Please choose an option:")


You know, I wish my parents played Mozart when I slept because half the time I don't even know what the heck anyone's talking about!
 
Reply With Quote
  #2  
Old 12-Mar-2008, 01:28 AM
Mathematix's Avatar
Mathematix Mathematix is offline
Longterm Member
Posts: 834
Points: 1124 Mathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 points
Power: 24
None
Join Date: 09 Mar 2006
Location: London
Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
WIP: Not doing certs. Computer geek.
You're new to programming so the feeling of defeat is natural and common. All you needed to do was give yourself time to research Python. Anyway, about your code. Given that the requirements for your program are not complicated in the first place, this wasn't a bad attempt - but I would have packaged the calculations in their own individual functions. I've also left the code uncommented so that you can research what's going on.

Code:
import os

valid_options = ['p','r','c','t','q']

def print_options():
    print "Main menu"
    print "======================"
    print " 'P'  Print Options"
    print " 'R'  Rectangle"
    print " 'C'  Circle"
    print " 'T'  Triangle"
    print " 'Q'  Quit"
    print "======================"

def calc_area():

    height = input("Please input the height: ")
    width = input("Please enter the width: ")
    area = height*width
    print "The area is: ", area

def calc_radius():
    
    radius = input("Please enter the radius: ")
    area = 3.14*(radius**2)
    print "The area is: ", area
    
def calc_base_height():
    
    base = input("Please enter the base: ")
    height = input("Please enter the height: ")
    area = .5*height*base
    print "The area is: ", area

def run():
    
    global valid_options
    
    option = ""

    while True:
        print_options()
        
        if option.lower() not in valid_options:
            option = raw_input("Please choose an option:")

        if option.lower() == "r":
            calc_area()
            option = ""
            continue

        if option.lower() == "c":
            calc_radius()
            option = ""
            continue

        if option.lower() == "t":
            calc_base_height()
            option = ""
            continue

        if option.lower() == "p":
            option = ""
            continue

        if option.lower() == "q":
            break
    
if __name__ == '__main__':
    run()


 
Reply With Quote
  #3  
Old 12-Mar-2008, 02:29 AM
tripwire45's Avatar
tripwire45 tripwire45 is offline
Administrator
Posts: 13,466
Points: 4044 tripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 points
Power: 184
None
Join Date: 29 Jun 2003
Location: Boise, ID, USA
Certifications: A+ and Network+
Quote:
Originally Posted by Mathematix View Post
You're new to programming so the feeling of defeat is natural and common. All you needed to do was give yourself time to research Python.
I didn't mean I felt *permanently* defeated. Just defeated for the day. The raging headache sitting just below the back of my skull isn't helping much.
Quote:
Originally Posted by Mathematix View Post
Anyway, about your code. Given that the requirements for your program are not complicated in the first place, this wasn't a bad attempt - but I would have packaged the calculations in their own individual functions. I've also left the code uncommented so that you can research what's going on.
Exactly what I was looking for. Funny how I can recognize it when I see it but still have difficulty imagining it well enough to actually write it.

There are some things that I still need to figure out about what you wrote (which is why you didn't include comments), so this'll keep me busy for a bit. Thanks.


You know, I wish my parents played Mozart when I slept because half the time I don't even know what the heck anyone's talking about!
 
Reply With Quote
  #4  
Old 12-Mar-2008, 10:51 AM
Mathematix's Avatar
Mathematix Mathematix is offline
Longterm Member
Posts: 834
Points: 1124 Mathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 points
Power: 24
None
Join Date: 09 Mar 2006
Location: London
Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
WIP: Not doing certs. Computer geek.
No problem, mate.


 
Reply With Quote
  #5  
Old 12-Mar-2008, 02:38 PM
BosonJosh's Avatar
BosonJosh BosonJosh is offline
Valued Member
Posts: 392
Points: 550 BosonJosh has over 500 pointsBosonJosh has over 500 pointsBosonJosh has over 500 pointsBosonJosh has over 500 pointsBosonJosh has over 500 pointsBosonJosh has over 500 points
Power: 11
None
Join Date: 01 Aug 2007
Location: Near Nashville
Good stuff, Mathematix! I've programmed in .NET before, but not Python. All this talk about Python has got me interested in looking into it.


Water is just coffee in waiting.
 
Reply With Quote
  #6  
Old 12-Mar-2008, 02:56 PM
Mathematix's Avatar
Mathematix Mathematix is offline
Longterm Member
Posts: 834
Points: 1124 Mathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 points
Power: 24
None
Join Date: 09 Mar 2006
Location: London
Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
WIP: Not doing certs. Computer geek.
Cheers, BosonJosh!

I didn't like Python at first, but now it's starting to win me over as both a very good teaching language and for powerful tool creation. This is my nineth month coding in it so far, and it's so handy when you want to knock-up something quick!

Nothing will take me away from my > 12 years of C++ though. ;)


 
Reply With Quote
  #7  
Old 12-Mar-2008, 05:33 PM
ffreeloader's Avatar
ffreeloader ffreeloader is offline
Lifetime Member
Posts: 3,657
Points: 3046 ffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 points
Power: 72
None
Join Date: 26 Jul 2005
Location: USA
Age: 55
Certifications: MCSE, MCDBA, CCNA, A+
WIP: LPIC 1
Quote:
Originally Posted by Mathematix View Post
Cheers, BosonJosh!

I didn't like Python at first, but now it's starting to win me over as both a very good teaching language and for powerful tool creation. This is my nineth month coding in it so far, and it's so handy when you want to knock-up something quick!

Nothing will take me away from my > 12 years of C++ though. ;)
I'm no developer, but I've been playing with Python on and off for a year or two. I don't use it often enough so that I'm always having to go back and relearn things, but I have to say it's probably the easiest to learn to use of any language I've played with, and it is incredibly powerful. I'm pretty much a believer in Python.

I just bought a wonderful book on it a while back. It's called "Object-Oriented Programming in Python". I started reading it, got pulled away by things at work, but I have to say that from the chapter or two I've read so far it's by far the best book on OO Python I've come across, and I have several Python books. It's expensive, but it was released as a means of teaching computer science using Python so it's priced as a textbook, not a technical book.

I subscribe to a Python newbie mailing list, and this book is getting rave reviews from those who have spent the money to buy it. It's been panned by those who won't buy it because it's so expensive, but I've always wondered how you can pan a book you've never read.

Here's a link to it. http://www.amazon.com/Object-Oriente...5342857&sr=8-1



Behold, the turtle. He makes progress only when he sticks his neck out.

James Bryant Conant
 
Reply With Quote
  #8  
Old 12-Mar-2008, 06:51 PM
BosonJosh's Avatar
BosonJosh BosonJosh is offline
Valued Member
Posts: 392
Points: 550 BosonJosh has over 500 pointsBosonJosh has over 500 pointsBosonJosh has over 500 pointsBosonJosh has over 500 pointsBosonJosh has over 500 pointsBosonJosh has over 500 points
Power: 11
None
Join Date: 01 Aug 2007
Location: Near Nashville
Yikes, that is an expensive book. However, a good training book is priceless, so if it's as good as you say, then it may be worth it.


Water is just coffee in waiting.
 
Reply With Quote
  #9  
Old 12-Mar-2008, 08:48 PM
Mathematix's Avatar
Mathematix Mathematix is offline
Longterm Member
Posts: 834
Points: 1124 Mathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 points
Power: 24
None
Join Date: 09 Mar 2006
Location: London
Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
WIP: Not doing certs. Computer geek.
Quote:
Originally Posted by ffreeloader View Post
I'm no developer, but I've been playing with Python on and off for a year or two. I don't use it often enough so that I'm always having to go back and relearn things, but I have to say it's probably the easiest to learn to use of any language I've played with, and it is incredibly powerful. I'm pretty much a believer in Python.

I just bought a wonderful book on it a while back. It's called "Object-Oriented Programming in Python". I started reading it, got pulled away by things at work, but I have to say that from the chapter or two I've read so far it's by far the best book on OO Python I've come across, and I have several Python books. It's expensive, but it was released as a means of teaching computer science using Python so it's priced as a textbook, not a technical book.

I subscribe to a Python newbie mailing list, and this book is getting rave reviews from those who have spent the money to buy it. It's been panned by those who won't buy it because it's so expensive, but I've always wondered how you can pan a book you've never read.

Here's a link to it. http://www.amazon.com/Object-Oriente...5342857&sr=8-1
Wow! very pricey book. Has me thinking, though. If Python is one of the easiest languages to learn out there, why does this book cost more than others for tougher languages? There are a number of good Python books out there like this one that I learned from, also with a 5-star rating, and I think that's an accurate rating!



Last edited by Mathematix : 12-Mar-2008 at 08:50 PM.
 
Reply With Quote
  #10  
Old 12-Mar-2008, 10:57 PM
tripwire45's Avatar
tripwire45 tripwire45 is offline
Administrator
Posts: 13,466
Points: 4044 tripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 points
Power: 184
None
Join Date: 29 Jun 2003
Location: Boise, ID, USA
Certifications: A+ and Network+
Yowza, Freddy! It really is pricey. Nevertheless, it's been added to my "wish list". Once I get through my uber-newbie Python lessons, I'll probably tackle O'Reilly's Learning Python next.


You know, I wish my parents played Mozart when I slept because half the time I don't even know what the heck anyone's talking about!
 
Reply With Quote
  #11  
Old 13-Mar-2008, 01:35 AM
ffreeloader's Avatar
ffreeloader ffreeloader is offline
Lifetime Member
Posts: 3,657
Points: 3046 ffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 points
Power: 72
None
Join Date: 26 Jul 2005
Location: USA
Age: 55
Certifications: MCSE, MCDBA, CCNA, A+
WIP: LPIC 1
Quote:
Originally Posted by Mathematix View Post
Wow! very pricey book. Has me thinking, though. If Python is one of the easiest languages to learn out there, why does this book cost more than others for tougher languages? There are a number of good Python books out there like this one that I learned from, also with a 5-star rating, and I think that's an accurate rating!
I'm pretty sure, and reading Python mailing list messages by the author reinforces my thoughts, is that the textbook aspect of it where the price comes from. Any publisher who puts the "textbook" stamp on a book pretty much does the same thing that a bolt manufacturer does when they put the "marine" or "aircraft" stamp on a product. The designation alone ups the price.

The other thing I've found is that most of the other books on Python don't cover OO in depth. It's more of an afterthought. I have Learning Python, Python Programming: an Introduction to Computer Science, Programming Python, and one more I can't recall off the top of my head, and the OO part of Python is very lightly touched on. What's more they get very little into how to develop software programs with Python. Yeah, they cover the syntax, but give very little information on how to use OO Python to accomplish different tasks. This book starts right off the top with how to work with the OO aspects of Python.

IMO, it's kind of a "horse of another color" as far as Python books go.



Behold, the turtle. He makes progress only when he sticks his neck out.

James Bryant Conant
 
Reply With Quote
  #12  
Old 13-Mar-2008, 01:36 PM
Mathematix's Avatar
Mathematix Mathematix is offline
Longterm Member
Posts: 834
Points: 1124 Mathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 points
Power: 24
None
Join Date: 09 Mar 2006
Location: London
Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
WIP: Not doing certs. Computer geek.
Quote:
Originally Posted by ffreeloader View Post
I'm pretty sure, and reading Python mailing list messages by the author reinforces my thoughts, is that the textbook aspect of it where the price comes from. Any publisher who puts the "textbook" stamp on a book pretty much does the same thing that a bolt manufacturer does when they put the "marine" or "aircraft" stamp on a product. The designation alone ups the price.

The other thing I've found is that most of the other books on Python don't cover OO in depth. It's more of an afterthought. I have Learning Python, Python Programming: an Introduction to Computer Science, Programming Python, and one more I can't recall off the top of my head, and the OO part of Python is very lightly touched on. What's more they get very little into how to develop software programs with Python. Yeah, they cover the syntax, but give very little information on how to use OO Python to accomplish different tasks. This book starts right off the top with how to work with the OO aspects of Python.

IMO, it's kind of a "horse of another color" as far as Python books go.
Well, strictly speaking OO is an entire subject in its own right and should be covered in its own context rather than that of a programming language. This brings several issues to the fore:

1. The reason why books like those for Python only appear to 'touch' on OOP is because it describes those aspects of OOP relevant to Python. Now, seeing that Python is a very high-level language (it hides low-level functionality from the developer managing resources and data structures internally), there should be no need for a book to described those aspects of OOP that the Python programmer will never have to use.

2. The lower the level of laguage you code in, the more prevelant the issues associated with OOP become. For example we can have the so-called 'Diamond of Death' in multiple inheritence in C++ whereby multiple objects inheriting from a common base class can has undefined results when an object in the parent class is updated. I believe that this is not a problem in Python and therefore doesn't need to be covered in the book material.

OO is a great field deserved of its own study. Clumping a detailed study of it in a book that also discusses a language that doesn't require such detailed coverage of the topic only serves to confuse the reader as to what is relevant between OO and Python.

Or maybe I'm just missing something.


 
Reply With Quote
  #13  
Old 13-Mar-2008, 04:10 PM
ffreeloader's Avatar
ffreeloader ffreeloader is offline
Lifetime Member
Posts: 3,657
Points: 3046 ffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 pointsffreeloader has over 3000 points
Power: 72
None
Join Date: 26 Jul 2005
Location: USA
Age: 55
Certifications: MCSE, MCDBA, CCNA, A+
WIP: LPIC 1
Quote:
Originally Posted by Mathematix View Post
Well, strictly speaking OO is an entire subject in its own right and should be covered in its own context rather than that of a programming language. This brings several issues to the fore:

1. The reason why books like those for Python only appear to 'touch' on OOP is because it describes those aspects of OOP relevant to Python. Now, seeing that Python is a very high-level language (it hides low-level functionality from the developer managing resources and data structures internally), there should be no need for a book to described those aspects of OOP that the Python programmer will never have to use.

2. The lower the level of laguage you code in, the more prevelant the issues associated with OOP become. For example we can have the so-called 'Diamond of Death' in multiple inheritence in C++ whereby multiple objects inheriting from a common base class can has undefined results when an object in the parent class is updated. I believe that this is not a problem in Python and therefore doesn't need to be covered in the book material.

OO is a great field deserved of its own study. Clumping a detailed study of it in a book that also discusses a language that doesn't require such detailed coverage of the topic only serves to confuse the reader as to what is relevant between OO and Python.

Or maybe I'm just missing something.
Methinks so. I probably just don't do "developer speak" well enough to explain to you what I mean.

To me, what you're saying is that teaching how to do OO programming in Python is a no-no because it is something that no one needs to know. I guess I don't quite follow, but that's fine. I have learned a lot from the book in the couple of chapters that I've studied. I've found the book expands my knowledge of both Python and how to solve problems using Python. To me that's the bottom line for any book. If I find a book useful to me, then it's a "good" book, and this one qualifies for that rating from me.



Behold, the turtle. He makes progress only when he sticks his neck out.

James Bryant Conant
 
Reply With Quote
  #14  
Old 13-Mar-2008, 05:42 PM
mgoldwasser mgoldwasser is offline
Posts: 6
Points: 89 mgoldwasser has between 1 & 100 points
Power: 2
None
Join Date: 13 Mar 2008
Quote:
Originally Posted by Mathematix View Post
Well, strictly speaking OO is an entire subject in its own right and should be covered in its own context rather than that of a programming language. This brings several issues to the fore:

1. The reason why books like those for Python only appear to 'touch' on OOP is because it describes those aspects of OOP relevant to Python. Now, seeing that Python is a very high-level language (it hides low-level functionality from the developer managing resources and data structures internally), there should be no need for a book to described those aspects of OOP that the Python programmer will never have to use.

2. The lower the level of laguage you code in, the more prevelant the issues associated with OOP become. For example we can have the so-called 'Diamond of Death' in multiple inheritence in C++ whereby multiple objects inheriting from a common base class can has undefined results when an object in the parent class is updated. I believe that this is not a problem in Python and therefore doesn't need to be covered in the book material.

OO is a great field deserved of its own study. Clumping a detailed study of it in a book that also discusses a language that doesn't require such detailed coverage of the topic only serves to confuse the reader as to what is relevant between OO and Python.

Or maybe I'm just missing something.
I'll jump into the conversation for a moment, acknowledging that I'm one of the authors of the book mentioned in this thread.

I don't understand your premise that OO is an entirely different subject than a programming language, and that they should be learned separately. You seem to be focussing on advanced and esoteric issues such as diamond patterns with multiple inheritance. Certainly that is not a topic that you would introduce to a beginner.

At its heart, our book is designed to teach beginners how to program. We've chosen to use Python as an instructive language and we've chosen to do so with the acknowledgment that Python is at its heart a very object-oriented language. That doesn't mean that we need to introduce advanced OO issues that may not be relevant to beginning Python programmers. But we do want beginners to understand that all of the data that they deal with (e.g., lists, strings, numbers) are objects that can be manipulated in various ways. This viewpoint can be very helpful in smoothing the transition to users developing their own classes.

 
Reply With Quote
  #15  
Old<