[Tutor] Where to store test-code?
Up to now I use this structure: src/myapp/setup.py src/myapp/myapp/real_code.py Now I want to write a test for a method which is implemented real_code.py. Where should I write store the file which contains the unittest? Is there a guideline for the directory structure of tests? I know that there are several ways. I know that all these ways work. Nevertheless it would be great to have a sane default. If there is a guideline IDEs could assist to create new tests at a common location. Related: https://youtrack.jetbrains.com/issue/JT-53069 Regards, Thomas -- Thomas Guettler http://www.thomas-guettler.de/ I am looking for feedback: https://github.com/guettli/programming-guidelines ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Next steps after creating virtualenv (new github project)?
Hello, I want to execute: print('Hello world.') in a file called hello.py After creating a virtual-env (via PyCharm) I have these directories: ./foo ./foo/venv ./foo/venv/lib ./foo/venv/lib/python3.6 ./foo/venv/lib/python3.6/site-packages ./foo/venv/include ./foo/venv/bin I want to store my small project in git and upload it to github later. What is the best practice for the directory layout? Are there (official) docs how to start a new project after creating the virtualenv? Regards, Thomas Güttler -- Thomas Guettler http://www.thomas-guettler.de/ I am looking for feedback: https://github.com/guettli/programming-guidelines ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Percentage of installations without setuptools (Was if __name__=='__main__' ...)
Am 13.08.2017 um 02:12 schrieb Steven D'Aprano: On Fri, Aug 11, 2017 at 02:35:00PM +0200, Thomas Güttler wrote: How high is the percentage of python installation which don't have setuptools? I have no clue. Is it 5%, 10%, 15% ...? I know there is no definite answer to this question. But you can guess this better than me. Somewhere between 0.1% and 99.9%. For what little it is worth, out of the 9 versions of Python I have installed on my personal machines, setuptools is installed for 4 of them. On work machines, 2 out of 5 have setuptools installed. So in total, 6 out of 14 Python installations I have access to include setuptools. So 57% *don't* have setup tools. Really Thomas, why do you care? Good question. Why do I care ... If there is no solid ground, no sane defaults, then young and talented programmers waste time. I just don't know why, but this makes me feel pain. If you want to require setuptools for your packages, go right ahead. If you want to tell people that using setuptools is the best choice, or the most popular choice, or the smartest choice, do so. Just don't say it is the "default choice" because that is silly. The whole purpose of something being *default* is so that you DON'T have to make a choice. Obviously that doesn't apply to choosing a packaging library, and especially not to choosing a packaging language which may not even be present. Even if its only missing 1% of the time. As a third-party author, the sorts of people who don't have setuptools installed either won't be installing your software at all, or will be installing it from source. -- Thomas Guettler http://www.thomas-guettler.de/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Percentage of installations without setuptools (Was if __name__=='__main__' ...)
I start a new thread, since this is a new topic. I don't have the deep knowledge like Chris, Steven or Alan. I guess most python installations have setuptools. But this is only my naive vague guess. How high is the percentage of python installation which don't have setuptools? I have no clue. Is it 5%, 10%, 15% ...? I know there is no definite answer to this question. But you can guess this better than me. Regards, Thomas Güttler Am 10.08.2017 um 12:01 schrieb Chris Warrick: > On 9 August 2017 at 23:15, Steven D'Aprano <st...@pearwood.info> wrote: >> On Tue, Aug 08, 2017 at 12:56:56PM +0200, Chris Warrick wrote: >> >>> While setuptools is not officially part of the stdlib, >> >> This is the critical factor. How can you use *by default* something that >> is *NOT* supplied by default? >> >> Obviously you cannot. It is physically impossible. > > > The problem with setuptools (and pip) is that they are not first-party > stdlib members, but they are not third-party packages either. They’re > somewhere in between. They have been blessed by the core developers. > And yes, setuptools might be in all the places you mentioned: > >> But this does NOT hold for everyone, possibly not even for the majority >> of Python users. For example: >> >> - students using their school's computers; >> >> - corporate and government users using a SOE (Standard Operating >>Environment); >> >> - people using a system where, for policy reasons, only the >>standard library is permitted. > > * If those computers run Windows (as they often do) and run a recent > Python version (3.4 or newer/2.7.9 or newer), setuptools will be > installed, unless the IT people explicitly disabled ensurepip. > * On macOS, setuptools will be installed if they’re using the system > Python, the python.org installers (which are not uninstallable), or > Python from Homebrew. The last two also have pip, and system Python > has ensurepip. > * On Linux, setuptools/pip is likely to be there, but it’s not > required in all distributions. (Fedora mandates setuptools; Debian > even rips out ensurepip by default and hides it in python3-venv > because reasons…) > > If the users are meant to install Python packages, their system > administrators would take care of that — either by setting up > setuptools/pip and perhaps virtualenv, or taking install requests from > users. If users are not supposed to be running setuptools/pip, they > probably shouldn’t, but they can still install it from ensurepip or > downloading get-pip.py. > >> I've worked in places where installing unauthorized software was a >> firing offence. > > Those people don’t need setuptools. Those people should not be using > distutils either. They might not even be allowed to download packages > and run __main__.py without installation. > -- Thomas Guettler http://www.thomas-guettler.de/ -- Thomas Guettler http://www.thomas-guettler.de/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] The sane default choice is entry_points console_scripts Was: if __name__=='main' vs entry points: What to teach new comers?
Am 08.08.2017 um 12:56 schrieb Chris Warrick: On 8 August 2017 at 03:30, Ben Finney <ben+pyt...@benfinney.id.au> wrote: Thomas Güttler <guettl...@thomas-guettler.de> writes: Why is "the sane default is 'use console_scripts entry-point in setup.py'" not a good answer? Because third-party Setuptools is required for entry points, which means entry points cannot be a default choice. It may well be a good choice for many cases. But that's a different matter from it being a good *default* choice; it can only be a default choice if it's in the standard library. While setuptools is not officially part of the stdlib, it *is* recommended by the official documentation, the dev team, and it’s available pretty much everywhere. setuptools can’t be in stdlib, because it’s moving too fast for stdlib to keep up. Look here: http://pythonwheels.com/ — 254 of the top 360 packages on PyPI use wheels. It means that at least that many use setuptools; sometimes with a distutils fallback, but often without one. Moreover, many of the packages without wheels use setuptools as well. The sane default choice is entry_points. Sounds good. Thank you for this statement. Regards, Thomas Güttler -- Thomas Guettler http://www.thomas-guettler.de/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] setup.py "script" vs "console_scripts" Was: if __name__=='main' vs entry points: What to teach new comers?
Am 05.08.2017 um 06:14 schrieb Ben Finney: Thomas Güttler <guettl...@thomas-guettler.de> writes: The underlaying question is: Imangine you are a newcomer. A newcomer is in a tough position when it comes to packaging and distributing Python code, especially the command-line programs. There has been significant progress on this in recent years. The Setuptools third-party library is a lot saner, the inclusion of ‘pip’ in standard installs makes it much broader in scope. But *not* in the standard library today, it's true. You need a guide like 'if unsure do x'. With other words: What is the sane default choice? There isn't a good answer to that question, today. The best answer today is: Read the guides from the Python Packaging Authority, and stay abreast of developments because this continues to change. Maybe eventually the ongoing work of the PyPA will be settled enough that it can update the standard library Distutils. But not today. You say that there isn't a good answer to that question, today. For me the question was: setup.py "script" vs "console_scripts" ? I found this: https://packaging.python.org/tutorials/distributing-packages/#console-scripts You say that there isn't a good answer to that question, today. I can't follow. Why is "the sane default is 'use console_scripts entry-point in setup.py'" not a good answer? Regards, Thomas Güttler -- Thomas Guettler http://www.thomas-guettler.de/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] setup.py "script" vs "console_scripts" Was: if __name__=='main' vs entry points: What to teach new comers?
Am 04.08.2017 um 02:50 schrieb Ben Finney: Thomas Güttler <guettl...@thomas-guettler.de> writes: Why are there two ways: "script" vs "console_scripts entry-point"? Because Distutils implements only ‘scripts’, and that's not capable enough for what people need so Setuptools implements entry points. In other words: One of them is in the standard library and does something; the other is third-party and can do more. That answers why there are two. But maybe you wanted to ask some underlying question? The underlaying question is: Imangine you are a newcomer. And there are two more choices. You need a guide like 'if unsure do x'. With other words: What is the sane default choice? Chris wrote "Simple: `scripts` are legacy." You say it is the standard, and console_scripts is from a third party. For me "legacy" sound like "don't go this old way". For me "third party" sounds like "don't go this way, stick to the standard". I feel stupid since I have no clue. Regards, Thomas Güttler -- Thomas Guettler http://www.thomas-guettler.de/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] setup.py "script" vs "console_scripts" Was: if __name__=='main' vs entry points: What to teach new comers?
Am 02.08.2017 um 18:06 schrieb Wolfgang Maier: On 08/02/2017 04:57 PM, Steven D'Aprano wrote: On Wed, Aug 02, 2017 at 10:48:39PM +1000, Ben Finney wrote: Thomas Güttler <guettl...@thomas-guettler.de> writes: Maybe I am doing something wrong. I was proud because I did use “console_scripts” entry points. Did someone lead you to believe it was wrong? Setuptools console_scripts entry points are a good tool. My point was that it is an *advanced* tool, difficult to use and also difficult to explain because the concepts are advanced. Can you explain the use-case for when somebody might want to use console_scripts entry points? I have a module with a main() function and an "if __name__ == ..." guard. Under what circumstances is that not sufficient, and I would want console_scripts? If you install things using pip/setuptools and have defined a console_scripts entry point for it, then the corresponding wrapper script will be installed in whatever is considered the scripts directory at install time on that machine. With a bit of luck the entry point will thus be executable directly without any end-user intervention (like adding folders to $PATH and chmodding files). Personally, I always found it straightforward to write the wrapper script myself, then define this as a 'scripts' file in the package layout of my setup.py, but people's MMV. I was not aware of "scripts" in setup.py. But I found docs: http://python-packaging.readthedocs.io/en/latest/command-line-scripts.html Why are there two ways: "script" vs "console_scripts entry-point"? Regards, Thomas -- Thomas Guettler http://www.thomas-guettler.de/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] if __name__=='main' vs entry points: What to teach new comers?
Am 02.08.2017 um 05:51 schrieb Steven D'Aprano: On Wed, Aug 02, 2017 at 11:22:00AM +1000, Ben Finney wrote: Steven D'Aprano <st...@pearwood.info> writes: On Tue, Aug 01, 2017 at 04:54:40PM +0200, Thomas Güttler wrote: [...] I use Python since several years and I use console_script in entry_points of setup.py. What's console_script in entry_points of setup.py? It is an advanced feature in Setuptools, that allows defining a function in the code base as the entry point for external use. The “console_scripts” entry points tell Setuptools to, at installation time, create a wrapper script that invokes that function as a command-line program. <URL:https://setuptools.readthedocs.io/en/latest/setuptools.html#automatic-script-creation> Thanks. Now that I have learned that, I shall do my best to forget it :-) Maybe I am doing something wrong. I was proud because I did use “console_scripts” entry points. I thought this is the right way of doing it. Doing things the right way always makes my feel so very good :-) Regards, Thomas -- Thomas Guettler http://www.thomas-guettler.de/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] if __name__=='main' vs entry points: What to teach new comers?
Am 02.08.2017 um 05:35 schrieb Abdur-Rahmaan Janhangeer: what difference do you make between python scripts and python code files? are codes relating to file manipulation called scripts? Do you ask this question all people on this list, or only one particular person? I don't know the difference between python scripts and python code files. Regards, thomas -- Thomas Guettler http://www.thomas-guettler.de/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] __main__.py file Was: if __name__=='main' vs entry points: What to teach new comers?
Do both. If you’re making a package, create a __main__.py file as well so your package is usable with `python -m somepackage`. On the other hand, if you’re making things more akin to shell scripts, using just entry_points makes stuff harder, because you need to install the code (and write a setup.py), as opposed to just putting the script somewhere in $PATH. Up to now I never did this. Maybe I will do this in the future. thank you, Thomas Güttler -- Thomas Guettler http://www.thomas-guettler.de/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] if __name__=='main' vs entry points: What to teach new comers?
I have a friend who is a talented shell script writer. He is a linux guru since several years. He asked me if "if __name__=='main':" is state of the art if you want to translate a shell script to python. I started to stutter and did not know how to reply. I use Python since several years and I use console_script in entry_points of setup.py. I am very unsure if this is the right way if you want to teach a new comers the joy of python. In the current context we want to translate a bunch of shell scripts to python scripts. What do you think? Regards, Thomas Güttler -- Thomas Guettler http://www.thomas-guettler.de/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] classproperty: readonly and inheritance - not more needed
Now the "not read-only" part: Foo.my_prop = "whatever" Foo.my_prop 'whatever' You now have a string attribute, the property is lost. Methods behave the same way and it's generally not a problem, but you should at least be aware of this behaviour. Yes, now I understand you. Thank you Regards, Thomas Güttler -- Thomas Guettler http://www.thomas-guettler.de/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] classproperty: readonly and inheritance - not more needed
Am 20.04.2017 um 14:26 schrieb Steven D'Aprano: On Thu, Apr 20, 2017 at 10:39:57AM +0200, Thomas Güttler wrote: - its hard to get classproperty to work right. What is "righ"? In my case a read-only classproperty is enough. Inheritance should be supported. I don't have a usecase for a setter. The standard library is not just for you :-) If Peter's solution is "good enough" for you, then great, go ahead and use it. But beware: of the two implementations I know, you cannot have both: - access from instances; - read-only property; You can have access from instances, but then the classproperty is not read-only. Or you can have read-only access, but only from the class object. I can't follow what you. What do you mean with "... is not read-only". This snippet works fine: {{{ class classproperty(object): def __init__(self, f): self.f = f def __get__(self, obj, owner): return self.f(owner) class Foo(object): @classproperty def my_prop(cls): return 42 print Foo.my_prop print Foo().my_prop }}} Regards, Thomas -- Thomas Guettler http://www.thomas-guettler.de/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] classproperty: readonly and inheritance - not more needed
Am 19.04.2017 um 11:16 schrieb Steven D'Aprano: On Wed, Apr 19, 2017 at 09:28:26AM +0200, Thomas Güttler wrote: [code for a classproperty] Nice, if it is that simple. Is there a reason why this is not in the standard library? I haven't had a chance to test Peter's classproperty code yet, but I don't expect it to be that simple. People have asked for it before, and even Guido himself (the inventor of Python) has agreed that if it existed he'd use it, but the proposals have (so far) always stumbled on two factors: - there are not a lot of uses for classproperty that ordinary property isn't "good enough" for; - its hard to get classproperty to work right. What is "righ"? In my case a read-only classproperty is enough. Inheritance should be supported. I don't have a usecase for a setter. Regards, Thomas Güttler ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] classproperty, three times in virtualenv
Am 19.04.2017 um 09:43 schrieb Alan Gauld via Tutor: On 19/04/17 08:28, Thomas Güttler wrote: Nice, if it is that simple. Is there a reason why this is not in the standard library? Probably because it is such a rare use case and because its not that hard to do yourself if you really need it. But the standard library, like any open source project, develops as people need things. If nobody needs something it will never be built and therefore never be added to the library. I'd guess this falls into that category. In my virtualenv it looks like it has three implementations. Maybe more with a different name. user@host> find src/ lib/ -name '*.py'|xargs grep -Ei '(def|class) classproperty' lib/python2.7/site-packages/logilab/common/decorators.py:class classproperty(object): lib/python2.7/site-packages/django/utils/decorators.py:class classproperty(object): lib/python2.7/site-packages/mptt/models.py:class classpropertytype(property): Regards, Thomas -- Thomas Guettler http://www.thomas-guettler.de/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] classproperty for Python 2.7 (read-only enough)
Am 18.04.2017 um 13:17 schrieb Peter Otten: Thomas Güttler wrote: I would like to have read-only class properties in Python. I found this http://stackoverflow.com/questions/128573/using-property-on-classmethods But there are a lot of discussions of things which I don't understand. I want to be a user of class properties, not an implementer of the details. I found this: https://pypi.python.org/pypi/classproperty But above release is more then ten years old. I am unsure if it's dead or mature. I am using Python 2.7 and attribute getters would be enough, no attribute setter is needed. My use case is configuration, not fancy algorithms or loops. Like this? $ cat classproperty.py class classproperty(object): def __init__(self, fget): self.fget = fget def __get__(self, inst, cls): return self.fget(cls) class Foo(object): FOO = 42 @classproperty def foo(cls): return cls.FOO print "Foo.foo =", Foo.foo print "Foo().foo =", Foo().foo $ python2 classproperty.py Foo.foo = 42 Foo().foo = 42 Nice, if it is that simple. Is there a reason why this is not in the standard library? Regards, Thomas Güttler -- Thomas Guettler http://www.thomas-guettler.de/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] classproperty for Python 2.7 (read-only enough)
I would like to have read-only class properties in Python. I found this http://stackoverflow.com/questions/128573/using-property-on-classmethods But there are a lot of discussions of things which I don't understand. I want to be a user of class properties, not an implementer of the details. I found this: https://pypi.python.org/pypi/classproperty But above release is more then ten years old. I am unsure if it's dead or mature. I am using Python 2.7 and attribute getters would be enough, no attribute setter is needed. My use case is configuration, not fancy algorithms or loops. Regards, Thomas Güttler -- Thomas Guettler http://www.thomas-guettler.de/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] NumPy and SciPy
Hi there, you have an idea where I can find NumPy and SciPy windows *.exe-files for Python 3.5? Thanks for any help! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Practice Exercises for Beginner ? :p:
On Jun 2, 2016, at 16:43, Andrei Coltawrote: Hi, Anyone can recommend practical work on learning python.. seems reading and reading does not helping. Thanks in advance, Andrei I would echo those saying "make something" - for me the thing that really moved me forward was doing a data project, make the sqlite database, manipulate it, make a Flask site to access it, etc. Lots of resources on the web to guide you to do such things. Alternatively try some of the many coding challenge sites. My daughter is currently loving CodeAbbey. A trick to CodeAbbey - there are lots of tools in Python that make the challenges vanishingly easy (at least the early ones) but you will likely learn more if you force yourself to write those programs without Python's "batteries included" tools. SDG, tom ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Semantic Error: Trying to access elements of list and append to empty list with for loop
Thanks, everyone, for your help. The objective was to extract all words from each line and place them in a list IF they didn't already exist in it. I sorted it out by adding little bits of everyone's suggestions. Here's the code that fixed it. fname = raw_input('Enter file name:\n') try: fhand = open(fname) except: print 'File cannot be found or opened:', fname exit() lst = list() for line in fhand: words = line.split() for word in words: if word in lst: continue else: lst.append(word) lst.sort() print lst I named the file WordExtract.py since it does just that. :) *Warm regards,* *Olaoluwa O. Thomas,* *+2347068392705* On Thu, Jun 2, 2016 at 6:44 PM, Steven D'Aprano <st...@pearwood.info> wrote: > On Thu, Jun 02, 2016 at 06:05:43PM +0100, Olaoluwa Thomas wrote: > > > fname = raw_input('Enter file name:\n') > > try: > > fhand = open(fname) > > except: > > print 'File cannot be found or opened:', fname > > exit() > > lst = list() > > for line in fhand: > > words = line.split() > > #print words (this was a test that a portion of my code was working) > > lst.append(words) > > If you printed words, you should have seen that it was a list. > > If you append a list to a list, what do you get? At the interactive > prompt, try it: > > > py> L = [1, 2, 3] > py> L.append([4, 5, 6]) > py> L > [1, 2, 3, [4, 5, 6]] > > > Append takes a single argument, and adds it *unchanged* to the end of > the list. > > What you want is the extend method. It takes a list as argument, and > appends each item individually: > > > py> L.extend([7, 8, 9]) > py> L > [1, 2, 3, [4, 5, 6], 7, 8, 9] > > > But if you didn't know about that, you could have done it the > old-fashioned way: > > lst = list() > for line in fhand: > words = line.split() > for word in words: > lst.append(word) > > > > -- > Steve > ___ > 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] Semantic Error: Trying to access elements of list and append to empty list with for loop
Hi Tutor, I'm trying to parse words in a file line by line and place all words into another list but I keep getting a list with nested lists. I would normally pore over it and go to google and fix my problems but this one escapes me and frankly, I'm tired of being stuck in the same place for almost a week. Here's the code: fname = raw_input('Enter file name:\n') try: fhand = open(fname) except: print 'File cannot be found or opened:', fname exit() lst = list() for line in fhand: words = line.split() #print words (this was a test that a portion of my code was working) lst.append(words) print lst A text file with the following contents "But soft what light through yonder window breaks It is the east and Juliet is the sun Arise fair sun and kill the envious moon Who is already sick and pale with grief" would give me the output in the attached screenshot [image: Inline image 2] whereas I want only one list containing strings not nested lists. Any help would be appreciated. *Warm regards,* *Olaoluwa O. Thomas,* *+2347068392705* ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Issues converting a script to a functioin (or something) [SOLVED]
Gotcha. *Warm regards,* *Olaoluwa O. Thomas,* *+2347068392705* On Sun, May 1, 2016 at 7:14 PM, Alan Gauld via Tutor <tutor@python.org> wrote: > On 01/05/16 14:38, Olaoluwa Thomas wrote: > > > Thanks for your feedback. Please do not hesitate to provide more as I > shall > > email you personally in the future. > > Please don't do that. > a) Bob is a busy man who volunteers his time here, but may >have other things to do too. > b) The list is here so that everyone can benefit from the >discussions not only the people actively involved. > > > > The problem was that running the code gave an error which I now do not > > remember in detail as I have moved on after having fixed it. > > But the answer is nearly always in the detail. And as you get > more advanced in coding the errors get harder to spot. That's > why it is important to supply us (or any other forum) with > as much detail as you can. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > 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 maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Issues converting a script to a functioin (or something) [SOLVED]
Hi Bob, Thanks for your feedback. Please do not hesitate to provide more as I shall email you personally in the future. The script is made up of a function definition and its call prompting the user for input. The script itself takes "number of hours worked" and "hourly rate" as inputs and gives gross pay as a product of the two. As I stated in my earlier email, there is also a portion for calculating gross pay with considerations for overtime (> 40 hours worked). The problem was that running the code gave an error which I now do not remember in detail as I have moved on after having fixed it. Here's the initial email below with Sreenathan's helpful input followed by my amendments to the code: (I thought my initial email was quite self-explanatory but what do I know... Please read through to the end) On Sun, May 1, 2016 at 1:09 PM, Sreenathan Nair <sreenath...@gmail.com> wrote: > On Sun, May 01, 2016 at 5:34 PM, Olaoluwa Thomas <thomasolaol...@gmail.com> > wrote: > > The novice Python programmer is back. > > I'm trying to incorporate a function and its call in the GrossPay.py > script > that Alan solved for me. > It computes total pay based on two inputs, no. of hours and hourly rate. > > There's a computation for overtime payments in the if statement. > > Something seems to be broken. > > Here's the code: > def computepay(hours, rate): > hours = float(raw_input ('How many hours do you work?\n')) > rate = float(raw_input ('What is your hourly rate?\n')) > if hours > 40: > gross = ((hours - 40) * (rate * 1.5)) + (40 * rate) > elif hours >= 0 and hours <= 40: > gross = hours * rate > print "Your Gross pay is "+str(round(gross, 4)) > > computepay() > > What am I doing wrong? > > *Warm regards,* > > *Olaoluwa O. Thomas,* > *+2347068392705* > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > Hi, > The parameters hours and rate are required when calling the method > computepay ex: computepay(8, 200), so basically computepay() by itself will > throw an error Also, as a suggestion if you're gonna get hours and > rate via user input perhaps they can be removed from the method definition? > > Thanks, Sreenathan. These alterations solved it. def computepay(hours, rate): if hours > 40: gross = ((hours - 40) * (rate * 1.5)) + (40 * rate) elif hours >= 0 and hours <= 40: gross = hours * rate print "Your Gross pay is "+str(round(gross, 4)) computepay(hours = float(raw_input ('How many hours do you work?\n')), rate = float(raw_input ('What is your hourly rate?\n'))) *Warm regards,* *Olaoluwa O. Thomas,* *+2347068392705* On Sun, May 1, 2016 at 2:13 PM, Bob Gailer <bgai...@gmail.com> wrote: > > On May 1, 2016 8:04 AM, "Olaoluwa Thomas" <thomasolaol...@gmail.com> > wrote: > > > > The novice Python programmer is back. > Welcome back. We are here to help you when you are stuck. Telling us > something is broken is not adequate. Tell us-what you are expecting the > program to do and what results you're getting. > > > > I'm trying to incorporate a function and its call in the GrossPay.py > script > > that Alan solved for me. > > It computes total pay based on two inputs, no. of hours and hourly rate. > > > > There's a computation for overtime payments in the if statement. > > > > Something seems to be broken. > > > > Here's the code: > > def computepay(hours, rate): > > hours = float(raw_input ('How many hours do you work?\n')) > > rate = float(raw_input ('What is your hourly rate?\n')) > > if hours > 40: > > gross = ((hours - 40) * (rate * 1.5)) + (40 * rate) > > elif hours >= 0 and hours <= 40: > > gross = hours * rate > > print "Your Gross pay is "+str(round(gross, 4)) > > > > computepay() > > > > What am I doing wrong? > > > > *Warm regards,* > > > > *Olaoluwa O. Thomas,* > > *+2347068392705* > > ___ > > 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] Issues converting a script to a functioin (or something)
The novice Python programmer is back. I'm trying to incorporate a function and its call in the GrossPay.py script that Alan solved for me. It computes total pay based on two inputs, no. of hours and hourly rate. There's a computation for overtime payments in the if statement. Something seems to be broken. Here's the code: def computepay(hours, rate): hours = float(raw_input ('How many hours do you work?\n')) rate = float(raw_input ('What is your hourly rate?\n')) if hours > 40: gross = ((hours - 40) * (rate * 1.5)) + (40 * rate) elif hours >= 0 and hours <= 40: gross = hours * rate print "Your Gross pay is "+str(round(gross, 4)) computepay() What am I doing wrong? *Warm regards,* *Olaoluwa O. Thomas,* *+2347068392705* ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Issue with Code [SOLVED]
Thank you so much, Alan. That fixed it (See Script 2[SOLVED] below). For the purpose of record-keeping, I'm pasting the entire code of all scripts below as I should have done from the very beginning. P.S. How were you able to open attachments with the restrictions on this mailing list? Script 1 hours = raw_input ('How many hours do you work?\n') rate = raw_input ('What is your hourly rate?\n') gross = float(hours) * float(rate) print "Your Gross pay is "+str(round(gross, 4)) Script 2 hours = raw_input ('How many hours do you work?\n') rate = raw_input ('What is your hourly rate?\n') if hours > 40: gross = ((float(hours) - 40) * (float(rate) * 1.5)) + (40 * float(rate)) elif hours >= 0 and hours <= 40: gross = float(hours) * float(rate) print "Your Gross pay is "+str(round(gross, 4)) Script 2 [SOLVED] hours = float(raw_input ('How many hours do you work?\n')) rate = float(raw_input ('What is your hourly rate?\n')) if hours > 40: gross = ((hours - 40) * (rate * 1.5)) + (40 * rate) elif hours >= 0 and hours <= 40: gross = hours * rate print "Your Gross pay is "+str(round(gross, 4)) I'm gonna add Try and Except to make it more responsive. Thanks a lot! *Warm regards,* *Olaoluwa O. Thomas,* *+2347068392705* On Sun, May 1, 2016 at 2:00 AM, Alan Gauld via Tutor <tutor@python.org> wrote: > On 01/05/16 01:16, Alan Gauld via Tutor wrote: > > > I can't see anything obviously wrong in your code > > I was too busy focusing on the calculations that > I didn't check the 'if' test closely enough. > You need to convert your values from strings > before comparing them. > > hours = float(raw_input ('How many hours do you work?\n')) > rate = float(raw_input ('What is your hourly rate?\n')) > if hours > 40: >gross = (hours-40)*(rate*1.5) + (rate*40) > else: >gross = hours*rate > > > Sorry, > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > 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 maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: Issue with Code
Hi All, I sent this forwarded email earlier but hadn't subscribed to the mailing list so I guess that's why I didn't get a response. Please review and advise. *Warm regards,* *Olaoluwa O. Thomas,* *+2347068392705* -- Forwarded message -- From: Olaoluwa Thomas <thomasolaol...@gmail.com> Date: Sat, Apr 30, 2016 at 4:30 PM Subject: Issue with Code To: tutor@python.org Hi, I'm new to Python and programming in general. I came across a simple exercise that is used to compute gross pay when prompted to enter number of hours and hourly rate. I've attached the scripts in question (created via Notepad++). The 1st script I wrote worked perfectly. The 2nd script makes amendments to the 1st by increasing the hourly rate by 50% when number of hours is greater than 40. The problem with this script is that the "else" statement (which is equivalent to the 1st script) does not compute gross pay accurately as seen in the attached screenshot. I would appreciate a logical explanation for why the "else" statement in the 2nd script isn't working properly. I'm running Python v2.7.8 on a Windows 7 Ultimate VM via Command prompt and my scripts are created and edited via Notepad++ v6.7.3 *Warm regards,* *Olaoluwa O. Thomas,* *+2347068392705* hours = raw_input ('How many hours do you work?\n') rate = raw_input ('What is your hourly rate?\n') gross = float(hours) * float(rate) print "Your Gross pay is "+str(round(gross, 4))hours = raw_input ('How many hours do you work?\n') rate = raw_input ('What is your hourly rate?\n') if hours > 40: gross = ((float(hours) - 40) * (float(rate) * 1.5)) + (40 * float(rate)) else: gross = float(hours) * float(rate) print "Your Gross pay is "+str(round(gross, 4))___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Issue with Code
Hi, I'm new to Python and programming in general. I came across a simple exercise that is used to compute gross pay when prompted to enter number of hours and hourly rate. I've attached the scripts in question (created via Notepad++). The 1st script I wrote worked perfectly. The 2nd script makes amendments to the 1st by increasing the hourly rate by 50% when number of hours is greater than 40. The problem with this script is that the "else" statement (which is equivalent to the 1st script) does not compute gross pay accurately as seen in the attached screenshot. I would appreciate a logical explanation for why the "else" statement in the 2nd script isn't working properly. I'm running Python v2.7.8 on a Windows 7 Ultimate VM via Command prompt and my scripts are created and edited via Notepad++ v6.7.3 *Warm regards,* *Olaoluwa O. Thomas,* *+2347068392705* hours = raw_input ('How many hours do you work?\n') rate = raw_input ('What is your hourly rate?\n') gross = float(hours) * float(rate) print "Your Gross pay is "+str(round(gross, 4))hours = raw_input ('How many hours do you work?\n') rate = raw_input ('What is your hourly rate?\n') if hours > 40: gross = ((float(hours) - 40) * (float(rate) * 1.5)) + (40 * float(rate)) else: gross = float(hours) * float(rate) print "Your Gross pay is "+str(round(gross, 4))___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recommendations for best tool to write/run Python :p:
On 03/03/2016 02:26 AM, Lisa Hasler Waters wrote: Could you please recommend the best Python tools for writing and running our code for the long term? Also, we are hoping to find free tools! Most people on this list are a lot smarter than me so there are probably good reasons for it but I have used Ipython (now Jupyter) for teaching my kids programming in middle and high school. === Thomas C. Hicks, MD, MPH Training Manager Gansu Gateway, Lanzhou, Gansu ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recommendations for best tool to write/run Python :p:
Matt, As a physician myself just getting into the world of teaching computer programming I would be very interested to know what you teach to the doctors. Feel free to reply off list, would love to discuss this! === Thomas C. Hicks, MD, MPH Training Manager Gansu Gateway, Lanzhou, Gansu On 03/03/2016 05:25 AM, Matt Williams wrote: I teach an introductory programming course to medical students (and a few doctors). I would look at Sublime Text 2 if one Windows/ Mac. Has a 'nag' screen to remind you to buy, but feels simple enough when you start it. M On Wed, 2 Mar 2016 19:50 Ben Finney, <ben+pyt...@benfinney.id.au> wrote: Lisa Hasler Waters <lwat...@flinthill.org> writes: Ben, in terms of time for learning curve, I suppose we do have some limitations as we are up against school schedules. However, if it is something I could learn in a reasonable time that I could then more quickly walk my students through then I'd be up for the challenge! In that case, my recommendation is to learn a good programmer's editor, and let your students gain exposure to that. Emacs and Vim are the unchallenged masters here; community-owned, free-software, cross-platform, mature and highly flexible with support for a huge range of editing tasks. Learning either of those will reward the student with a tool they can use broadly throughout whatever computing career they choose. They aren't a small investment, though. That “mature” comes at the cost of an entire ecosystem that evolved in decades past; concepts and commands are idiosynratic in each of them. It is highly profitable for any programmer to learn at least one of Emacs or Vim to competence, but it may be too much to confront a middle-school student in limited class time. Maybe let the class know they exist, at least. Short of those, I'd still recommend a community-owned, free-software, highly flexible programmer's editor. If you're on GNU+Linux, use the Kate or GEdit editors; they integrate very nicely with the default desktop environment and are well-maintained broadly applicable text editors. GEdit in particular has good Python support. I would recommend staying away from any language-specific IDE. Teaching its idiosyncracies will still be a large time investment, but will not be worth it IMO because the tool is so limited in scope. Better to teach a powerfuly general-purpose programmer's editor, and use the operating system's facilities for managing files and processes. -- \“Humanity has advanced, when it has advanced, not because it | `\ has been sober, responsible, and cautious, but because it has | _o__)been playful, rebellious, and immature.” —Tom Robbins | Ben Finney ___ 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 maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Create complex dictionary :p:
On 10/23/2015 05:19 AM, jarod_v6--- via Tutor wrote: Hi!!I would like to prepare a dictionary with complex structure: complex = {name ="value",surname="po",age=poi) What is the most pythonic way to build a dictionary of dictionary?thanks for any help! This doesn't look too complex so I am probably missing something. The normal dictionary construction would look something like this: mydict = dict('name'='value', 'surname'='po','age'='poi') Then you can access any given item in mydict with the get method: mydict.get('name') SDG, tom ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Create complex dictionary :p: :p:
On 10/23/2015 05:59 AM, Alex Kleider wrote: mydict = dict('name'='value', 'surname'='po','age'='poi') Oops, you are correct! Don't want to put the key names in quotes, I mistyped my experiment. SDG, tom ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] tkinter in Python 3
I'm trying to move a Python 2.x program to Python 3.x. When I try to import tkinter I get the error message that no module _tkinter can be found. I've tried sudo apt-get install python-tk. While this command works, there is no difference in the result. This problem has only cropped up after I changed to Ubuntu 15.04. Does anyone have any suggestions? Thanks in advance for any help. Mike ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Pytest help :p:
On 07/07/2015 06:58 PM, Alan Gauld wrote: The best place to ask for help on any 3rd party package is on the package's own support forum/list. Py.test has several options: https://pytest.org/latest/contact.html The Testing In Python http://lists.idyll.org/listinfo/testing-in-python mailing list is outstanding, civil, knowledgable people really wanting to help. == Thomas C. Hicks, MD, MPH Training Manager, Gansu Gateway Lanzhou, Gansu, PR China ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] creat a program that reads frequency of words in file :p:
On 06/01/2015 05:56 PM, Alan Gauld wrote: if text in line: count += 1 print(This word appears, count, times in the file) And this is, of course, completely off track. You need to split the line into its separate words and store each word into the dictionary. OP may want to research the setdefault and get methods for dictionaries. SDG, tom ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Integrating TDD into my current project work-flows :p:
On 05/06/2015 07:18 AM, WolfRage wrote: I find myself in the same mind set as this individual: http://stackoverflow.com/a/64453/4285911 It is hard to write a proper test with out me initially outlining where I am going. Perhaps I need to better understand planning and drafting a programming project before I can hope to emulate TDD. For what it is worth the idea of user stories really helped me develop an approach to testing (or should I say, start an approach to testing). The tutorial (here http://chimera.labs.oreilly.com/books/123400754/index.html) covering Django development really drove that idea and its implementation home for me. I believe the user story idea first shows up in chapter 2 of the book. thomas ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to output dictionary data to CSV file :p:
On 04/28/2015 09:43 PM, Alan Gauld wrote: You could consider JSON too. JSON looks a lot like a Python dictionary of strings so is almost a perfect match to your data. Sounds great, I'll check it out. Thanks! thomas == Thomas C. Hicks, MD, MPH Training Manager, Gansu Gateway Lanzhou, Gansu, PR China ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to output dictionary data to CSV file :p:
On 04/28/2015 05:30 PM, Peter Otten wrote: data = {'B002':'NRP 2014','B003':'HBB 2015'} writer = csv.writer(sys.stdout) writer.writerows(data.items()) B002,NRP 2014 B003,HBB 2015 That is exactly what I was looking for! Thanks, apparently my knowledge deficit is in understanding dictionary methods. How rude of me, I neglected to note I am using Python 3.4.3. And now you're top-posting to make it even worse;) Lesson learned! thomas ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Variable data to CSV
Hey all so I'm new to python(like 2 days ago new) I need to find the device address, usb port, and number of times the error occurs Heres what I have: import re import csv import reimport csvf = open(file.txt, r) #location of log file searchlines = f.readlines() #create list from filef.close()for element in searchlines: usbPres = re.search('(USB)',element) #pattern to find usb lines devAddr = re.search('(address)\s\d+',element) #parsing pattern for device address port = re.search('(port)\s\d',element) #parsing pattern for port if usbPres: This is where I get lost because I want to assign the correct port to device address and then count number of time it failed before a new device is inserted into that port. then write it to a CSV SAMPLE TEXT *** [11883.112089] hub 1-0:1.0: Cannot enable port 3. Maybe the USB cable is bad? [11883.224080] usb 1-7: new high speed USB device using ehci_hcd and address 42 [11883.328151] hub 1-0:1.0: unable to enumerate USB device on port 7 [11904.472097] hub 1-0:1.0: Cannot enable port 3. Maybe the USB cable is bad? [11907.440096] hub 1-0:1.0: Cannot enable port 3. Maybe the USB cable is bad? [11910.408093] hub 1-0:1.0: Cannot enable port 3. Maybe the USB cable is bad? [11913.376095] hub 1-0:1.0: Cannot enable port 3. Maybe the USB cable is bad? [11913.616090] usb 1-7: new high speed USB device using ehci_hcd and address 47 [11913.716121] hub 1-0:1.0: unable to enumerate USB device on port 7 [11927.340096] hub 1-0:1.0: Cannot enable port 3. Maybe the USB cable is bad? [11930.308096] hub 1-0:1.0: Cannot enable port 3. Maybe the USB cable is bad? [11933.276124] hub 1-0:1.0: Cannot enable port 3. Maybe the USB cable is bad? [11936.244118] hub 1-0:1.0: Cannot enable port 3. Maybe the USB cable is bad? [11939.212116] hub 1-0:1.0: Cannot enable port 7. Maybe the USB cable is bad?Any help is much appreciated.Tom ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] I am teaching my students Python the second semester using www.LearnStreet.com ( http://www.learnstreet.com/ ). I am in need of some help. I am having a problem with the Lists-Set 1 exercise 1
I am teaching my students Python the second semester using www.LearnStreet.com ( http://www.learnstreet.com/ ). I am in need of some help. I am having a problem with the Lists-Set 1 exercise 18. The problem is below. I have put in several codes and the output is 5, which is the right answer. But it is asking for List's index logic. I have tried support with LearnStreet but they have yet to respond. Thank you for your time. Tommy Maher 18 : Finding the length of nested lists. Create two lists list1 = [1,2,3,4,5] and list2 = [6,7,8,list1]. Write a code to find the length of list1 in list2 using for loop. Use the if statement to check elements in the list2. def len_of_innerlist(list2): # your code here list1 = [1,2,3,4,5] print len_of_innerlist([6,7,8,list1]) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Web scrapping
Hi, I am new to python3. I am working in computational biology. I need to submit many sequence (one by one) to a http web server ( http://mfold.rna.albany.edu/?q=mfold/RNA-Folding-Form) . After the processing I need to download the output file. There is an offline package for this server but certain features not available in it. The url for each request is not unique. Is there anyway to do this process by a code ie sending the request, downloading etc. Any suggestions or useful material will be of great help. Working on Python 3.3.1,ubuntu 13.04(Linux 3.8.0-29-generic x64) Thanking you, Amal ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Web scrapping
Hi, Ya its kind of user filling out a form and sending request. Steps are like this. 1. I need to submit my sequence in webserver ( like filling out a form in web) 2. Then I have to give a request for format sequence(available in the link: http://mfold.rna.albany.edu/?q=mfold/RNA-Folding-Form ) 3. Then further steps downloading the output.. Thanks, On Fri, Dec 13, 2013 at 12:19 AM, Joel Goldstick joel.goldst...@gmail.comwrote: On Thu, Dec 12, 2013 at 1:41 PM, Amal Thomas amalthomas...@gmail.comwrote: Hi, I am new to python3. I am working in computational biology. I need to submit many sequence (one by one) to a http web server ( http://mfold.rna.albany.edu/?q=mfold/RNA-Folding-Form) . After the processing I need to download the output file. There is an offline package for this server but certain features not available in it. The url for each request is not unique. Is there anyway to do this process by a code ie sending the request, downloading etc. Any suggestions or useful material will be of great help. Working on Python 3.3.1,ubuntu 13.04(Linux 3.8.0-29-generic x64) Thanking you, Amal ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor Python comes with the urllib module, but there is a third party module called Requests (http://requests.readthedocs.org/en/latest/). This will let you fill in the form via your program, and also download some document. Your subject 'screen scraping' is puzzling. It seems what you are asking is how to make your program act like a user filling out a form. Or i completely misunderstood. -- Joel Goldstick http://joelgoldstick.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Web scrapping
On Fri, Dec 13, 2013 at 12:29 AM, Joel Goldstick joel.goldst...@gmail.comwrote: So, read the Requests tutorial, and study the POST examples as POST is the http method that is used when filling in a form. First you will need to examine the form to learn the names of the fields you need to provide data for. @Joel : Thanks. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Need to create code
Write a function named SSN2Name with an interactive loop. The function takes the dictionary named data as input argument where this dictionary stores the key, value pairs of SSN, name of person. The SSN is in the string format 'xxx-xx-' and name is also a string. Each iteration of the functions's loop should prompt the user to enter an SSN in the required format and next, it should print the name of the person if he/she is found in the dictionary, otherwise a message like person not found if that SSN does not exist in the keys of the dictionary. The loop should stop iterating when the user inputs the empty string when prompted for SSN. Write the full function definition in your answer. The function outline is given below with comments provided as code hints - def SSN2Name(data): # create a loop that repeats forever (while True loop) # within the loop prompt user for SSN # if user input is empty string break out of loop # if user input is an SSN found as a key in the dictionary, print the value corresponding to that key # if user input is not found as a key in the dictionary print message saying person was not found ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Load Entire File into memory
On Mon, Nov 4, 2013 at 10:00 PM, Steven D'Aprano st...@pearwood.info wrote: import os filename = YOUR FILE NAME HERE print(File size:, os.stat(filename).st_size) f = open(filename) content = f.read() print(Length of content actually read:, len(content)) print(Current file position:, f.tell()) f.close() and send us the output. This is the output: File size: 50297501884 Length of content actually read: 50297501884 Current file position: 50297501884 This Code used 61.4 GB RAM and 59.6 GB swap (I had ensured that no other important process were running in my server before running this :D) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Load Entire File into memory
Hi, I am new to python. I am working in computational biology and I have to deal with text files of huge size. I know how to read line by line from a text file. I want to know the best method in *python3* to load the enire file into ram and do the operations.(since this saves time) I am currently using this method to load my text file: *f = open(output.txt)content=io.StringIO(f.read())f.close()* But I have found that this method uses 4 times the size of text file.( if output.txt is 1 gb total ram usage of the code is approx 3.5 gb :( ). Kindly suggest me a better way to do this. Working on Python 3.3.1,ubuntu 13.04(Linux 3.8.0-29-generic x64) Thanks -- *AMAL THOMAS * ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Load Entire File into memory
Hi, Thanks Alan. Now I have made changes in code : Present code: *f = open(output.txt)content=f.read().split('\n') f.close()for lines in content:* * processing* *content.clear()* Previous code: *f = open(output.txt) content=io.StringIO(f.read()) f.close()for lines in content: processing* *content.close()* Now I have found that memory use is roughly 1.5 times the size of text file. Previously it was around 4-5 times. Its remarkable change. Waiting for more suggestions. Thanks, On Mon, Nov 4, 2013 at 5:05 PM, Alan Gauld alan.ga...@btinternet.comwrote: On 04/11/13 11:07, Amal Thomas wrote: I am currently using this method to load my text file: *f = open(output.txt) content=io.StringIO(f.read()) f.close()* But I have found that this method uses 4 times the size of text file. So why not use f = open(output.txt) content=f.read() f.close() And process the file as a raw string? Is there a reason for using the StringIO? -- 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 -- *AMAL THOMASFourth Year Undergraduate Student Department of Biotechnology IIT KHARAGPUR-721302* ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Load Entire File into memory
Yes I have found that after loading to RAM and then reading lines by lines saves a huge amount of time since my text files are very huge. On Mon, Nov 4, 2013 at 6:46 PM, Alan Gauld alan.ga...@btinternet.comwrote: On 04/11/13 13:06, Amal Thomas wrote: Present code: *f = open(output.txt) content=f.read().split('\n') f.close() If your objective is to save time, then you should replace this with f.readlines() which will save you reprocesasing the entire file to remove the newlines. for lines in content: * processing* *content.clear()* But if you are processing line by line what makes you think that reading the entire file into RAM and then reprocessing it is faster than reading it line by line? Have you tried that on aqnother file and measutred any significant improvement? There are times when reading into RAM is faster but I'm not sure this will be one of them. for line in f: process line may be your best bet. *f = open(output.txt) content=io.StringIO(f.read()) f.close() for lines in content: processing * *content.close()* -- 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 -- *AMAL THOMASFourth Year Undergraduate Student Department of Biotechnology IIT KHARAGPUR-721302* ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Load Entire File into memory
Hi, @Peter: I have checked the execution time manually as well as I found it through my code. During execution of my code, at start, I stored my initial time(start time) to a variable and at the end calculated time taken to run the code = end time - start time. There was a significance difference in time. Thanks, On Mon, Nov 4, 2013 at 7:11 PM, Peter Otten __pete...@web.de wrote: Amal Thomas wrote: Yes I have found that after loading to RAM and then reading lines by lines saves a huge amount of time since my text files are very huge. How exactly did you find out? You should only see a speed-up if you iterate over the data at least twice. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -- *AMAL THOMASFourth Year Undergraduate Student Department of Biotechnology IIT KHARAGPUR-721302* ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Load Entire File into memory
@William: Thanks, My Line size varies from 40 to 550 characters. Please note that text file which I have to process is in gigabytes ( approx 50 GB ) . This was the code which i used to process line by line without loading into memory. *for lines in open('uniqname.txt'): * * processing* On Mon, Nov 4, 2013 at 7:16 PM, William Ray Wing w...@mac.com wrote: On Nov 4, 2013, at 8:30 AM, Amal Thomas amalthomas...@gmail.com wrote: How long are the lines in your file? In particular, are they many hundreds or thousands of characters long, or are they only few hundred characters, say 200 or less? Unless they are so long as to exceed the normal buffer size of your OS's read-ahead buffer, I strongly suspect that the big time sink in your attempt to read line-by-line was some inadvertent inefficiency that you introduced. Normally, when reading from a text file, python buffers the reads (or uses the host OS buffering). Those reads pull in huge chunks of text WAY ahead of where the actual python processing is going on, and are VERY efficient. -Bill -- *AMAL THOMAS* ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Load Entire File into memory
@Dave: thanks.. By the way I am running my codes on a server with about 100GB ram but I cant afford my code to use 4-5 times the size of the text file. Now I am using read() / readlines() , these seems to be more efficient in memory usage than io.StringIO(f.read()). On Mon, Nov 4, 2013 at 9:23 PM, Steven D'Aprano st...@pearwood.info wrote: On Mon, Nov 04, 2013 at 02:48:11PM +, Dave Angel wrote: Now I understand. Processing line by line is slower because it actually reads the whole file. The code you showed earlier: I am currently using this method to load my text file: *f = open(output.txt) content=io.StringIO(f.read()) f.close()* But I have found that this method uses 4 times the size of text file. will only read a tiny portion of the file. You don't have any loop on the read() statement, you just read the first buffer full. So naturally it'll be much faster. Dave, do you have a reference for that? As far as I can tell, read() will read to EOF unless you open the file in non-blocking mode. http://docs.python.org/3/library/io.html#io.BufferedIOBase.read I am of course assuming you don't have a machine with 100+ gig of RAM. There is that, of course. High-end servers can have multiple hundreds of GB of RAM, but desktop and laptop machines rarely have anywhere near that. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -- *AMAL THOMASFourth Year Undergraduate Student Department of Biotechnology IIT KHARAGPUR-721302* ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Load Entire File into memory
@Joel: The code runs for weeks..input file which I have to process in very huge(in 50 gbs). So its not a matter of hours.its matter of days and weeks..I was using C++. Recently I switched over to Python. I am trying to optimize my code to get the outputs in less time and memory efficiently. On Mon, Nov 4, 2013 at 9:57 PM, Joel Goldstick joel.goldst...@gmail.comwrote: If you are new to python why are you so concerned about the speed of your code. You never say how long it takes. Do these files take hours to process? or minutes or seconds?I suggest you write your code in a way that is clear and understandable, then try to optimize it if necessary. -- *AMAL THOMAS* ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Load Entire File into memory
@Steven: Thanks... Right now I cant access the files. I will send you the output when I can. -- Please try this little bit of code, replacing the file name with the actual name of your 50GB data file: import os filename = YOUR FILE NAME HERE print(File size:, os.stat(filename).st_size) f = open(filename) content = f.read() print(Length of content actually read:, len(content)) print(Current file position:, f.tell()) f.close() and send us the output. -- *AMAL THOMAS* ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Load Entire File into memory
@Steven: Thank you...My input data is basically AUGC and newlines... I would like to know about bytearray technique. Please suggest me some links or reference.. I will go through the profiler and check whether the code maintains linearity with the input files. It's probably worth putting some more timing statements into your code to see where the time is going because it's not the reading from the disk that's the problem. The first thing I would do is run the code on three smaller sample files: 50MB 100MB 200MB The time taken should approximately double as you double the size of the file: say it takes 2 hours to process the 50MB file, 4 hours for the 100MB file and 8 hours for the 200 MB file, that's linear performance and isn't too bad. But if performance isn't linear, say 2 hours, 4 hours, 16 hours, then you're in trouble and you *desperately* need to reconsider the algorithm being used. Either that, or just accept that this is an inherently slow calculation and it will take a week or two. Amal, another thing you should try is use the Python profiler on your code (again, on a smaller sample file). The profiler will show you where the time is being spent. Unfortunately the profiler may slow your code down, so it is important to use it on manageable sized data. The profiler is explained here: http://docs.python.org/3/library/profile.html If you need any help, don't hesitate to ask. trying to optimize my code to get the outputs in less time and memory efficiently. Memory efficiency is easy, do it line by line off the disk. This assumes that you can process one line at a time, sequentially. I expect that is not the case. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -- *AMAL THOMAS* ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Which version of python should i use?
hi, I am a beginner. I am using a unix sytem (ubuntu 12.10). Python 2.7.3 is installed in my system. I found out that Python has version upto 3.3.2. Should I update my python version? Is the syntaxes of the each version different? Thanks, Thomas ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Which version of python should i use?
Thank you very much..!! I am starting to learn python for my Bioinformatics work, so I would look for the version that has libraries helpful for me.. On Mon, May 20, 2013 at 6:38 PM, Dave Angel da...@davea.name wrote: On 05/20/2013 05:59 AM, Amal Thomas wrote: hi, I am a beginner. I am using a unix sytem (ubuntu 12.10). Python 2.7.3 is installed in my system. I found out that Python has version upto 3.3.2. Welcome, and thanks for telling us your environment up front. Should I update my python version? No. Your OS has lots of dependencies on that installed Python, and if you remove that one (eg. replace it), many things will stop working. HOWEVER, you can install a second Python, of whatever version, and use that for all your own experimenting and learning. So the question is which one you should use for learning. My comments at the end. Is the syntaxes of the each version different? Yes. Not only syntax but semantics as well. Version 3.0 was deliberately a breaking update, where many of the painful gotchas in the language were fixed, even if it meant things were incompatible. There is a 2to3 utility, but the transition can be painful for large programs. Which one should you learn on? #1 --- if you're committed to a particular tutorial, use the version that matches the tutorial. At your stage, you don't want to have to convert every example in your head before getting it to work. #2 --- If you have a particular library or libraries that you plan to use, and it's only currently available for one version, then use that version. #3 --- If neither of the above apply, then use 3.3 or the soon-coming 3.4. What's different? For a beginner, the most noticeable different is that the print statement in 2.x was replaced by a print function in 3.x For really simple cases, that just means slap a parentheses around the argument(s). But the print statement has syntax for redirecting to a file, while the print function has a parameter. And the technique for suppressing the trailing newline is different. Etc. The second most noticeable difference is that 3.x handles Unicode directly, so that a string is Unicode, and if you want bytes, those are different. -- DaveA __**_ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/**mailman/listinfo/tutorhttp://mail.python.org/mailman/listinfo/tutor -- *AMAL THOMAS Third Year Undergraduate Student Department of Biotechnology IIT KHARAGPUR-721302* ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Random Number Game: Returns always the same number - why?
Mitya, Why is it best in this situation to use range() rather than a while loop? Curious about best practices for the various iterating functions. Thanks! There are a few issues here: * variable names should be lower case * for this case it's best to use for loop with range() * you calculate random number only once, outside of loop Try something like: for count in range(100): print random.randint(1, 100) -m ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] writing effective unittests
* Albert-Jan Roskam fo...@yahoo.com wrote: Hi, I am trying to learn a bit of test-driven programming using unittests and nosetests. I am having trouble finding resources that explain how to write effective tests. I am not a programmer or a student, so I do not have access to collegues or classes. I'm hoping that someone knows of a good tutorial that I've missed. Based on the O'Reilly 2-Part introduction, I hope that learning to write tests will make my code better. I am on the digest version of the list, so I haven't gotten a copy of any replies. Apologies if two copies of my last email hit the list, I'm still learning to use mutt. To partially answer my own question, let me tell you what I've learned in the last 48 hours. It is easy to learn that unittest is the standard testing module in Python 2.6, that it is backported, that it is being improved in Python 3 with new tools. There are a few PyCon videos that discuss this evolution. It is also easy to learn that unittest is based off of prior library for Java (JUnit) and SmallTalk. It is fairly easy to find an introduction to the syntax of writing a test: class blargTest(unittest.TestCase) def testFeature(self): ... do some stuff... assertTrue('blarg', blarg) And there are a few videos available that walk through how to put this together into a test suite. (I've included what I found below, so that this email will have some value to others.) What am I missing? The biggest problem is that no one is explaining the rationale behind testing. The trivial examples compare integers: 2 == 2. At first glance this seems pointless. I had assumed that tests would attempt to confuse my functions and teach me how to write more robust code. But I *think* now that tests are a way to determine if new code has changed old behaviors. Testing 2 == 2 is trivial, but if the function starts returning 3 in a few months, it would be helpful to know right away. In general, though, I'm finding it difficult to conceptualize what my tests should be doing, testing, and telling me about my code. The second problem is complexity. I'll paraphrase a well known saying about regex: I wrote a unittest for my Python code, now I have two problems. Just to test my relatively simple code, I'm trying to do things like create temporary file structures, do some datetime parsing, etc. None of this is easy code for me to write at this stage. When a test fails, it could just as easily be a problem with the test code. (I'm unaccountably reminded about infinite regress here.) I *think* the answer must be that the benefit of writing tests on large, complex projects far outweighs the cost. But I've seen even small projects tout their test coverage. I think what I need is a conceptual shift: how do python programmers use unittests? My next step is to look into buying some real books. Resources Agile Testing Blog: http://agiletesting.blogspot.com/ Tool Taxonomy: http://wiki.python.org/moin/PythonTestingToolsTaxonomy Doug Hellman's Blog: http://www.doughellmann.com/articles/pythonmagazine/completely-different/2008-01-testing-tools/ Unittest Docs: http://docs.python.org/3/library/unittest.html Nose Docs https://nose.readthedocs.org/en/latest/testing.html Fixture Docs http://www.farmdev.com/projects/fixture/index.html PyCon 2010: http://blip.tv/pycon-us-videos-2009-2010-2011/pycon-2010-new-and-improved-coming-changes-to-unittest-the-standard-library-test-framework-52-3283307 PyCon 2011: http://blip.tv/pycon-us-videos-2009-2010-2011/pycon-2011-testing-with-mock-4899484 PyOhio July 2012. This looks perfect except it is missing about half the audio. https://www.youtube.com/watch?v=jTJHQ-zQMk4 Marakana Tech TV: https://www.youtube.com/watch?v=xdY7svOz6n4 At O'Reilly: http://onlamp.com/pub/a/python/2004/12/02/tdd_pyunit.html - Luke Mergner ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] writing effective unittests
Hi, I am trying to learn a bit of test-driven programming using unittests and nosetests. I am having trouble finding resources that explain how to write effective tests. I am not a programmer or a student, so I do not have access to collegues or classes. I'm hoping that someone knows of a good tutorial that I've missed. Based on the O'Reilly 2-Part introduction, I hope that learning to write tests will make my code better. Thanks, -- Luke Thomas Mergner Glendale, CA Sent from Mutt. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Displaying data in columns
I have some data that comes out of a database as a list of tuples of integers and strings, one tuple for each row in the ResultProxy from the select operation. The data looks something like this: [(56, 12, 8, u'2012-02', 10, 12, u'Guangxi Province', u'Guangxi', u'10', 8, u'TOT'), (57, 21, 1, u'2012-03', 36, 21, u'Sichuan EQ Region', u'Sichuan', u'2', 1, u'Basic Medical - Rural')] I would like to display some of the items in the tuples in columnar format with each column lining up on the left side (below should be three neat columns with location, training type, number trained and date): Guangxi ProvinceTOT 10 2012-02 Sichuan EQ Region Basic Medical - Rural 36 2012-03 Surely there is a python module that helps with that, isn't there? I know I could write a function that reads the items, figures string lengths, adds padding white space and prints out the columns but am hoping there is a more elegant solution. I am not against reading documentation, just can't find the right module to read about. thomas ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] How do you save work in progress in Pyscripter ?
Please help a newbie Was able to write and successfully run this but I can't seem to be able to save it Luckily I had saved it to Word and then I was able to copy and paste it back into PyScripter. I'm using Python Scripter Version 2.5.3.0 x86 *** Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32. *** *** Remote Python engine is active *** from decimal import * getcontext() Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-9, Emax=9, capitals=1, flags=[], traps=[DivisionByZero, InvalidOperation, Overflow]) getcontext().prec=3#change decimal precision to 3 decimal places for a in xrange(1,30): #NESTED note no matter what the variables are the syntax is always xrange ... for b in xrange(1,30): #LOOPS DO 29 ITERATIONS ... c=pow(a,2)+pow(b,2)# this is really c squared because a and b are raised to exponent 2 ... h=pow(c,.5) #pow is .5 so h is the square root of c ...h is the hypotenuse ... d=round(h,2) ... if a==1 and b==1: #will allow titles to be printed at beginning of print out ... print Side a,Side b,Hypotenuse ... if h==d and d==h:#will eliminate all values of h that are not integers from printout ... print ,a,\t,b,\t\t,h #for alignment purpose 3 spaces before a then tab b, and 2tabs ... # before h Side a Side b Hypotenuse 3 4 5.0 4 3 5.0 5 1213.0 6 8 10.0 7 2425.0 8 6 10.0 8 1517.0 9 1215.0 102426.0 125 13.0 129 15.0 121620.0 158 17.0 152025.0 161220.0 182430.0 201525.0 202129.0 212029.0 212835.0 247 25.0 241026.0 241830.0 282135.0 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Datetime objects
Hi, I am having trouble comparing two datetime objects. Using Sqlalchemy I save a string as a date into an sqlite field (which has no native date format, I gather). import datetime as dt date_obj = dt.datetime.strptime(date_string,'%m.%d.%Y') I want to compare that date later with an inputed date, which I created with strptime(). This function is only available for datetime.datetime.strptime() not datetime.date compare_date = dt.datetime.strptime('2011-01-27', '%Y-%m-%d') print compare_date datetime.datetime(2012, 1, 27, 0, 0) Despite the fact that I don't care about the time fields, they still get added. It appears that I can get at the date object returned in an sqlalchemy object: for row in query_object: ... type(row.date) ... 2012-03-16 19:18:18,420 INFO sqlalchemy.engine.base.Engine SELECT posts.date AS posts_date FROM posts 2012-03-16 19:18:18,420 INFO sqlalchemy.engine.base.Engine () type 'datetime.date' type 'datetime.date' type 'datetime.date' But when I compare them, it always returns false because datetime.date does not seem to compare to datetime.datetime... for row in q1: ... print type (row.date), row.date, ' vs ', type(compare_date), compare_date, row.date == compare_date ... 2012-03-16 19:33:56,011 INFO sqlalchemy.engine.base.Engine SELECT posts.date AS posts_date FROM posts 2012-03-16 19:33:56,011 INFO sqlalchemy.engine.base.Engine () type 'datetime.date' 2011-11-05 vs type 'datetime.datetime' 2012-01-27 00:00:00 False type 'datetime.date' 2011-11-29 vs type 'datetime.datetime' 2012-01-27 00:00:00 False type 'datetime.date' 2011-12-23 vs type 'datetime.datetime' 2012-01-27 00:00:00 False type 'datetime.date' 2012-01-18 vs type 'datetime.datetime' 2012-01-27 00:00:00 False type 'datetime.date' 2012-01-17 vs type 'datetime.datetime' 2012-01-27 00:00:00 False type 'datetime.date' 2012-01-27 vs type 'datetime.datetime' 2012-01-27 00:00:00 False type 'datetime.date' 2012-01-14 vs type 'datetime.datetime' 2012-01-27 00:00:00 False Can anyone help me out here? Thanks in advance. PS: I'm asking here since I think this is a simple object comparison question, not a question specific to a library (sqlalchemy). If it matters, I'm playing around with a small web log application built on Werkzeug, Sqlalchemy, and Jinja2. I'm actually very impressed with the progress I've made. Luke Mergner Mechanicsville, MD lmerg...@gmail.com___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] creating dict of dict : similar to perl hash of hash
On Tue, Mar 6, 2012 at 8:19 PM, David Rock da...@graniteweb.com wrote: * Abhishek Pratap abhishek@gmail.com [2012-03-06 09:50]: Hi Guys I am looking for a way to build dictionaries of dict in python. For example in perl I could do my $hash_ref = {}; $hash-{$a}-{$b}-{$c} = value; if (exists $hash-{$a}-{$b}-{$c} ){ print found value} Can I do something similar with dictionaries in Python. Absolutely. Python is very good at using nested dicts. dict = {} dict['a'] ={} dict['a']['b'] = {} dict['a']['b']['c']= value This is a bit brute force, but it illustrates that the intermediary keys need to exist. ie, if you try to assign directly, it won't work: Type help, copyright, credits or license for more information. dict ={} dict['a']['b']['c'] = 'value' Traceback (most recent call last): File stdin, line 1, in module KeyError: 'a' Since the key 'a' doesn't exist, it throws an exception. Python is also more flexible than perl in nesting data because it doesn't have to be the same data type. You can nest variables, lists, dicts, etc all at the same level: dict = {} dict['mylist'] = [1,2,3] dict['mystring'] = 'string' dict['mynum'] = 4 dict['anotherdict'] = {} dict['anotherdict']['anotherstring'] = 'string2' Hi David, Mixed data types in nested data structure are possible in Perl as well: %hash = (); $hash{'mylist'} = [1,2,3]; $hash{'mystring'} = 'string'; $hash{'mynum'} = 4; $hash{'anotherhash'} = {}; $hash{'anotherhash'}{'anotherstring'} = 'string2'; Thomas ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Debugging While Loops for Control
-- Message: 1 Date: Wed, 15 Feb 2012 23:57:08 -0500 From: Luke Thomas Mergner lmerg...@gmail.com To: tutor@python.org Subject: [Tutor] Debugging While Loops for Control Message-ID: a8bdf988-fe78-4ca1-8cb7-c0a0e68fd...@gmail.com Content-Type: text/plain; charset=us-ascii Hi, I've been translating and extending the Blackjack project from codeacademy.com into Python. My efforts so far are here: https://gist.github.com/1842131 My problem is that I am using two functions that return True or False to determine whether the player receives another card. Because of the way it evaluates the while condition, it either prints too little information or previously called the hitMe() function too many times. I am assuming that I am misusing the while loop in this case. If so, is there an elegant alternative still running the functions at least once. e.g. while ask_for_raw_input() AND is_the_score_over_21(): hitMe(hand) Any advice or observations are appreciated, but please don't solve the whole puzzle for me at once! And no, not all the functionality of a real game is implemented. The code is pretty raw. I'm just a hobbyist trying to learn a few things in my spare time. Thanks in advance. Luke -- Message: 2 Date: Thu, 16 Feb 2012 09:05:39 + From: Alan Gauld alan.ga...@btinternet.com To: tutor@python.org Subject: Re: [Tutor] Debugging While Loops for Control Message-ID: jhigt3$jdp$1...@dough.gmane.org Content-Type: text/plain; charset=ISO-8859-1; format=flowed On 16/02/12 04:57, Luke Thomas Mergner wrote: My problem is that I am using two functions that return True or False to determine whether the player receives another card. Because of the way it evaluates the while condition, it either prints too little information or previously called the hitMe() function too many times. I am assuming that I am misusing the while loop in this case. while ask_for_raw_input() AND is_the_score_over_21(): hitMe(hand) I haven't looked at the code for the functions but going by their names I'd suggest you need to reverse their order to while is_the_score_over_21() and ask_for_raw_input(): hitMe(hand) The reason is that the first function will always get called but you (I think) only want to ask for, and give out, another card if the score is over 21 (or should that maybe be *under* 21?). Personally I would never combine a test function with an input one. Its kind of the other side of the rule that says don't don;t put print statements inside logic functions. In both cases its about separating himan interaction/display from program logic. So I'd make the ask_for_raw_input jusat return a value(or set of values) and create a new funtion to test the result and use that one in the while loop. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ Alan (and list), Thanks for the advice. It at least points me to an answer: I'm trying to be too clever for my experience level. I am going to go back and incorporate your suggestions. In the meantime, and continuing my problem of over-cleverness, I was trying to rethink the program in classes. With the caveat that I'm only a few hours into this rethinking, I've added the code below. My question is: when I want to build in a return self into the Hand class, which is made up of the card class; how do I force a conversion from card object into integer object which is all the card class is really holding? Should I make the class Card inherit from Integers? or is there a __repr__ def I don't understand yet? Bonus question: when I create a the def score(self) in class Hand, should that be an generator? And if so where do I go as a newb to understand generators? I'm really not understanding them yet. The x for x in y: syntax makes it harder to follow for learners, even if I appreciate brevity. Thanks in advance, Luke class Card(object): def __init__(self): self.score = self.deal() def deal(self): deal a card from 1 to 52 and return it's points return self.getValue(int(math.floor(random.uniform(1, 52 def getValue(self, card): Converts the values 1 - 52 into a 1 - 13 and returns the correct blackjack score based on remainder. if (card % 13 == 0 or card % 13 == 11 or card % 13 == 12): #Face Cards are 10 points return 10 elif (card % 13 == 1): return 11 else: #Regular cards, return their value return card % 13 def showCard(self): return repr(self.score) class Hand: def __init__
[Tutor] Debugging While Loops for Control
Hi, I've been translating and extending the Blackjack project from codeacademy.com into Python. My efforts so far are here: https://gist.github.com/1842131 My problem is that I am using two functions that return True or False to determine whether the player receives another card. Because of the way it evaluates the while condition, it either prints too little information or previously called the hitMe() function too many times. I am assuming that I am misusing the while loop in this case. If so, is there an elegant alternative still running the functions at least once. e.g. while ask_for_raw_input() AND is_the_score_over_21(): hitMe(hand) Any advice or observations are appreciated, but please don't solve the whole puzzle for me at once! And no, not all the functionality of a real game is implemented. The code is pretty raw. I'm just a hobbyist trying to learn a few things in my spare time. Thanks in advance. Luke ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Testing dymamically created methods
Hi all, I would like to use some existing tool like py.test or nose to run my tests, but I failed to do so. The problem is as follow. I have tests: ### test_methods.py ### def test_one(): assert 1 == 1 def test_two(): assert 1 == 1 # I have abstraction layer that keeps information about this test, like method name. It's simple JSON file. Then I have the test runner: ### test_runner.py ### def read_test_definition(): read the JSON file and returns dict with test details def test_run(): my_test_data = read_test_definition() import test_methods for testid in my_test_data: my_method = my_test_data[testid] # here the 'my_method' is equal 'test_one' or 'test_two', hope it's clear.. test_method = getattr(test_methods, my_method) test_method() ### This code works without py.test or nosetests. For example if I use print instead of 'assert'. Both py.test and nosetests failed to execute this correctly. Or maybe they do execute it correctly, I just don't understand it..:) They both report only single test was executed. I would like to see test report for each method executed in 'for' loop. Is it possible? PS. Sorry for my ignorance, I just started to learn Python last week. Thanks, Thomas ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Testing dymamically created methods
On Tue, Jan 10, 2012 at 3:31 PM, Walter Prins wpr...@gmail.com wrote: Hi, On 10 January 2012 12:15, Thomas Maier hay...@gmail.com wrote: This code works without py.test or nosetests. For example if I use print instead of 'assert'. Both py.test and nosetests failed to execute this correctly. Or maybe they do execute it correctly, I just don't understand it..:) They both report only single test was executed. I would like to see test report for each method executed in 'for' loop. Is it possible? For nose, I *think* you can basically achieve what you want by turning test_run() into a generator (by essentially replacing the call to the test_method() with a suitable yield statement. See here: http://readthedocs.org/docs/nose/en/latest/writing_tests.html#test-generators Works perfect. Additionally you might also look at the TestLoader functionality for taking further control over how and where your tests are loaded, e.g. see for example nose.loader.loadTestsFromGenerator() or nose.loader.loadTestsFromGeneratorMethod() (or indeed all the other methods) here: http://readthedocs.org/docs/nose/en/latest/api/loader.html Will try later. HTH, my $0.02 worth, Walter Thank you very much! Thomas ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Wading through traceback output
I have a script that I used to be quite proud of, up until today it was working great. Basically it reads in a directory tree of spreadsheets, extracts info from them then makes a new spreadsheet to output the info to. The spreadsheets are xls files so it uses xlrd and xlwt to manage the data extraction and spreadsheet creation. Today when I ran it (after a hiatus of about 3 months) I got this output: Traceback (most recent call last): File ./cttOverviewMain.0.03.2011.py, line 294, in module monthData(searchList) File ./cttOverviewMain.0.03.2011.py, line 261, in monthData writeMonthlyHeader(writeSheet) File ./cttOverviewMain.0.03.2011.py, line 183, in writeMonthlyHeader sh.write(7,10,# Locations,xlwt.easyxf('font: bold True')) File /usr/local/lib/python2.6/dist-packages/xlwt/Worksheet.py, line 1003, in write self.row(r).write(c, label, style) File /usr/local/lib/python2.6/dist-packages/xlwt/Row.py, line 227, in write style_index = self.__parent_wb.add_style(style) File /usr/local/lib/python2.6/dist-packages/xlwt/Workbook.py, line 303, in add_style return self.__styles.add(style) File /usr/local/lib/python2.6/dist-packages/xlwt/Style.py, line 90, in add return self._add_style(style)[1] File /usr/local/lib/python2.6/dist-packages/xlwt/Style.py, line 149, in _add_style raise ValueError(More than 4094 XFs (styles)) ValueError: More than 4094 XFs (styles) I don't understand this very well at all - any pointers are appreciated. I think what it is saying is that there is a problem with my Python libraries but this is not a problem I have ever seen before. Is it possible the 2.6 libraries were updated in the hiatus time causing this problem? If so any ideas on how I can investigate fixing this are appreciated. thomas ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Wading through traceback output :p:
On Mon, 26 Dec 2011 07:10:45 -0500 Alan Gauld alan.ga...@btinternet.com wrote: On 26/12/11 11:42, Thomas C. Hicks wrote: Given it was working before and not now the obvious question is what has changed? It looks like you are on a Linux box so do you have automatic updates switched on? Or do you always just accept the recommendation to update? In which case try looking at the modification dates of the library files Also has the verion of Excel used to create the files changed? It looks like the point that the program leaves your code is here: File ./cttOverviewMain.0.03.2011.py, line 183, in writeMonthlyHeader sh.write(7,10,# Locations,xlwt.easyxf('font: bold True')) So that points the finger at the xlwt module. If it has been updated has the format of that call changed - to a dictionary/tuple of values for example? These are all guesses but might give you a starting point. Incidentally cttOverviewMain.0.03.2011.py seems like a bizarre name for a file? I assume that's the date or somesuch? What is the thinking behind that? Thanks so much for the input Alan, guesses on your part are far better than the ignorance on my part. I do get automatic updates (though xlwt is not part of that, OpenOffice and its xls writing is), will have to look at that. Also appreciate the thoughts about the file name. This is my first big project and I still have much to learn. If you can point me to a discussion of file naming when there are multiple files involved in a project I am game to do some reading! thomas ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Assigning range :p:
On Wed, 27 Jul 2011 20:16:31 -0400 Alexander Quest alexxqu...@gmail.com wrote: Does anyone know how to assign a certain numerical range to a variable, and then choose the number that is the middle of that range? For example, I want to assign the variable X a range between 1 and 50, and then I want to have the middle of that range (25) return with some command when I call it (perhaps rangemid or something like that?). In pseudocode, I am trying to say X = range [1,50], return middle of range (which should return 25) but I don't know how to code it. This is for a basic program I'm trying to write where the player thinks of a number and the computer tries to guess the number in as few tries as possible. Thanks for any help! -Alex There are probably better ways but this worked for me: x=range(1,50) mid=x[len(x)/2] You do have to keep in mind the way python counts list indices for a range call - i.e. x=range(1,50) will give you a list with all numbers 1 to 49 in it. Hope that helps! tom ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Logger object not passed between modules
Hi, Python 2.7.2 wxPython 2.9.1.1 OS X 10.7 I am very new to Python and programming, basically just a curious hobbyist. I am building a learning app that hopefully will include a wxPython GUI. Right now I am trying to understand my code better by including print statements. Now I know that I could just print to the terminal, but I thought 'why not try this nice little logger class.' And it works perfectly in the main class App(wx.App), but I can't seem to pass the same logger object to the imported modules. I'm verifying this by printing the logger object to terminal (stdout?). I've spent close to 6 hours trying to figure this out, and I need some help. The logger object is created within a function in the main app class. Is this wrong? I thought that logger ensured the same object is used by both classes. The logger.getLogger(__name__) doesn't set anything other than the name used to describe the source of the message, so how do I make sure I'm using the same log object? I assume the problem is either scope (the log has to be in the module, not the class) or passing the object properly, neither of which Im very comfortable with obviously. Thanks in advance. Code snippets and prints follow. Luke # File / module one. import FrameMaker # instantiates the subclassed wx.Frame object and fills it. class App(wx.App): def __init__(self) self.logger = self.Log() def Log(self): appName = 'wxNew' # I thought this line would make it easier to 'refactor' I hear people care about that. logfile = ''.join([appName, '.log']) #Look, I learned to use the .join() function! if not os.path.exists(log file): # some examples I saw suggest logger handles this file check. f = open(logfile, 'w') f.close() logger = logging.getLogger('Main') logger.setLevel(logging.DEBUG) fh = logging.FileHandler(logfile) fh.setLevel(logging.DEBUG) # If I only want one log, do I need to create a special handler 'fh'? format = logging.Formatter(%(asctime)s - %(name)s - %(levelname)s - %(message)s) fh.setFormatter(format) logger.addHandler(fh) logger.info('Starting log... ') return logger # File / Module two class myFrame(wx.Frame): def __init__(self, parent, id=-1, label=, size=(300, 500)): #set the name of the logger. self.logger = logging.getLogger('Frame') # The argument shouldn't matter, as I follow the examples. print self.logger self.logger.info('In frame __init__, the size is : ', self.GetSize) $ python app.py logging.Logger object at 0x105a1a110 logging.Logger object at 0x105a1a450 --The log prints -- 2011-07-26 01:39:07,642 - Main - INFO - Starting log... 2011-07-26 01:39:11,078 - Main - INFO - Shutting down main app. Luke Thomas Mergner Mechanicsville, MD lmergner.blogspot.com lmerg...@gmail.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] IDLE/tk in 10.6
Hi, I am not a professional programmer, but just trying to learn. I'm running Mac 10.6 Snow Leopard. I used MacPorts to install python26, python27, and python3. My python interpreter loads 2.7.2 after I ran the python_select command, which is added via MacPorts I think. I'd like to try IDLE but there appears to be a known bug with 10.6's version of ActiveTCL. I've installed a newer version 8.5 via their website, but this has not fixed the problem. The module tkinter is still unable to load. Since both python and activeTCL are installed as Frameworks on my mac, I wonder if I need to tell python27 that there is another Tkinter installed elsewhere. Can anyone give me some advice? import Tkinter Traceback (most recent call last): File stdin, line 1, in module File /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py, line 39, in module import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named _tkinter Luke Mergner lmerg...@gmail.com___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] voluntary work :p:
On Mon, 25 Apr 2011 15:09:02 -0400 Rafael Durán Castañeda rafadurancastan...@gmail.com wrote: I recommend you visit www.pythonchallenge.comhttp://www.pythonchallenge.com On 25/04/11 20:42, Wolf Halton wrote: Learn Python the Hard Way is pretty cool. I am always looking for books that lay it out well. Thanks for mentioning it, and good luck with your studies. I find that having a project that is a little beyond me helps me get better at coding. -Wolf On Mon, Apr 25, 2011 at 1:33 PM, Alan Gauld alan.ga...@btinternet.commailto:alan.ga...@btinternet.com wrote: Edgar Almonte samud...@gmail.commailto:samud...@gmail.com wrote is i want learn i read a bit and do some exercises but i am the kind of ppl that need saw the path that will walk so need a route and a little of guide to keep going , Have you looked at the python web site? There is a whole section dedicated to tutorials for people who have never programmed before. Take a look at a few and choose the one you like - ie the one that aseems to make most sense to you.. HTH, I second the recommendation to try out Python Challenge - outstanding way to learn (at least for me). Another option is to visit Sourceforge.net and look for python projects still in development. Open source pojects seem to always need bug finders and smashers as well as beta testers and I suspect most any of them would appreciate free help! tom ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] While Loops: Coin Flip Game :p:
On Sun, 14 Nov 2010 17:16:36 -0500 Dawn Samson sd...@live.ca wrote: Greetings, I'm a Python beginner and working my way through Michael Dawson's Python Programming for the Absolute Beginner. I'm stuck in a particular challenge that asks me to write a program that flips a coin 100 times and then tells you the number of heads and tails. I've been trying to work on this challenge for a while now and can't get it to work (either it has 100 heads or 100 tails). I've been reworking this code many times and currently what I have does not do anything at all at IDLE. Please take a look at my code below: import random # set the coin coin = random.randrange(2) headsCount = 0 tailsCount = 0 count = 0 # the loop while count = 100: coin if coin == 0: headsCount += 1 if coin == 1: tailsCount += 1 count += 1 print The number of heads was, heads print The number of tails was, tails raw_input(\n\nPress the enter key to exit.) Thanks, S. Dawn Samson From one beginner to another - it looks to me like you set the value of coin once then checked it 100 times. If you want to reset the value of coin maybe it (i.e. setting the value of coin, not just calling the value of coin) should be in the loop too? tom ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] monodevelop 2.2
I was wondering if someone could tell me if you can use the gui designer in monodevelop 2.2+ with python. Thanks, Thomas ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] string to list
On Thu, 5 Aug 2010 03:40:55 -0400 Sander Sweers sander.swe...@gmail.com wrote: On 5 August 2010 06:38, Vikram K kpguy1...@gmail.com wrote: Suppose i have this string: z = 'AT/CG' How do i get this list: zlist = ['A','T/C','G'] If you know the format of the string is always the same you can do something like this. This fails when you have strings that do not have the '/' in the middle and has 2 characters on either side. def parseString(s): n = s.find('/') l = [] if n: l = [s[0],s[n-1:n+2], s[-1]] return l parseString(s) ['A', 'T/C', 'G'] Greets Sander Much better than my original thought on this! If the data is stereotypic couldn't you simplify it though? ... z='AT/CG' zlist=[z[0],z[1:4],z[-1]] tom ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to do excel in python
On Thu, 5 Aug 2010 10:08:59 -0400 invincible patriot invincible_patr...@hotmail.com wrote: hi, can any one tell me how can I access MS excel worksheet in python and how can I access itz individual cells..?? I have had good luck with the xlrd and xlwt modules, you can get them at www.python-excel.org. The Google Group for those packages is reasonably helpful as well. tom ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help return a pattern from list
On Mon, 05 Jul 2010 20:29:02 +0200 tutor-requ...@python.org wrote: Date: Mon, 5 Jul 2010 13:54:55 -0400 From: Vineeth Rakesh vineethrak...@gmail.com To: tutor@python.org Subject: [Tutor] Help return a pattern from list Message-ID: aanlktimtfl0hdrjqrrzjxsyv8vebwehpvz_qdcjg4...@mail.gmail.com Content-Type: text/plain; charset=iso-8859-1 Hello all, Can some one help me to return a special pattern from a list. say list = [something1.mp3,something2.mp3,something4.pdf,something5.odt] now say I just need to return the files with .mp3 extension. How to go about doing this? Thanks Vin I use the fnmatch module: import fnmatch fileList = [something1.mp3,something2.mp3,something4.pdf,something5.odt] pattern='*.mp3' for x in fnmatch.filter(fileList,pattern): #do something to your files or list items here thomas ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Suggestions for output on multiple platforms
I am a beginner at all this and never expected to reach a point where people other than myself may have to have access to the output of one of my programs. My problem is this - I have written a program that uses xlrd to read a series of xls files and collate and summarize the data. My original plan was to then write out that data into another xlwt spreadsheet that could be updated on a regular basis. I was thinking of adding a page per month as the data is updated regularly. The problem is that xlwt doesn't allow for very convenient addition of data to a spreadsheet - basically it has to re-create the whole spreadsheet each time. So now I am looking for suggestions of how I can output my data analysis. I am running Linux but the data needs to be able to be seen by users of OSX and Windows. I have been reading about GTK and figure I could output the analysis using that but am not sure it will be readable under Mac and Windows. Any ideas are welcome! thomas ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Iterating through a list of strings
Wow, this is great! I appreciate all the pointers, lots to keep learning here. thomas ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Iterating through a list of strings
I am using Python 2.6.4 in Ubuntu. Since I use Ubuntu (with its every 6 months updates) and want to learn Python I have been working on a post-install script that would get my Ubuntu system up and running with my favorite packages quickly. Basically the script reads a text file, processes the lines in the file and then does an apt-get for each line that is a package name. The text file looks like this: %Comment introducing the next block of packages %Below are the packages for using Chinese on the system %Third line of comment because I am a verbose guy! ibus-pinyin ibus-table-wubi language-pack-zh-hans etc. I read the lines of the file into a list for processing. To strip out the comments lines I am using something like this: for x in lines: if x.startswith('%'): lines.remove(x) This works great for all incidents of comments that are only one line. Sometimes I have blocks of comments that are more than one line and find that the odd numbered lines are stripped from the list but not the even numbered lines (i.e in the above block the line %Below are the ... line would not be stripped out of the list). Obviously there is something I don't understand about processing the items in the list and using the string function x.startswith() and the list function list.remove(). Interestingly if I put in print x in place of the lines.remove(x) line I get all the comment lines printed. Can anyone point me in the right direction? thomas ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Saving class instances
On 13 Jul 2009, at 22:04, Alan Gauld alan.ga...@btinternet.com wrote: That's one way and you can find an example and some advice on how to handle subclassing in the OOP topic of my tutor. Wow; thanks! That tutorial was really useful, I will have to check out the rest of the site now. I am sure this has an obvious and easy answer but I just cannot find it anywhere! Actually no. Saving and retrieving object instances (known as persisting objects in OOP speak) was one of the biggest challenges facing the OOP paradigm when it got started in the real world. Many different solutions have evolved from flat text files to dedicated Object databases, and everyting in between, but it remains a task frought with difficulty, especially on large scale projects. Good to know I wasn't being totally dense. Now that I have got the pickle thing under my belt I am going to have a go at sqllite. Thanks again everybody. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Saving class instances
Hi everyone, I am new to Python (and to programming) and, now that I have worked through most of Learning Python, I have set myself the exercise of writing a little text-based program to catalogue the contents of my CD collection. I have written enough code to allow me to create instances of an Album class with attributes like name, artist, year etc. However, I am at a loss as to how to save these instances so that they can be retrieved the next time I run the program. I assume I need to write them to a file somehow, and while I know how to write and read to and from files, I do not know how to write instances. I am sure this has an obvious and easy answer but I just cannot find it anywhere! If anybody could help I would be most grateful. Tom On 13 Jul 2009, at 14:44, tutor-requ...@python.org wrote: Send Tutor mailing list submissions to tutor@python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-requ...@python.org You can reach the person managing the list at tutor-ow...@python.org When replying, please edit your Subject line so it is more specific than Re: Contents of Tutor digest... Today's Topics: 1. Re: for statement with addition ... (Rommel Asibal) 2. Re: for statement with addition ... (Kent Johnson) 3. Xampp Python (Rommel Asibal) 4. Re: thesaurus (Dave Angel) 5. Re: for statement with addition ... (Dave Angel) 6. Re: for statement with addition ... (Markus Hubig) -- Message: 1 Date: Mon, 13 Jul 2009 05:22:28 -0600 From: Rommel Asibal rumzs...@gmail.com To: Markus Hubig mhu...@gmail.com Cc: tutor@python.org Subject: Re: [Tutor] for statement with addition ... Message-ID: de6a4e6f0907130422x2e1e5bf6n3fcfff4d4739e...@mail.gmail.com Content-Type: text/plain; charset=iso-8859-1 Markus, That looks like a typo. remove it and it should work. On Mon, Jul 13, 2009 at 4:50 AM, Markus Hubig mhu...@gmail.com wrote: Hi @all, within diveintopython I often found a for-statement like this: f for f in bla: print f So what actually is the first f for ... is it just to declare f before starting the for loop? I can't find any information on python.org and it's hard to google this kinda stuff. - Markus -- ---it's like this-- even samurai have teddy bears and even teddy bears get drunk ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- next part -- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20090713/ad0174f6/attachment-0001.htm -- Message: 2 Date: Mon, 13 Jul 2009 07:37:45 -0400 From: Kent Johnson ken...@tds.net To: Markus Hubig mhu...@gmail.com Cc: tutor@python.org Subject: Re: [Tutor] for statement with addition ... Message-ID: 1c2a2c590907130437y4f19d357r811d0c956b53e...@mail.gmail.com Content-Type: text/plain; charset=ISO-8859-1 On Mon, Jul 13, 2009 at 6:50 AM, Markus Hubigmhu...@gmail.com wrote: Hi @all, within diveintopython I often found a for-statement like this: f for f in bla: ??? print f So what actually is the first f for ... is it just to declare f before starting the for loop? I can't find any information on python.org and it's hard to google this kinda stuff. That is not Python, maybe a copy/paste artifact? Omit the initial 'f '. Can you point to an example on the web site or in the printed book? Kent -- Message: 3 Date: Mon, 13 Jul 2009 05:56:46 -0600 From: Rommel Asibal rumzs...@gmail.com To: Python Tutor List tutor@python.org Subject: [Tutor] Xampp Python Message-ID: de6a4e6f0907130456t491ea967i40ab083aebdda...@mail.gmail.com Content-Type: text/plain; charset=iso-8859-1 Hello All, I am trying to go through the Python Power! book and i am at the part where i need to setup a web server. I am thinking of using XAMPP and have checked its site and wanted to try using mod_python. I am using Python 3.1 but from initial looks it seems mod_python doesnt support it, could someone verify if that is correct? Does that mean i have to go to python 2.6 for it to work? Thanks! -- next part -- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20090713/5925e053/attachment-0001.htm -- Message: 4 Date: Mon, 13 Jul 2009 07:57:54 -0400 From: Dave Angel da...@ieee.org To: Pete Froslie fros...@gmail.com Cc: Alan Gauld alan.ga...@btinternet.com, tutor@python.org, Dave Angel da...@ieee.org Subject: Re: [Tutor] thesaurus Message-ID: 4a5b2142.7080...@ieee.org Content-Type: text/plain; charset=UTF-8; format=flowed Pete Froslie wrote:
Re: [Tutor] Saving class instances
I think I will give both approaches a go, since this is just a learning exercise anyway. Thanks very much for your help. Oh, and sorry for accidentally quoting the whole digest last time. Won't happen again! Tom On 13 Jul 2009, at 17:53, tutor-requ...@python.org wrote: I think you are better off using a database in this situation, sqlite3 is a good choice since no extra setup is required. See http://docs.python.org/library/sqlite3.html And to answer your question, the python pickle module can save class instances, see http://docs.python.org/library/pickle.html Regards, Daniel Woodhouse ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Building VST's with Python
I'm new to python but do have a little programming knowledge with C++I got into programming so I could build Virtual Instruments because I love the world of sound and creating instruments that shape it...I have tried to find a program that would be an ideal vehicle for this task...I've narrowed it down to Delphi or PythonC++ would take too long for me to learn and would take to long to build an application...I was wondering if you could direct me to some tutorials or source code that might involve building virtual instruments or even gamesThanks for listening, Logan ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Lucky Boy Sudhir wants to chat
Thank you Tom -Original Message- From: Kent Johnson [mailto:ken...@tds.net] Sent: Wednesday, December 17, 2008 6:52 AM To: Lucky Boy Sudhir Cc: tutor@python.org Subject: Re: [Tutor] Lucky Boy Sudhir wants to chat I have unsubscribed Lucky Boy from the list as he is just spamming it. Kent On Wed, Dec 17, 2008 at 7:01 AM, Lucky Boy Sudhir sudhir.tact@gmail.com wrote: --- Lucky Boy Sudhir wants to stay in better touch using some of Google's coolest new products. If you already have Gmail or Google Talk, visit: http://mail.google.com/mail/b-4696b4693-d5d69810df-aafd3a6b94976b5f You'll need to click this link to be able to chat with Lucky Boy Sudhir . To get Gmail - a free email account from Google with over 2,800 megabytes of storage - and chat with Lucky Boy Sudhir , visit: http://mail.google.com/mail/a-4696b4693-d5d69810df-ee3cdf55e5 Gmail offers: - Instant messaging right inside Gmail - Powerful spam protection - Built-in search for finding your messages and a helpful way of organizing emails into conversations - No pop-up ads or untargeted banners - just text ads and related information that are relevant to the content of your messages All this, and its yours for free. But wait, there's more! By opening a Gmail account, you also get access to Google Talk, Google's instant messaging service: http://www.google.com/talk/ Google Talk offers: - Web-based chat that you can use anywhere, without a download - A contact list that's synchronized with your Gmail account - Free, high quality PC-to-PC voice calls when you download the Google Talk client Gmail and Google Talk are still in beta. We're working hard to add new features and make improvements, so we might also ask for your comments and suggestions periodically. We appreciate your help in making our products even better! Thanks, The Google Team To learn more about Gmail and Google Talk, visit: http://mail.google.com/mail/help/about.html http://www.google.com/talk/about.html (If clicking the URLs in this message does not work, copy and paste them into the address bar of your browser). ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] XML to text
This might be helpful: http://www.boddie.org.uk/python/XML_intro.html Have fun! Thomas Dinesh B Vadhia schrieb: I have a large number of xml files that I want to convert into text format. What is the best and easiest way to do this? Thanks! Dinesh ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Decimals 'not equal to themselves' (e.g. 0.2 equals 0.200000001)
CNiall wrote: I want to make a simple script that calculates the n-th root of a given number (e.g. 4th root of 625--obviously five, but it's just an example :P), and because there is no nth-root function in Python I will do this with something like x**(1/n). Side note: of course there are python built-in ways to do that. You just named one yourself: In [6]: 625**(1.0/4) Out[6]: 5.0 also: In [9]: pow(625, 1.0/4) Out[9]: 5.0 However, with some, but not all, decimals, they do not seem to 'equal themselves'. As you can see, the last two decimals are very slightly inaccurate. However, it appears that when n in 1/n is a power of two, the decimal does not get 'thrown off'. How might I make Python recognise 0.2 as 0.2 and not 0.20001? You just can't store 0.1 as a binary floating point. You might want to read: http://www.network-theory.co.uk/docs/pytut/FloatingPointArithmeticIssuesandLimitations.html http://www.network-theory.co.uk/docs/pytut/RepresentationError.html The decimal module provides decimal floating point arithmetic: http://docs.python.org/lib/module-decimal.html like in: In [1]: 0.2 * 2 Out[1]: 0.40002 In [2]: from decimal import Decimal In [3]: Decimal('0.2') * 2 Out[3]: Decimal(0.4) thomas ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unable to Reconfigure IDLE
On Jul 27, 2008, at 7:16 AM, Tim Golden wrote: Thomas Corbett wrote: On Jul 26, 2008, at 9:02 AM, Alan Gauld wrote: Thomas Corbett [EMAIL PROTECTED] wrote Configured shell window to wrong size, now can't seem to find the menu (Options Configure) to resize the shell. Don't you just resize it then close it and the next time it opens it uses the new size? Thats how I thought it was supposed to work! Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor The window is too large to resize. I missed the beginning of this thread, but I assume that you mean its edges are off the visible screen so you can't use the mouse to grab the frame and resize it? If so, and if you're on Windows, you can resize with the keyboard: Alt-Space S will put you in Sizing mode; then use the cursor keys to move the edges in and out. Alternatively, Alt -Space M will put the window in Moving mode and, again, the cursor keys can be used to bring a corner into view and into range of the mouse. TJG ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor Running IDLE 1.2.2 under MacPython 2.5 on Mac OS X 5.1. Not aware of a similar option on Mac. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Unable to Reconfigure IDLE
Running IDLE 1.2.2 under MacPython 2.5 on Mac OS X 5.1. Configured shell window to wrong size, now can't seem to find the menu (Options Configure) to resize the shell. Tried going to username Library Preferences and removing org.python* files, but that did not work. Thanks! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unable to Reconfigure IDLE
On Jul 26, 2008, at 9:02 AM, Alan Gauld wrote: Thomas Corbett [EMAIL PROTECTED] wrote Configured shell window to wrong size, now can't seem to find the menu (Options Configure) to resize the shell. Don't you just resize it then close it and the next time it opens it uses the new size? Thats how I thought it was supposed to work! Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor The window is too large to resize. -Tom ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] listing classes
Hi, dir(A) will essentially give you what you want (and a little more) If you're only interested in classes, you can do something like: import types [ name for name in dir(A) if type(eval('A.'+name)) == types.ClassType ] Thomas Laureano Arcanio wrote: Hi All, I need to have a listing of all classes defined inside a class body, something like this: class A(object): class B(object): pass class C(object): pass(object): and i need to get the classes to instantiate them.. something like this. classes =[A,B] Any ideas ? do i need meta classes or something ? Thanks in advice. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Open a directory in the default file manager
Tim Michelsen wrote: Hello, is there any function/module that allows me to open a directory in the default file manager of a operating system? On Windows you can use os.startfile(). On pure Unices there's no such thing as filetype associations However, if you use a desktop environment, you can spawn xdg-open (from xdg-utils) from Python. This will autodetect gnome, kde and xfce and use their tools (gnome-open, kfmclient, exo-open). I think on OS X/Darwin there's a similar utility called `open'. You can use sys.platform to determine which system you're running on. thomas ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] SOAPpy and ZSI
Hi, I've been tasked with setting up a basic SOAP client and I'm its been the most frustrating python experience. Here's the code: from LoginService_services import * import sys from SOAPpy import SOAPProxy # get a port proxy instance loc = LoginServiceLocator() port = loc.getLogin(in0='pbs_uen', in1='TDapi', in2='3dcarapi') # create a new request req = LoginRequest() # call the remote method resp = port.Login(req) lr = resp.LoginReturn lri0 = lr.get_element_items()[0] service_url = lri0.Value n = 'http://DefaultNamespace' server = SOAPProxy(service_url, namespace=n) server.config.dumpSOAPOut = 1 server.config.dumpSOAPIn = 1 server.config.dumpHeadersOut = 1 server.config.dumpHeadersIn = 1 test = server.greeting() Notice I use ZSI (LoginService_services) for the Login and then SOAPpy for the post log-in stuff (ZSI's wsdl2py script broke on the post log-in WSDL). The login part works fine. It returns a URL with a session id appended. server.greeting() creates this envelope which I can see because of the dumps: SOAP-ENV:Envelope SOAP-ENV:encodingStyle=http://schemas.xmlsoap.org/soap/encoding/; xmlns:SOAP-ENC=http://schemas.xmlsoap.org/soap/encoding/; xmlns:SOAP-ENV=http://schemas.xmlsoap.org/soap/envelope/; SOAP-ENV:Body ns1:greeting xmlns:ns1=http://DefaultNamespace; SOAP-ENC:root=1 /ns1:greeting /SOAP-ENV:Body /SOAP-ENV:Envelope but then this error follows right after: File generic_usage.py, line 34, in module test = server.greeting() File /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/SOAPpy/Client.py, line 470, in __call__ return self.__r_call(*args, **kw) File /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/SOAPpy/Client.py, line 492, in __r_call self.__hd, self.__ma) File /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/SOAPpy/Client.py, line 363, in __call config = self.config) File /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/SOAPpy/Client.py, line 252, in call raise HTTPError(code, msg) SOAPpy.Errors.HTTPError: HTTPError 500 Apple line 252 of Client.py is: if code == 500 and not \ ( startswith(content_type, text/xml) and message_len 0 ): raise HTTPError(code, msg) I can't tell if the server is returning the 500 error or if the transport is. I honestly don't know where to go from here. I wouldn't doubt that the envelope isn't correct for the service but I don't have access to any more info on that. Help much appreciated. Dan All men dream: but not equally. Those who dream by night in the dusty recesses of their minds wake in the day to find that it was vanity: but the dreamers of the day are dangerous men, for they may act their dreams with open eyes, to make it possible. -T. E. Lawrence - ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on multithreading
Hi, Here are some thoughts: From the Python Library Reference: If the subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread. You'll have to do that for your GuiScript class. You can't just stop a thread, you can only wait for it to finish using join(). Or you can set its deamon flag, so it will exit when no non-daemon threads are left. Is there any reason for starting the GUI code in a separate thread? You could just leave it in the main thread. For some general notes on this topic this might be helpful: http://wiki.wxpython.org/LongRunningTasks Cheers, Thomas Pani Varsha Purohit wrote: Hello, i have a gui program in wxpython where i am spawning two threads. one for the mainloop of gui and other for some background tasks. I have to stop the background running thread once its work is done. I am trying to use the join method but it is giving me an error saying threads cannot be joined as the thread has just been created... whereas at that point the thread is done with its job. So i am confused whether i am putting it correctly or not. also, is there any method called stop() to stop the threadsAlso, i want to see if the thread is alive or not.. but i donno where should i put the isAlive() method associated with the thread.. i tried putting it in the code where thread does execution but apparently it is not the correct place. Here is the code... class GuiScript(threading.Thread): def __init__(self): self.run() def run(self): app = wx.PySimpleApp() MainWindow().Show() app.MainLoop() class RunScript(threading.Thread): def run(self): imFile=test() and when the stop button is pressed the two threads should stop executing... so i have written code like this... def OnCloseWindow(self,event): GuiScript().Stop() RunScript().Stop() self.Destroy() but seems stop() method is not existing... can anybody guide me pl thanks, -- Varsha Purohit, Graduate Student ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] opening a pipe?
The subprocess module is what you're looking for. Your example would look like % import subprocess p = subprocess.Popen('cat hi.txt', shell=True, stdout=subprocess.PIPE) for line in p.stdout: print line % I assume you know that you can just open a file for reading instead of piping cat. thomas James Hartley wrote: A Perl script can easily serve as a filter within a pipe as seen in the following: use strict; use warnings; open(IN, 'cat hello.txt |') or die 'unable to open file'; while (IN) { print; } close(IN); Can I do the same within Python? Thanks. Jim ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A bit about python culture
Michael Bernhard Arp Sørensen wrote: Greetings Masters. I was wondering if there's a well know word for python programmers, that is usable as a domain name. Pythonista is one. pythonista.dk seems to be available. Kent Other available .dk domains pyproject.dk pyprojects.dk python-project.dk pythonprogram.dk These might be used for project subdomains, then the programmers might add their name in E-mail adresses. Doing this you will also marked Python projects + making people aware of Python as a programming language. Just a thought :) BR Thomas ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Bad time to get into Python?
Dotan Cohen wrote: However, with the coming of Python3 and the new syntax, is this a bad time to start learning Python? Not at all, I'd say. Changes will be fairly small, with the main changes being: - print is replaced by a print() function - / will become the float division operator - changes towards iterators (e.g. range() doesn't return a list) - string filetype changes There are lots of other changes, but most of them include removing already deprecated idioms. [1] has a list of Python 3k changes. There's also the 2to3 conversion tool which allows you to run lots of conversion automated. That asked, I've heard that 2.6 can be configured to warn when using code that will not run in 3.x. Is this correct? Yes, 2.6 will support a Py3k warnings mode. It should also have many of 3k's features already implemented, allowing to run both side-by-side or via __future__. PEP 3000 ([2]) has more info on this. How is this done? I'd like to do it on a per-file basis, so that I will only need to run one version of python on this machine. Don't know. But if your only using it for some home-coding, you would just once do the conversion and then update to 3k. I want my own apps to throw errors, but not other python apps on this system. Is there some error-level code that I can run? Not sure what you mean by that. Are you refering to exception-handling? I'd say it's not a bad time to learn Python. There will be some major changes in 3k, but as long as you don't have to maintain 2.6 and 3.0 in parallel, conversion should be easy enough. Cheers, thomas pani [1] http://docs.python.org/dev/3.0/whatsnew/3.0.html [2] http://www.python.org/dev/peps/pep-3000/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] regex eats even when not hungry
I have the following mostly working function to strip the first 4 digit year out of some text. But a leading space confounds it for years starting 20..: import re def getyear(text): s = (?:.*?(19\d\d)|(20\d\d).*?) p = re.compile(s,re.IGNORECASE|re.DOTALL) #|re.VERBOSE y = p.match(text) try: return y.group(1) or y.group(2) except: return '' getyear('2002') '2002' getyear(' 2002') '' getyear(' 1902') '1902' A regex of .*? means any number of any characters, with a non-greedy hunger (so to speak) right? Any ideas on what is causing this to fail? Many thanks in advance, Thomas ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] class methods as argument
Hi, I want to do something like this, don't know how to properly explain it, so I just give you some example code class Foo(object): def method(self, arg): print arg def doSomething(object, func): object.func(test) object = Foo() doSomething(object, Foo.method) I want to execute the class method given as argument, but this obvious doesn't work, but I don't know how to get it work, Is it possible? and how? Thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor