1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

A problem with functions in Python

Discussion in 'Scripting & Programming' started by tripwire45, Mar 11, 2008.

  1. tripwire45
    Honorary Member

    tripwire45 Zettabyte Poster

    13,493
    179
    287
    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:")  
     
    Certifications: A+ and Network+
  2. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    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()
    
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  3. tripwire45
    Honorary Member

    tripwire45 Zettabyte Poster

    13,493
    179
    287
    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.
    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. :oops:

    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.
     
    Certifications: A+ and Network+
  4. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    No problem, mate. :)
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  5. BosonJosh

    BosonJosh Gigabyte Poster

    1,326
    28
    89
    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.
     
  6. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    Cheers, BosonJosh! :biggrin

    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. ;)
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  7. ffreeloader

    ffreeloader Terabyte Poster

    3,661
    106
    167
    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-Orient...bs_sr_1?ie=UTF8&s=books&qid=1205342857&sr=8-1
     
    Certifications: MCSE, MCDBA, CCNA, A+
    WIP: LPIC 1
  8. BosonJosh

    BosonJosh Gigabyte Poster

    1,326
    28
    89
    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.
     
  9. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    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! :biggrin
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  10. tripwire45
    Honorary Member

    tripwire45 Zettabyte Poster

    13,493
    179
    287
    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.
     
    Certifications: A+ and Network+
  11. ffreeloader

    ffreeloader Terabyte Poster

    3,661
    106
    167
    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.
     
    Certifications: MCSE, MCDBA, CCNA, A+
    WIP: LPIC 1
  12. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    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. :biggrin
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  13. ffreeloader

    ffreeloader Terabyte Poster

    3,661
    106
    167
    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.
     
    Certifications: MCSE, MCDBA, CCNA, A+
    WIP: LPIC 1
  14. mgoldwasser

    mgoldwasser New Member

    6
    2
    2
    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.
     
  15. ffreeloader

    ffreeloader Terabyte Poster

    3,661
    106
    167
    Very well stated. I could not have said what you did the same way, but that is exactly what your book does for me. I haven't gotten very far into it yet due to other issues at work, but it has opened my eyes a lot in how to use Python to solve problems. It addresses exactly what I have found to be my main problem in using any scripting or programming language: how to go about solving problems.

    The book is expensive, but I think it's worth its weight in gold even with the little I've read, so it's a good value.
     
    Certifications: MCSE, MCDBA, CCNA, A+
    WIP: LPIC 1
  16. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    Welcome to the thread! :biggrin

    Because OO is a subject in itself that does not only exist within the realms of Python or 'just' any other programming language. The reason why I hinted towards more advanced topics in OO was to convey to the reader the broader aspect of the topic. There are a multitude of books out there specifically addressing OO with OO as its highlight as opposed to the programming language being the highlight of the text.

    Thing is if the reader is new to programming, they are unlikely to be able to grasp OO concepts anyway because of their lack of experience. Granted that I haven't thumbed through your book, but in my personal opinion it isn't a case of whether you should introduce OO to someone new to programming, it's a case of whether to provide an appropriate lead up to the topic of OO so that the reader will solidly understand the topic. As pointed out in my earlier post maybe such a detailed appreciation of OO is not required since Python handles a lot of the issues associated with OO under the hood, but they should also keep in mind that OO has a lot more to it.

    Having said that, I do agree with your reasons for mentioning OO. :)
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  17. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    I think we got our wires crossed there, mate. I've covered what I mean in my last post above. :)
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  18. BosonMichael
    Highly Decorated Member Award

    BosonMichael Yottabyte Poster

    19,136
    462
    374
    Welcome to the forums, Michael! :) Please stick around - there are a few other authors here on the site! :)
     
    Certifications: CISSP, MCSE+I, MCSE: Security, MCSE: Messaging, MCDST, MCDBA, MCTS, OCP, CCNP, CCDP, CCNA Security, CCNA Voice, CNE, SCSA, Security+, Linux+, Server+, Network+, A+
    WIP: Just about everything!
  19. ffreeloader

    ffreeloader Terabyte Poster

    3,661
    106
    167
    I'd disagree with this only because knowing how to implement OO in one language is to me something that is a transferable skill. If I understand the basics of how to use OO in Python, I'm going to have a good understanding of the basics of how to use classes and inheritance in other OO languages too. I mean, I don't think anyone intelligent enough to understand how to abstract out problems in one OO language is going to assume that another language is going to do things in exactly the same way, but they will understand that the foundations of how to do things is the same. Given that Python is so easy to learn I think it's a natural for teaching the foundations of OO programming to noob programmer such as I. For me it really eases the learning curve as learning how to abstract out problems and a very complex syntax at the same time is not an easy task. Python allows me to focus more what I'm trying to accomplish, and less on the language itself.

    I've even seen people object to Python because of its usage of tabs and whitespace, and that just makes no sense to me whatsoever. It's just a part of the syntax of the language. To me I like it that Python enforces tabs the way it does because it forces me write code in a much more readable way.


    Here I would disagree with you again. Ever since I was first introduced to scripting and any kind of programming the OO way of doing things has always seemed like a much easier way of abstracting out a problem. I haven't done much of it yet, but the advantage seems obvious to me. I guess it's because I am much better at this type of problem solving. It's just a much more natural way of thinking to me.
     
    Certifications: MCSE, MCDBA, CCNA, A+
    WIP: LPIC 1
  20. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    Whith all due respect, ffreeloader, after you have really got into Python writng fairly complex scripts and having researched OO to some depth I urge you to return and read this post.

    No. The point at which OO skills learned become 'transferrable' is when you have a knowledge of the OO concept and apply that knowledge to other languages. In terms of Python, you will have learned about object orientation within the implemetation provided by Python.

    At work I have regular debates with a fellow programmer, he is from a strong Java background and me from a strong C++ background. Both languages have their own flavours of OO with slightly different naming conventions to top it off: he calls a base class (C++) a 'parent class' (Java), and the nature of inheritence varies somewhat to the point where we have to resort to explaining to each other exactly what we mean when explaining a concept or problem. This is the message that I am trying to get across. Are you seriously telling me that once you have mastered OO for Python that you have mastered OO for every other language? If not, I have proved my point.

    New programmers should be mastering procedural programming before touching OO. If they are unfamiliar with the basic structure of a program it beats me how they have anything to contrast the benefits of OO against.

    No, and I agree with the opinion that forced indentation is a pain. Have you ever tried debugging a large Python script? The debugger, if one exists for your chosen IDE, is woefully inadequate - and without the aid of braces to clearly show code block boundaries, you can find yourself trying to line up lines of code tens of line apart. Secondly, it is very easy to 'misindent' a single line of code that qualifies it for a block that it was not supposed to be a part of. This can make a statement that was meant to be executed once to be part of a loop, for example. Very large scripts are a pain to follow and bugs are very hard to track.

    Programming has a habit of appearing easy when you first start to learn it, and this is true across all methodolgies (OO, procedural, functional, logic...). As problems increase in difficulty the programming effort increases exponentially to the point where the most seemingly moderately easy problems require a surprising amount of programming effort to see through to completion. This is where the true value of a programming language shine or otherwise. This leads to the suitability of a language for the problem domain at hand, and how the language facilitates the use whatever methodology it claims to implement. In determining the appropriate methodology for a problem needs the kind of knowledge that requires you to be able to abstract the principles of that methodology from the confines of any programming language. Only after this decision has been made can the actual programming language be chosen.

    Yes, Python is a great learning language and implements the OO methodoly as a tool to allow the programmer to solve problems that would otherwise take a lot more effort, but it is by no means a perfect language.
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.

Share This Page

Loading...