Re: [Tutor] Hi This is Michael Munn and I’m interested of the Python programming language.
see also https://wiki.python.org/moin/PythonEditors On August 26, 2018 5:19:20 PM MDT, Alan Gauld via Tutor wrote: >On 26/08/18 18:42, Michael Munn wrote: > >> I’m using Python 3.6 and I heard a friend of mine told me that He >write his >> code using a word processer called Note pad plus some thing like that >to >> code. > >I assume you are on Windows OS? >In which case you probably mean Notepad++ (like >in the C++ programming language) > >It's a well known programmer's editor for Windows. > >Note that it is not a Word Processor, it has >no support for formatting text (fonts, justification >etc) it is just a powerful text editor, which is >what you need for programming. Most importantly >it saves in plain text not in a binary or XML/HTML >format. > >> Any idea where to get this word Processer? > >A web search for Notepad++ should find it. >However Python comes with a useful programming >environment called Idle which you can use instead. >It is Python specific whereas Notepad++ caters >for many languages but if you are starting out >in Python Idle is a fair choice and its already >installed! > >I don't use Windows for Python work but last >time I looked it was called something like >Python GUI in the Windows start menu. > >> PS This question might sounds Stupid to you all. > >Not at all, choice of programming toolset is >a very personal opinion and you will likely >get several suggestions. > >> I ask you not to laugh at me if I post question like this in the >future. >We won't laugh, its why we are here. > >When posting questions always try to be as specific >as possible, post any code you have and the full >text of any error messages. Also post in plain text >if possibly, email servers tends to mess up code >otherwise. > >A reminder of your OS and Python version is also useful. > >Have fun, > >-- >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 -- Sent from my Android device with K-9 Mail. Please excuse my brevity. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi This is Michael Munn and I’m interested of the Python programming language.
On 26/08/18 18:42, Michael Munn wrote: > I’m using Python 3.6 and I heard a friend of mine told me that He write his > code using a word processer called Note pad plus some thing like that to > code. I assume you are on Windows OS? In which case you probably mean Notepad++ (like in the C++ programming language) It's a well known programmer's editor for Windows. Note that it is not a Word Processor, it has no support for formatting text (fonts, justification etc) it is just a powerful text editor, which is what you need for programming. Most importantly it saves in plain text not in a binary or XML/HTML format. > Any idea where to get this word Processer? A web search for Notepad++ should find it. However Python comes with a useful programming environment called Idle which you can use instead. It is Python specific whereas Notepad++ caters for many languages but if you are starting out in Python Idle is a fair choice and its already installed! I don't use Windows for Python work but last time I looked it was called something like Python GUI in the Windows start menu. > PS This question might sounds Stupid to you all. Not at all, choice of programming toolset is a very personal opinion and you will likely get several suggestions. > I ask you not to laugh at me if I post question like this in the future. We won't laugh, its why we are here. When posting questions always try to be as specific as possible, post any code you have and the full text of any error messages. Also post in plain text if possibly, email servers tends to mess up code otherwise. A reminder of your OS and Python version is also useful. Have fun, -- 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] Hi This is Michael Munn and I’m interested of the Python programming language.
Hi All, This is Michael and I have a question about resources on starting to code python. I’m using Python 3.6 and I heard a friend of mine told me that He write his code using a word processer called Note pad plus some thing like that to code. Any idea where to get this word Processer? Please respond if you all get any chance. Best Regards Michael Munn PS This question might sounds Stupid to you all. I just want you all to know that I’m a beginner Pythonist. And I know Nothing about coding at all. I ask you not to laugh at me if I post question like this in the future. Thanks and have a nice day. Best REGARDS michael Munn ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi there, have a question for a side project in physics.....
On Mon, Dec 25, 2017 at 09:45:35AM +, Alan Gauld via Tutor wrote: > On 25/12/17 09:08, Siddharth Sehgal wrote: > > >physics masters student. I am trying to use the Sellmeier Equation > > >I originally state them as floats. However such a process apparently > > >cannot be done with "floats" like these. > > It can be done just with a large error (although as a physics > grad you will know how to calculate the error I assume) I don't think the numbers or equation is so ill-conditioned that the error will be "large", or at least not larger than the experimental uncertainty in the coefficients. Floating point maths is tricky, but it isn't *that* tricky. Especially not for "reasonable" sized numbers, with only nine or ten significant figures. This is the huge advantage of IEEE-754 maths using 64-bit floats, as Python does: most of the time, the obvious formula "just works". -- Steve ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi there, have a question for a side project in physics.....
On Mon, Dec 25, 2017 at 01:08:13PM +0400, Siddharth Sehgal wrote: > The actual equation is below screen shotted No it isn't -- either you forgot to attach it, or the mailing list removed it. Do you mean this equation? https://en.wikipedia.org/wiki/Sellmeier_equation I suggest you try using Python and compare your results to those from here: http://www.calctool.org/CALC/phys/optics/sellmeier or from some authoritative source of refractive indexes. Here is my simple test, for borosilicate glass BK7 using the values from Wikipedia. Using the website: refractive index at 590 nm = 1.51670 Using Python, I get: 1.516698697993053 Here is my code. Feel free to use it for any purpose, no credit required (except as needed to meet any academic obligations you may have about collaboration and/or plagiarism). import math def sellmeier(lambd, B1, B2, B3, C1, C2, C3): return 1 + B1*f(lambd, C1) + B2*f(lambd, C2) + B3*f(lambd, C3) def f(x, y): x2 = x**2 return x2/(x2 - y) # Coefficients for BK7 (borosilicate crown glass) result = sellmeier(0.590, # 590nm == 0.590µm 1.03961212, 0.231792344, 1.01046945, 6.00069867e-3, 2.00179144e-2, 103.560653) print(math.sqrt(result)) -- Steve ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi there, have a question for a side project in physics.....
On Mon, Dec 25, 2017 at 01:08:13PM +0400, Siddharth Sehgal wrote: > Hi there > > > I am a novice python user and am a physics masters student. I am > trying to use the Sellmeier Equation to calculate a refractive index. > The coefficients of this equation are decimals to a large number of > sig figs ( i.e B1 = 1.03961212, B2 = 0.231792344, C1 = 6.00069867×10−3 That's not really a lot of significant figures. Python floats are C 64-bit doubles, so they can represent about 15 or 16 significant figures. The numbers you show are only 9 or 10. > ... and so on) in the sellmeier formula there is a lot of fractions, > multiplication and squaring of these numbers. I originally state them > as floats. However such a process apparently cannot be done with > "floats" like these. What makes you think that you cannot use floats for this? Of course floating point maths on computers is not the same as real arithmetic of the Real numbers in mathematics class, and you may need to carefully consider the possible error conditions in your equations, round-off error, and so forth, but in general I would expect that simply using Python as a calculator will be fine for all but the most precise calculations. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi there, have a question for a side project in physics.....
On 25/12/17 09:08, Siddharth Sehgal wrote: physics masters student. I am trying to use the Sellmeier Equation I originally state them as floats. However such a process apparently > cannot be done with "floats" like these. It can be done just with a large error (although as a physics grad you will know how to calculate the error I assume) What do i do? PLEASE NEED HELP! There ae several ways and I guess the best will involve using SciPy/numpy features. But since i don't know those I'll suggest the old school way which is to multiply your numbers up until they become integers and take advantage of pythons big int feature. You will need to plug all the multipliers into your formula and work out the final multiplier - but that is just exponent arithmetic so should be doable. Finally adjust your answer by the calculated exponent. As I say there will probably be better solutions in the numpy space and hopefully someone else will tell you about them. The actual equation is below screen shotted This list does not permit non-text attachments - the server throws them away. Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Hi there, have a question for a side project in physics.....
Hi there I am a novice python user and am a physics masters student. I am trying to use the Sellmeier Equation to calculate a refractive index. The coefficients of this equation are decimals to a large number of sig figs ( i.e B1 = 1.03961212, B2 = 0.231792344, C1 = 6.00069867×10−3 ... and so on) in the sellmeier formula there is a lot of fractions, multiplication and squaring of these numbers. I originally state them as floats. However such a process apparently cannot be done with "floats" like these. What do i do? PLEASE NEED HELP! The actual equation is below screen shotted Many thanks, I look forward to your response, THIS IS NOT HOMEWORK BY THE WAY, I just want to use this program as it saves a lot of writing on paper. Siddharth Sehgal MSc Student in Physics SUNY - Stony Brook University ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi all: How do I save a file in a designated folder?
On 03/05/17 00:28, Cameron Simpson wrote: >> And so forth? I assume you mean >> >> MMDD.png format? >> >> You should read about the strftime function in the time > > Further to this, I would also advocate that you consider writing the > timestamp > from largest unit to smallest unit, like an ISO8601 timestamp, which > typically > looks like: > > MMDD.png Yes, I absolutely second this advice and should have included it. ISO dates make programming life so much easier! -- 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
Re: [Tutor] Hi all: How do I save a file in a designated folder?
On Tue, May 2, 2017 at 6:09 PM, Michael Cwrote: > screenshot.save("\test\missed.png") You probably know that "\t" represents a tab in a string literal, but there's something about working with a path that causes people to overlook this. Windows won't overlook it. Control characters, i.e. characters with an ordinal value below 32, are forbidden in Windows file names. Also, you're depending on whatever drive or UNC path is the current directory. For example: >>> os.chdir('C:\\') >>> os.path.abspath('/test/missed.png') 'C:\\test\\missed.png' >>> os.chdir('localhost\C$') >>> os.path.abspath('/test/missed.png') 'localhost\\C$\\test\\missed.png' A fully-qualified path must start with the drive or UNC share. For example: >>> os.path.abspath('C:/test/missed.png') 'C:\\test\\missed.png' >>> os.path.abspath('//localhost/C$/test/missed.png') 'localhost\\C$\\test\\missed.png' In this case I'm using abspath() to normalize the path, which first has Windows itself normalize the path via GetFullPathName(). This shows what Windows will actually try to open or create, given that it implements legacy DOS rules. For example, it ignores trailing spaces and dots in the final path component: >>> os.path.abspath('C:/test/missed.png ... ') 'C:\\test\\missed.png' and DOS devices are virtually present in every directory: >>> os.path.abspath('C:/test/nul.txt') '.\\nul' ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi all: How do I save a file in a designated folder?
On 03May2017 00:01, Alan Gauldwrote: On 02/05/17 19:09, Michael C wrote: 1. How to name the file with time stamp. e.g. 05012017.png and so forth. And so forth? I assume you mean MMDD.png format? You should read about the strftime function in the time (and datetime) module. Other functions thee will find the current date/time for you. Thee are examples on the documentation pages but if you get stuck come back with specific questioons. Further to this, I would also advocate that you consider writing the timestamp from largest unit to smallest unit, like an ISO8601 timestamp, which typically looks like: MMDD.png See: https://www.iso.org/iso-8601-date-and-time-format.html https://en.wikipedia.org/wiki/ISO_8601 This has the advantage that a lexical sort (as in a typical directory listing or file glob) automatically arranges names in date order. I'd also remark that the USA centric format (MMDD) that Alan inferred is particularly unfortunate in that (a) the rest of the world generally use DDMM so that the units come in increasing size and (b) doesn't sort very nicely at all. Of course, you might have meant 5th December 2017 above, so who knows? But the very ambiguity makes this one to avoid. For numeric timestamps like yours I only ever use MMDD (or the obvious variants like -MM-DD etc). If I use another, I make the month a word (lousy for sorting and parsing, but clear to the human reader); I only do that in prose, not in filenames. Cheers, Cameron Simpson ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi all: How do I save a file in a designated folder?
On 02/05/17 19:09, Michael C wrote: > from PIL import Image > from PIL import ImageGrab > > screenshot = ImageGrab.grab() > screenshot.show() > screenshot.save("\test\missed.png") > > This is my current code, using Python Image Library! You should probably investigate Pillow, I believe development of PIL has now ceased in favour of Pillow. Pillow is backwardly compatible with PIL so your existing code should still work. > What I would like to get help with is: > > 1. How to name the file with time stamp. e.g. 05012017.png and so forth. And so forth? I assume you mean MMDD.png format? You should read about the strftime function in the time (and datetime) module. Other functions thee will find the current date/time for you. Thee are examples on the documentation pages but if you get stuck come back with specific questioons. > 2. How to save it in a designated folder like C:\test\test2\ and so forth. That is just string handling. thee is nothing special about a file path(*), it is just a string. Store the folder as one string then construct your file path with filepath = folder + filename (*)Having said that there is nothing special there is a dedicated module for working with paths - os.path - that has convenience functions for constructing and de-constructing path strings. You might find it useful. > P.S. I am on windows 10 The biggest issue with Windows is its use of \ as a separator. Be sure to use raw strings ( ie prefix an r: r'') or just use a Unix style [path with / instead of \. Or use os.path which will intelligently decide which separator to use. HTH -- 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] Hi all: How do I save a file in a designated folder?
from PIL import Image from PIL import ImageGrab # takes the screenshot screenshot = ImageGrab.grab() # display the screenshot screenshot.show() # save the screenshot screenshot.save("\test\missed.png") This is my current code, using Python Image Library! What I would like to get help with is: 1. How to name the file with time stamp. e.g. 05012017.png and so forth. 2. How to save it in a designated folder like C:\test\test2\ and so forth. P.S. I am on windows 10 Thanks! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi
Hi, On 23 June 2016 at 19:00, Bharath Swaminathanwrote: > Can I run my python code in multiple processors? I have a dual core... Like an idiot I forgot a link for the "pp" module, my apologies. Here it is: http://www.parallelpython.com/ If you have/use pip, you can simply enter (from an operating system shell/command prompt, and provided you've got an internet connection): pip2 install pp Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi
Hi Bharath, On 23 June 2016 at 19:00, Bharath Swaminathanwrote: > > Can I run my python code in multiple processors? I have a dual core... Notwithstanding Alan's answer, I'm going to directly answer your question: Yes, it can. However The degree and level of success you're going to have in fully utilising your dual cores (in other words parallelizing your Python program) are going to depend on the concurrency mechanism you choose. As a minor digression: Concurrency and Parallelism are not the same thing, though they're related. Concurrency "is about dealing with a lot of things at once" (e.g. it's about design, it's about structure) whereas parallelism "is about doing a lot of things at once" (e.g. it's about execution)[1] Please go watch the referenced video if this is at all unclear as it's actually and important distinction IMO. As an additional reference Russel Winder has given several talks over the years on threads, parallelism, concurrency and related topics which are well worth watching, please google around as I can't lay my hands on one I saw at Pycon which was particularly good. The following page seems to contain some useful links:[2] -- The one I saw was the "GIL isn't evil" presentation IIRC. Anyway, so, most people reach for threads as the default concurrency construct. Now, Python also supports threads (see the "threading" module: https://www.youtube.com/watch?v=cN_DpYBzKso) and you could use this as concurrency construct, but depending on what your program does you will likely find that it doesn't fully make use of your 2 cores like you want to. This is down to the design of the Python interpreter, and something called the Global Interpreter Lock (GIL). In most cases the GIL essentially has the result of serializing most of the execution of multiple thread, resulting in sub-optimal use of processor resources, when using real thread. For this reason multi-processing is highly preferable for Python and will allow you to effectively sidestep the GIL and make full use of all your cores (or even multiple machines if you want). The "multiprocessing" module (https://docs.python.org/2/library/multiprocessing.html) provides an API similar to that of the "threading" module but works with processes and is perhaps worth looking at. For other concurrency approaches, frameworks and libraries, you may want to look at https://wiki.python.org/moin/Concurrency/ There are quite a few. I want to highlight one particular Python concurrency module, called "ParrallelPython", the module name being "pp", which I've had great success with and highly recommend if your problem is suitable to it. The beauty of this module is that it automatically load balances according to the relative speeds of the processors/cores available. and can easily scale if more compute cores are added. So you can very easily also just spin up more nodes and providing they're suitable equipped with a "pp" based server will join and share the computational load regardless of the relative speeds/cores on each machine/processor. All the work just gets split equally based on relative speed. Really rather easy and satisfying to see and use. (Oh and by the way, "pp" also works seamless with PyPy, which in the stuff I did sped the programs up several orders of magnitude, should you need even more speed. If you don't know what PyPy is: PyPy is an alternative Jit-compiler version of Python. Basically your Python programs are compiled to machine code on the fly as they run and will in many cases, depending on what they're doing, be in some cases /several orders of magnitude/ faster than the same code on the C Python interpreter.) Anyway, that's enough for now. Have fun and ask again if anything's unclear. Walter [1] Rob Pike - 'Concurrency Is Not Parallelism', https://www.youtube.com/watch?v=cN_DpYBzKso [2] Presentations Relating to Parallelism,http://www.concertant.com/presentations_parallelism.html ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi
On 23/06/16 19:00, Bharath Swaminathan wrote: > Can I run my python code in multiple processors? I have a dual core... Your OS may run your python code on multiple processors but it's not something you can easily control in Python. Remember that your computer probably has hundreds of processes running at any one time and your python program(s) will only be a part of the total load. The OS schedules the jobs to run on whichever processor is available at any given time - it may well use different processors for the same process during the lifetime of that process. Now, if what you really want to know is whether the OS can split a single Python process over multiple CPU cores in parallel, that's a much more complex question and I think the current answer is probably not. (But others on this list know a lot more about that kind of thing than I do!) But it depends on the exact version of Python you are running and probably which OS you are using too. In my experience trying to guess how the OS will schedule your jobs is an exercise in frustration. Let the OS do its thing and only worry about those kinds of optimisation once you have proved it is really an issue (by measurement). -- 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] Hi
Can I run my python code in multiple processors? I have a dual core... ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Hi Dear!
Hi Dear! I newbie and read 2.1.2. Interactive Mode https://docs.python.org/3/tutorial/interpreter.html but when I type >>> the_world_is_flat = True >>> if the_world_is_flat: ... print("Be careful not to fall off!") I got answer IndentationError: expected an indented block [root@localhost /]# python3 Python 3.4.3 (default, Jun 29 2015, 12:15:26) [GCC 5.1.1 20150618 (Red Hat 5.1.1-4)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> the_world_is_flat = True >>> if the_world_is_flat: ... print(Be careful not to fall off!) File "", line 2 print(Be careful not to fall off!) ^ IndentationError: expected an indented block >>> I have installed Python3 in Linux Fedora 23 Please tell my why Python3 doesn't work? Sincerely! Alexander ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi Dear!
On Thu, Feb 4, 2016 at 7:49 AM, Alexa kunwrote: > Hi Dear! > I newbie and read 2.1.2. Interactive Mode > https://docs.python.org/3/tutorial/interpreter.html > > but when I type > > >>> the_world_is_flat = True > >>> if the_world_is_flat: > ... print("Be careful not to fall off!") > > I got answer > > IndentationError: expected an indented block > > [root@localhost /]# python3 > Python 3.4.3 (default, Jun 29 2015, 12:15:26) > [GCC 5.1.1 20150618 (Red Hat 5.1.1-4)] on linux > Type "help", "copyright", "credits" or "license" for more information. > > >>> the_world_is_flat = True > >>> if the_world_is_flat: > ... print(Be careful not to fall off!) > File "", line 2 > print(Be careful not to fall off!) > ^ > IndentationError: expected an indented block > >>> > There is something funny about your print function. The three periods > indicate that you are no longer in interactive mode. > See my session below > I have installed Python3 in Linux Fedora 23 > Please tell my why Python3 doesn't work? > > Sincerely! > Alexander > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > >>> flat = True >>> if flat: ... print("flat") ... flat >>> -- Joel Goldstick http://joelgoldstick.com/stats/birthdays ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi Dear!
Hello Alexander, and welcome! My answers are below, between your questions (starting with > quote marks). On Thu, Feb 04, 2016 at 02:49:39PM +0200, Alexa kun wrote: > Hi Dear! > I newbie and read 2.1.2. Interactive Mode > https://docs.python.org/3/tutorial/interpreter.html > > but when I type > > >>> the_world_is_flat = True > >>> if the_world_is_flat: > ... print("Be careful not to fall off!") Look carefully at the last line. Do you notice the indented space between the three dots ... and the print? You need to either press space at least once, or the TAB key, to indent the line. > I got answer > > IndentationError: expected an indented block Here Python tells you exactly what the problem is. Python expected an indented block of text (at least one line, indented by at least one space), but you didn't indent the line. Python expects: if the_world_is_flat: print(Be careful not to fall off!) but you typed: if the_world_is_flat: print(Be careful not to fall off!) without the indentation. You should press the TAB key to indent, or the SPACE key at least once. Also, one last comment: > [root@localhost /]# python3 I see from this that you are running Python as the root superuser. This is VERY dangerous for a beginner (and even for an expert). As root, you can over-write essential system files. Which means that if you accidentally give the wrong Python commands, you could break your system and leave it in a broken state where it needs to be re-installed. It is MUCH safer to experiment as the regular user. If the command prompt shows # then you are running as root. If it shows $ then you are running as a regular user. -- Steve ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi Dear!
On 04/02/16 12:49, Alexa kun wrote: > Hi Dear! Hi. Can I ask that in future you choose a subject line that reflects your question? For this case it might be "IndentationError" say. > but when I type > the_world_is_flat = True if the_world_is_flat: > ... print("Be careful not to fall off!") The problem is that is not what you typed. And this is why we always ask for the full error trace - thanks for including it. if the_world_is_flat: > ... print(Be careful not to fall off!) > File "", line 2 > print(Be careful not to fall off!) > ^ > IndentationError: expected an indented block It says that there is an IndentationError which means that Python is expecting to see a line starting in a different place from where it does. In your case that means the line after the 'if' is expected to be "indented". That is it should have a few spaces in front of it (we usually recommend 4 but Python doesn't care so long as there is more than the preceding line). The indentation is Python's way of telling which bits of code need to be executed if the 'if' test is true. Anything that is indented will be executed (or missed if the test is false) as appropriate. The indentation needs to be the same for all the indented lines. ie if foo > 42: print (foo) f = 666 is ok but if foo > 42: print (foo) f00 = 666# not enough spaces won't work. > Please tell my why Python3 doesn't work? It's working just fine, you only need to give it some space(s)... :-) -- 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
Re: [Tutor] Hi Dear!
On Thu, Feb 4, 2016 at 2:49 PM, Alexa kunwrote: > Hi Dear! > I newbie and read 2.1.2. Interactive Mode > https://docs.python.org/3/tutorial/interpreter.html > > but when I type > > >>> the_world_is_flat = True > >>> if the_world_is_flat: > ... print("Be careful not to fall off!") > > I got answer > > IndentationError: expected an indented block > > [root@localhost /]# python3 > Python 3.4.3 (default, Jun 29 2015, 12:15:26) > [GCC 5.1.1 20150618 (Red Hat 5.1.1-4)] on linux > Type "help", "copyright", "credits" or "license" for more information. > > >>> the_world_is_flat = True > >>> if the_world_is_flat: > ... print(Be careful not to fall off!) > File "", line 2 > print(Be careful not to fall off!) > ^ > IndentationError: expected an indented block > >>> > > You should have the print function indented, usually by 4 spaces. This is how Python knows which commands to be executed as part of the if block. So this is what you'll make your code work: >>> the_world_is_flat = True >>> if the_world_is_flat: ... print("Be careful not to fall off!") ... Be careful not to fall off! The interpreter also tries to help you, it puts ... at the begging of the line (instead of >>>) which means it expect some indentation. Emil I have installed Python3 in Linux Fedora 23 > Please tell my why Python3 doesn't work? > > Sincerely! > Alexander > ___ > 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] Hi Tutor
>I wrote this short program for my grandson: > >from random import sample > >soups = ['Onion soup', 'Veggie soup', 'Chicken soup', 'Corn soup'] >salads = ['Veggie', 'Onion', 'Cabbage', 'Lettuce', 'Caesar', 'Tomato'] >main = ['Crab cake', 'Catfish', 'Ribs', 'Chopped liver', 'Meat balls'] >beverage = ['Wine', 'Rum', 'Lemonade', 'Red bull', 'Margarita', 'Jin'] > >def dish(soups): >return (sample(soups, 1)) > >print('Soup:\t\t', dish(soups)) >print('Salad:\t\t', dish(salads)) >print('Main dish:\t', dish(main)) >print('Beverage:\t', dish(beverage)) > >A possible output could be: > >Soup: ['Chicken soup'] >Salad: ['Caesar'] >Main dish: ['Meat balls'] >Beverage: ['Wine'] > >How do I get rid from the square brackets and the quotation marks >in the output? There are many possible answers to this question. Here's my answer: from random import choice def dish(options): return choice(options) Then, the function dish() will return exactly one element from the options. Since each of soup, salads, main and beverage are lists with string elements, the dish() function will return a string. I would like to have some Onion soup, the Crab cake, Rum and a Caesar, please. Good luck, -Martin -- Martin A. Brown http://linux-ip.net/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Hi Tutor
I wrote this short program for my grandson: from random import sample soups = ['Onion soup', 'Veggie soup', 'Chicken soup', 'Corn soup'] salads = ['Veggie', 'Onion', 'Cabbage', 'Lettuce', 'Caesar', 'Tomato'] main = ['Crab cake', 'Catfish', 'Ribs', 'Chopped liver', 'Meat balls'] beverage = ['Wine', 'Rum', 'Lemonade', 'Red bull', 'Margarita', 'Jin'] def dish(soups): return (sample(soups, 1)) print('Soup:\t\t', dish(soups)) print('Salad:\t\t', dish(salads)) print('Main dish:\t', dish(main)) print('Beverage:\t', dish(beverage)) A possible output could be: Soup: ['Chicken soup'] Salad: ['Caesar'] Main dish: ['Meat balls'] Beverage: ['Wine'] How do I get rid from the square brackets and the quotation marks in the output? Thank you. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi there,
On 02/01/16 12:45, yehudak . wrote: > I know the mathematical way to solve it (resulting in 24), but I want a > Python solution. Show us your code. Usually "the mathematical way to do it" works in Python too. Although there will likely be other ways that may sometimes run faster or easier to code. But until we see your code we can't comment on what you are doing. One way to try would be continually dividing by 10 until you get a non-zero remainder. Count the number of divisions necessary. Hint: The divmod() function may help here. -- 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
Re: [Tutor] Hi there,
On Sat, Jan 02, 2016 at 02:45:30PM +0200, yehudak . wrote: > I'm trying to write a Python 3.5 program to find how many trailing zeros > are in 100! (factorial of 100). > I downloaded factorial from Math module, but all my efforts to solve the > problem failed. > > I know the mathematical way to solve it (resulting in 24), but I want a > Python solution. Here are the steps needed: http://www.purplemath.com/modules/factzero.htm Try writing some Python code for this, and if you have trouble, show us your code and we'll help. But you have to write it first -- we won't do your homework for you. -- Steve ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Hi there,
I'm trying to write a Python 3.5 program to find how many trailing zeros are in 100! (factorial of 100). I downloaded factorial from Math module, but all my efforts to solve the problem failed. I know the mathematical way to solve it (resulting in 24), but I want a Python solution. Thank you. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Hi pyusb Cant Connect Hid Device !
Hello i ve searching some information for my problem . i m trying to write data to usb hid device idVendor=0x0123, idProduct=0x0012 its pic18f2550 Bus 001 Device 008: ID 0123:0012 Device Descriptor: bLength18 bDescriptorType 1 bcdUSB 1.10 bDeviceClass0 (Defined at Interface level) bDeviceSubClass 0 bDeviceProtocol 0 bMaxPacketSize064 idVendor 0x0123 idProduct 0x0012 bcdDevice1.00 iManufacturer 1 USB iProduct2 IO INTERFACE iSerial 0 bNumConfigurations 1 Configuration Descriptor: bLength 9 bDescriptorType 2 wTotalLength 41 bNumInterfaces 1 bConfigurationValue 1 iConfiguration 0 bmAttributes 0xc0 Self Powered MaxPower 100mA Interface Descriptor: bLength 9 bDescriptorType 4 bInterfaceNumber0 bAlternateSetting 0 bNumEndpoints 2 bInterfaceClass 3 Human Interface Device bInterfaceSubClass 0 No Subclass bInterfaceProtocol 0 None iInterface 0 HID Device Descriptor: bLength 9 bDescriptorType33 bcdHID 1.00 bCountryCode0 Not supported bNumDescriptors 1 bDescriptorType34 Report wDescriptorLength 32 Report Descriptor: (length is 32) Item(Global): Usage Page, data= [ 0x00 0xff ] 65280 (null) Item(Local ): Usage, data= [ 0x01 ] 1 (null) Item(Main ): Collection, data= [ 0x01 ] 1 Application Item(Local ): Usage Minimum, data= [ 0x01 ] 1 (null) Item(Local ): Usage Maximum, data= [ 0x08 ] 8 (null) Item(Global): Logical Minimum, data= [ 0x80 ] 128 Item(Global): Logical Maximum, data= [ 0x7f ] 127 Item(Global): Report Size, data= [ 0x08 ] 8 Item(Global): Report Count, data= [ 0x02 ] 2 Item(Main ): Input, data= [ 0x02 ] 2 Data Variable Absolute No_Wrap Linear Preferred_State No_Null_Position Non_Volatile Bitfield Item(Local ): Usage Minimum, data= [ 0x01 ] 1 (null) Item(Local ): Usage Maximum, data= [ 0x08 ] 8 (null) Item(Global): Report Size, data= [ 0x08 ] 8 Item(Global): Report Count, data= [ 0x02 ] 2 Item(Main ): Output, data= [ 0x02 ] 2 Data Variable Absolute No_Wrap Linear Preferred_State No_Null_Position Non_Volatile Bitfield Item(Main ): End Collection, data=none Endpoint Descriptor: bLength 7 bDescriptorType 5 bEndpointAddress 0x81 EP 1 IN bmAttributes3 Transfer TypeInterrupt Synch Type None Usage Type Data wMaxPacketSize 0x0008 1x 8 bytes bInterval 250 Endpoint Descriptor: bLength 7 bDescriptorType 5 bEndpointAddress 0x01 EP 1 OUT bmAttributes3 Transfer TypeInterrupt Synch Type None Usage Type Data wMaxPacketSize 0x0008 1x 8 bytes bInterval 10 Device Status: 0x0001 i ve tried kind of codes read_bytes = self.handle.interruptRead(0x81, 8, 1000) hid_device.write(0x1, ([0x91])) both is return len(data) so it should write but its not writing ! is there anyone can help me thank you! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi pyusb Cant Connect Hid Device !
On 21/12/15 03:36, Seint Aksoy wrote: > Hello i ve searching some information for my problem . > i m trying to write data to usb hid device This list if for learning the core python language and standard library. Pyusb is not part of that and a bit more technical than our normal scope. You would be better asking on a pyusb support forum, or failing that on the main Python mailing list/newsgroup. The pyusb list details are here: https://lists.sourceforge.net/lists/listinfo/pyusb-users -- 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] Hi
Hello I've been using Python 27 on Windows for as long as I have used a computer for intelligent purposes, viz. since 2000 I think, well the earlier versions till the current version I'm using now. I used it primarily for mathematical precision on numerical computations. I make my own codes. I'm fluent in it and in VBA. I also use Mathematica (Home Edition) to compare. However as Mathematica is largely symbolic, I prefer Python. However I recently talked to a guy online and he told me the following, which actually intrigued and surprised me: The vast majority of numerical codes in science, including positional astronomy, are written in Fortran and C/C++. If you wish to use these codes in minority and less efficient languages such as Python and VBA, learning to translate this code into those languages is a skill you will have to acquire. The codes in question are referring to a query I posed to him regarding the GUST86 theory on the computational position of Uranus' natural satellites authored by Laskar and Jacobson in 1987. The code is readily downloadable in Fortran at the IMCCE ftp site. But his statement is insinuating that Python is inferior to Fortran as a mathematical tool and that all of the scientific community prefers to use Fortran. My question is simple: Is he right or wrong? Thanks Vick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi
On Apr 11, 2015, at 8:32 AM, Vick vick1...@orange.mu wrote: [byte] However I recently talked to a guy online and he told me the following, which actually intrigued and surprised me: The vast majority of numerical codes in science, including positional astronomy, are written in Fortran and C/C++. If you wish to use these codes in minority and less efficient languages such as Python and VBA, learning to translate this code into those languages is a skill you will have to acquire. The codes in question are referring to a query I posed to him regarding the GUST86 theory on the computational position of Uranus' natural satellites authored by Laskar and Jacobson in 1987. The code is readily downloadable in Fortran at the IMCCE ftp site. But his statement is insinuating that Python is inferior to Fortran as a mathematical tool and that all of the scientific community prefers to use Fortran. My question is simple: Is he right or wrong? He is probably right, but only because most large scientific codes have historical roots that date back to the days when FORTRAN was the only language readily available on the computers scientists used. Even today, FORTRAN compilers can frequently optimize typical scientific code to tighter (faster) executable code than the compilers for other, more modern, richer languages. HOWEVER, that said, more and more scientific code is being written with Python as the organizing language which calls mathematical libraries written in FORTRAN. Libraries like numpy make heavy use of FORTRAN arrays, while allowing the scientific programmer to concentrate on the higher levels of the science being modeled. Bill Thanks Vick ___ 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] Hi
Hi, Thanks for replying! I understand as you said that since it was the very first language available to them therefore scientists at large got stuck with it as I presume it would have become the primary programming language example given in their textbooks or study materials. However your reply does not answer the first part of the proposition of my question! Given that all scientists like to code in Fortran but does it mean that Python is inferior to it in terms of mathematical / scientific computation? Thanks Vick -Original Message- From: William Ray Wing [mailto:w...@mac.com] Sent: Saturday, 11 April, 2015 17:40 To: Vick Cc: William R. Wing; webmas...@python.org; tutor@python.org Subject: Re: [Tutor] Hi On Apr 11, 2015, at 8:32 AM, Vick vick1...@orange.mu wrote: [byte] However I recently talked to a guy online and he told me the following, which actually intrigued and surprised me: The vast majority of numerical codes in science, including positional astronomy, are written in Fortran and C/C++. If you wish to use these codes in minority and less efficient languages such as Python and VBA, learning to translate this code into those languages is a skill you will have to acquire. The codes in question are referring to a query I posed to him regarding the GUST86 theory on the computational position of Uranus' natural satellites authored by Laskar and Jacobson in 1987. The code is readily downloadable in Fortran at the IMCCE ftp site. But his statement is insinuating that Python is inferior to Fortran as a mathematical tool and that all of the scientific community prefers to use Fortran. My question is simple: Is he right or wrong? He is probably right, but only because most large scientific codes have historical roots that date back to the days when FORTRAN was the only language readily available on the computers scientists used. Even today, FORTRAN compilers can frequently optimize typical scientific code to tighter (faster) executable code than the compilers for other, more modern, richer languages. HOWEVER, that said, more and more scientific code is being written with Python as the organizing language which calls mathematical libraries written in FORTRAN. Libraries like numpy make heavy use of FORTRAN arrays, while allowing the scientific programmer to concentrate on the higher levels of the science being modeled. Bill Thanks Vick ___ 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] Hi
On Sat, Apr 11, 2015 at 08:35:08PM +0400, Vick wrote: Given that all scientists like to code in Fortran but does it mean that Python is inferior to it in terms of mathematical / scientific computation? Scientists do not like to code in Fortran. Anybody who tells you that is mistaken. If they wanted to be programmers, they would have become programmers, not scientists. If they *have* to program, they will, but they would rather do science, not programming. No, Python is not inferior. It is just different. It is designed to have different strengths and weaknesses compared to Fortran. Strengths of Fortran: - You can write very fast, powerful numeric programs. - Fortran excels at high-speed number-crunching. - Fortran is an old language, in fact it is the first (and therefore oldest) programming language. Because it has been around since the 1950s, there are lots of Fortran libraries you can use -- if you can find them, or afford them. Weaknesses of Fortran: - It is difficult to write Fortran code. - It is an old language which lacks modern programming features. - It is hard to work with strings or do anything except number-crunching. - It is a very low-level language, which means you have to care about things that have nothing to do with the problem you are trying to solve, like memory. Strengths of Python: - It is a modern language with many modern features that Fortran lacks. - It is easy to work with strings and other associated data structures. - It is a high-level language that automatically looks after all the boring book-keeping details, like memory. - It excels at rapid application development. - It excels at being a glue-language for calling pre-written C or Fortran libraries. Weaknesses: - Pure Python code may be a bit slower that C or Fortran code. (But that doesn't matter, if you can call a C or Fortran library to do the heavy lifting, and leave Python to do the parts that C or Fortran struggle with.) When people tell you that real scientists write their code in Fortran, they are being macho pretentious fools. Do real scientists also make their own test tubes from sand they dug out of the ground themselves? No, of course not. It isn't 1800 any more, and the average scientist no more needs to program in Fortran than they need to grind their own lenses. Some scientists may still need to use Fortran, but that is a sign that they are still stuck with using ancient computer programs, not a good thing to be copied. To give an analogy, Fortran is like flying a Suyez rocket. It is very difficult to learn to fly, but once you master it you can go into space in seconds. But it will takes years of training and months of preparation for each flight. Python is like driving a car: it won't get you into space, but it takes weeks to learn to drive a car, not years, and you can jump in the car and drive to the shops with no preparation needed. And you can get in your car and drive to the Suyez rocket, but you cannot get in the Suyez and fly to where you parked your car. Which is better? Well, it depends. If you want to drive to the shops, the Suyez is completely useless. It costs fifty million dollars every time you use it, and you cannot even get to the shops. If you want to spend six months writing a Fortran program to analysis your data, you can, and when you have finished, it will run in five seconds. Or you can spend six days writing it in Python, and it will run in five minutes. Which is better? To be more precise: Python can use Fortran and C libraries to do the heavy lifting, the difficult work. Doing that from Fortran or C is a horrible experience: they are hard languages to learn, and hard to use. But using those libraries from Python is fast, and fun, and easy, and that means that scientists can spend more time doing science and less time trying to program the computer. -- Steve ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi
On 11/04/15 13:32, Vick wrote: The vast majority of numerical codes in science, including positional astronomy, are written in Fortran and C/C++. True, because the vast majorioty of scientific codes (ie libraries) were written many years ago and are still maintained in the languages used back then. Mainly that was Fortran for science. The vast majpority of *new* scientific code being written is not in Fortran (and not much in C either). In fact I don't know of any local university that still teaches Fortran as part of their normal science or math syllabus. Most new scientific work is done in Mathematica or similar high level language and then translated when needed into a lower level language like C or increasingly Java. (And if its statistics often into R.) If you wish to use these codes in minority and less efficient languages such as Python and VBA, Minority - False. There are certainly more VBA programmers than Fortan ones. And probably as many as there are C/C++ Python is only a little way behind Fortan if at all. But if we limit ourselves to the scientific community then its closer to being true. learning to translatethis code into those languages is a skill you will have to acquire. Completely false. Almost all modern scripting languages have mechanisms to call C libraries easily. (And high quality Fortran to C translators exist.) Only if you need to write very high performance routines that do not already exist - ie you are a research scientist or mathematician - do you need to learn C or Fortran. And even then its unlikely to be your first choice. The codes in question are referring to a query I posed to him regarding the GUST86 theory on the computational position of Uranus' natural satellites authored by Laskar and Jacobson in 1987. The code is readily downloadable in Fortran at the IMCCE ftp site. Have you investigated the SciPy libraries, and especially the SciKit collection of specialist libraries. There are several astro libraries in there. Most are written in C but wrapped for use from Python. But his statement is insinuating that Python is inferior to Fortran as a mathematical tool No, he quite correctly states that Python is less efficient than C or Fortran for numerical analysis. That is true of mainstream, Python. There are various projects attempting to address that shortfall. But there are many dimensions to the goodness of a programming language and efficiency (ie runtime speed) is only one of them. And on modern computing hardware it is rarely the most important one. Others include development speed (programming efficiency), portability, reliability, connectivity, abstraction capability, readability/maintainability, tool support etc. To say any language is inferior to another needs to be qualified by the dimension(s) being measured. I see Steven has just posted a similar mail that goes into the comparisons in more detail. So I'll stop here :-) and that all of the scientific community prefers to use Fortran. That depends who you talk to. I know many scientists who swear by Mathematica and Matlab and don't use anything else. My question is simple: Is he right or wrong? The answer is less simple: it depends... Finally, for a more light-hearted take on the topic, see: http://www.ee.ryerson.ca/~elf/hack/realmen.html For maximum offence substitute Python for Pascal ;-) -- 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
Re: [Tutor] Hi
Hi Vick, and welcome! My replies to your questions are below, interleaved with your comments. On Sat, Apr 11, 2015 at 04:32:38PM +0400, Vick wrote: However I recently talked to a guy online and he told me the following, which actually intrigued and surprised me: The vast majority of numerical codes in science, including positional astronomy, are written in Fortran and C/C++. If you wish to use these codes in minority and less efficient languages such as Python and VBA, learning to translate this code into those languages is a skill you will have to acquire. [...] But his statement is insinuating that Python is inferior to Fortran as a mathematical tool and that all of the scientific community prefers to use Fortran. My question is simple: Is he right or wrong? He is partly right, partly wrong. But mostly wrong. Twenty years ago, if you wanted to do scientific computing, C and Fortran were essential. They are still very important, but they are no longer essential. There are many professional-quality mathematical libraries. Older libraries are nearly all written in C/C++ or Fortran. Some are older libraries are written in Pascal, but because few people use Pascal any more, you won't find many of them still in use. Some newer libraries are written in Java. In the future, I would expect new scientific libraries to start coming out written in Julia: http://julialang.org/ Although these libraries are written in C or Fortran, you don't need to program in those two languages to *use* those libraries. Most scripting languages like Python, Lua or Ruby include ways to call code in C or Fortran libraries as if they were written in Python (or Lua, Ruby, and so forth). We call languages like Python a glue language, because it is very good for gluing together code from different libraries. You want to use this library for planetary orbit calculations, written in Fortran, and that library for calculating lunar eclipses written in C, so you use a Python script to bring them together. Many mathematicians, statisticians and scientists use products such as Mathematica, Matlab, R, SAS, Minitab, Maple, and similar. These are all good products that have been around for a long time, with their own strengths and weaknesses. One Python-based product which is becoming widely used in scientific circles is Numpy, together with its sister-library Scipy. The core numeric routines in Numpy and Scipy are mostly written in C and Fortran, but the interface is designed for use with Python. http://www.numpy.org/ http://www.scipy.org/ Another Python product is SAGE, which aims to be a free alternative to Maple, Mathematica and other similar products. http://www.sagemath.org/ The idea is to create a group of powerful maths, statistics and scientific libraries. Those libraries can use whatever language they want, and often they are written in C and Fortran, but the glue that holds them together is Python. Together, they combine the power of low-level, hard-to-use but powerful fast languages like Fortran and C with the ease of use and convenience of modern high-level languages like Python. The core of scientific computing with Python includes: Numpy - fast N-dimensional array calculations Scipy - scientific computing libraries Matplotlib - 2D graphing IPython - enhanced interactive console with Mathematica-like notebook Sympy - symbolic mathematics Pandas - data analysis SAGE - integrated scientific computing system Parts of these are written in Python, and parts in C, Fortran, Javascript, and potentially any language imaginable. I also expect that people can start using PyPy to run pure-Python code almost as fast as C: http://pypy.org/ Or they can use Cython to write C code using Python syntax: http://cython.org/ All of these are parts of the Python ecosystem, and are why Python is currently becoming the go-to language for scientific computing. Where scientists used to write code in Fortran (hard and slow to write, but fast to run) or expensive proprietary products like Mathematica or Matlab, many people are gradually moving towards the Python ecosystem of Python, Numpy, IPython notebooks, and others. This post explains Python's advantages over Matlab, why the author thinks that scientific computing will continue to move towards Python, and links to a number of other good articles from people who already have done so. http://cyrille.rossant.net/why-using-python-for-scientific-computing/ My advice if you want to be a good scientific programmer: - Stay with Python. Anyone who tries to tell you that you need to know how to program in Fortran or C to do scientific computing is wrong. - Learn how to program in Python as well as possible. - Learn when *not* to program in Python, and know when to use existing tools already written in C, Fortran or other languages. Chances are very good that Numpy, Scipy and others above already solve some of your problems. - If
Re: [Tutor] Hi
Greetings Steven, Much great advice snipped. Is it possible (using U+1F600 through U+1F64F or otherwise) to offer a standing ovation for such a relevant, thorough, competent and well-written reply? Thank you, as always, -Martin (You know, Steven, we had gotten so accustomed to your slapdash answers, that this one comes as a huge surprise.) -- Martin A. Brown http://linux-ip.net/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Hi!
Hello. I am new to python and mailing lists. Where should I post some code if I need to? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi!
On 09/11/2013 21:04, Vlad Olariu wrote: Hello. I am new to python and mailing lists. Where should I post some code if I need to? Here but only after you've read this http://sscce.org/ -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi!
On Sat, Nov 9, 2013 at 4:04 PM, Vlad Olariu florinvlad.ola...@gmail.com wrote: Hello. I am new to python and mailing lists. Where should I post some code if I need to? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor Tell us your python version and OS version Try to create a small code example that shows the question you have. If you get an error in your code, copy and paste the complete traceback here Some people post to pastebin, but many others don't like that. So, best to keep example small and post here Finally, post in plaintext, not html -- 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] Hi!
Hello, On Sun, Nov 10, 2013 at 7:04 AM, Vlad Olariu florinvlad.ola...@gmail.com wrote: Hello. I am new to python and mailing lists. Where should I post some code if I need to? Welcome. Here is an example of a post with code. Assume that I am explaining to someone how they can exit out a while loop before the condition violated the first time: A while loop is an example of an entry controlled loop. This means that the condition is checked before entering the loop. Hence, this means if your loop condition was violated during the previous iteration, but not at the beginning, your loop will terminate after the first violation, not before it. Here is a simple example: a = 1 while a 5: ... a = a+3 ... print a ... 4 7 .. and so on. Also switch to Plain Text in your Gmail window before you post. (if you do not know what this means, please search on the Web a bit). Good Luck. Best. Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] hi
On 20 August 2013 13:49, Vick vick1...@orange.mu wrote: From: Oscar Benjamin [mailto:oscar.j.benja...@gmail.com] Well just send me some tutorial on how to build and obtain the coefficients for the butcher tableau for the RK4 as an example, and after I've mastered it, I'd give the dopri8 a shot. I am up for it so I'll see if I can find time to write a script that shows how to do it. [Vick] Hope you've had the time to code it. I'm waiting for it. Sorry, I haven't found the time yet. It is still on my todo list though! By the way your code for the Adams-Moulton coefficients are actually the Adams-Bashforth ones and so I copied it and modified the copy to have the Adams-Moulton coefficients as well. This means that I have now an nth-order predictor-corrector method to solve for ODEs. Oh sorry. That'll be a cut and paste error. My code lives in a private software library that I keep meaning to release on PyPI but it's not ready for public consumption in quite a number of ways. I'm glad that you worked it out though. You''ll probably understand what I mean now when I say that the AM or AB integrators need a secondary algorithm to bootstrap. The accuracy of the subsequent AM/AB method depends on the accuracy of that step. In the worst case you can just use rk4 with a very small time-step for this bit though. Oscar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] hi
-Original Message- From: Oscar Benjamin [mailto:oscar.j.benja...@gmail.com] Sent: Tuesday, 13 August, 2013 01:01 Well just send me some tutorial on how to build and obtain the coefficients for the butcher tableau for the RK4 as an example, and after I've mastered it, I'd give the dopri8 a shot. I am up for it so I'll see if I can find time to write a script that shows how to do it. [Vick] Hope you've had the time to code it. I'm waiting for it. By the way your code for the Adams-Moulton coefficients are actually the Adams-Bashforth ones and so I copied it and modified the copy to have the Adams-Moulton coefficients as well. This means that I have now an nth-order predictor-corrector method to solve for ODEs. Vick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] hi
Hi, It just plot one line. How to print several lines? I've attached your example and I've corrected my own 3d code which works now but it is not an animation. So how can I plot it using the code you gave me? By the way, I think you know that I'm trying to plot for n-body problem? Have you made a python code for the n-body problem? Mine works, but I'm just having trouble with 3d plotting of the orbits. And also I have searched the web on how to integrate conservation of energy as you suggested to me, but I couldn't find any article that talks about 1st order ODEs for energy, and the annotation is different from mine. PS: Also how do you make the plot run only once without having to do it over and over again? Thanks Vick -Original Message- From: Oscar Benjamin [mailto:oscar.j.benja...@gmail.com] Sent: Tuesday, 06 August, 2013 18:40 To: Vick Cc: tutor@python.org Subject: Re: [Tutor] hi On 1 August 2013 12:32, Vick vick1...@orange.mu wrote: Hi, Hi Vick, sorry I've been away and I've only had a chance to look at this now. As per your request below, I have attached a stand-alone example (test3d.py) of my problem. I am trying to plot in 3D using ion() from a loop. Basically don't use ion() for animation: it is intended for interactive use. Use matplotlib's animation API for animation. See here: http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/ I've put example scripts below. Both run fine on this computer. You'll want a recent matplotlib version. Here's a 2d animation script: #!/usr/bin/env python # 2d animation import numpy as np from matplotlib import pyplot as plt from matplotlib import animation fig = plt.figure(figsize=(5, 5)) ax = fig.add_axes([0.15, 0.15, 0.70, 0.70]) line, = ax.plot([], [], linewidth=2) def init(): ax.set_xlim([-1, 1]) ax.set_ylim([-1, 1]) line.set_data([], []) return line, def animate(i): t = dt * np.arange(i) x = np.cos(omega * t) y = np.sin(omega * t) line.set_data(x, y) return line, dt = .02 # in seconds T = 10 # Period (seconds) omega = 2 * np.pi / T # 0.1 Hz anim = animation.FuncAnimation(fig, animate, init_func=init, frames=int(T/dt), interval=int(1000*dt), blit=True) plt.show() And here's a 3d script: #!/usr/bin/env python # 3d animation import numpy as np from matplotlib import pyplot as plt from matplotlib import animation from mpl_toolkits.mplot3d import Axes3D fig = plt.figure(figsize=(5, 5)) ax = fig.add_axes([0.15, 0.15, 0.70, 0.70], projection='3d') line, = ax.plot([], [], [], linewidth=2) def init(): ax.set_xlim([-1, 1]) ax.set_ylim([-1, 1]) ax.set_zlim([0, 10]) line.set_data([], []) return line, def animate(i): t = dt * np.arange(i) x = np.cos(omega * t) y = np.sin(omega * t) z = t line.set_data(x, y) line.set_3d_properties(z) # WTF! return line, dt = .02 # in seconds T = 10 # Duration (seconds) omega = 2 * np.pi # 1 Hz anim = animation.FuncAnimation(fig, animate, init_func=init, frames=int(T/dt), interval=int(1000*dt), blit=True) plt.show() Oscar from pylab import * #import pylab from mpl_toolkits.mplot3d.axes3d import Axes3D import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d def drange(start, stop, step): r = start while r stop: yield r r += step a=[] b=[] z1=[] c=[] d=[] z2=[] #plt.ion() fig = plt.figure(dpi=100) ax = axes3d.Axes3D(fig)#fig.add_subplot(111, projection = '3d') t = 0 dt = 1 tn= 50 for i in drange (t+dt, tn,dt): aa = sin(i) bb = cos(i) cc = aa*bb aa1 = 1.5 *sin(i) bb1 = 1.5*cos(i) cc1 = aa1*bb1 a.append(aa) b.append(bb) z1.append(cc) c.append(aa1) d.append(bb1) z2.append(cc1) #clf() #ax.plot(a,b,z1, marker='o', linestyle='None') #ax.plot(c,d,z2, marker='o', linestyle='None') ax.plot(a,b,z1) ax.plot(c,d,z2) plt.show() #!/usr/bin/env python # 2d animation import numpy as np from matplotlib import pyplot as plt from matplotlib import animation fig = plt.figure(figsize=(5, 5)) ax = fig.add_axes([0.15, 0.15, 0.70, 0.70]) line, = ax.plot([], [], linewidth=2) def init(): ax.set_xlim([-1, 1]) ax.set_ylim([-1, 1]) line.set_data([], []) return line, def animate(i): t = dt * np.arange(i) x = np.cos(omega * t) y = np.sin(omega * t) line.set_data(x, y) return line, dt = .02 # in seconds T = 10 # Period (seconds) omega = 2 * np.pi / T # 0.1 Hz anim = animation.FuncAnimation(fig, animate, init_func=init, frames=int(T/dt), interval=int(1000*dt), blit=True) plt.show() #!/usr/bin/env python # 3d animation import numpy as np from matplotlib import pyplot as plt from matplotlib import animation from mpl_toolkits.mplot3d import Axes3D fig = plt.figure(figsize=(5, 5)) ax = fig.add_axes([0.15, 0.15, 0.70, 0.70], projection='3d') line, = ax.plot
Re: [Tutor] hi
Hi, As per your request below, I have attached a stand-alone example (test3d.py) of my problem. I am trying to plot in 3D using ion() from a loop. The code should plot x,y,z coordinates from a loop in ion(). We should see the plot line moving and the marker moving as well. I have also attached a working 2d-plot (test2d.py) to show what it's supposed to do. The 3d plot (test3d.py) should plot the same but with an additional z coordinates and a z axis! Thanks Vick -Original Message- From: Oscar Benjamin [mailto:oscar.j.benja...@gmail.com] Sent: Thursday, 01 August, 2013 01:42 To: Vick Subject: Re: [Tutor] hi On 31 July 2013 22:20, Vick vick1...@orange.mu wrote: Hello, Hi Vick, I would prefer it if you would send questions like this to the tutor mailing list rather than directly to me. This is because: 1) I'm often unable to respond and there are many other people there who could help (I may be the only one there who understands ODEs but I'm certainly not the only one who understands matplotlib). 2) It's helpful for others on the tutor mailing list to see the kind of problems (and solutions) that people new to Python are working with. 3) Any problem/solution gets publicly archived for future reference. Can you help me please with plotting in 3D using ion()? My code is the following: from pylab import * #import pylab from mpl_toolkits.mplot3d.axes3d import Axes3D import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d plt.ion() fig = plt.figure(dpi=100) ax = axes3d.Axes3D(fig)#fig.add_subplot(111, projection = '3d') tn= mpf('300')#mpf('800')*dt for i in drange (t+dt, tn,dt): mi = testran(i,mi,dt) #print i+ dt, , mi a.append(mi[0]) b.append(mi[1]) z1.append(mi[2]) c.append(mi[6]) d.append(mi[7]) z2.append(mi[8]) #clf() ax.plot(a,b,z1)#linestyle='None', marker='o', markersize = 5) ax.plot(a,b,z1, marker='o', linestyle='None') ax.plot(c,d,z2) ax.plot(c,d,z2, marker='o', linestyle='None') #draw() #grid() #show() I'm trying to plot in 3D, coordinates that are appended from a loop using ion(), but it doesn't plot. I get something different: $ python plot3d.py Traceback (most recent call last): File plot3d.py, line 13, in module tn= mpf('300')#mpf('800')*dt NameError: name 'mpf' is not defined Where does the mpf function come from? There are many other symbols that are not defined (t, dt, testran, ...) so presumably this code is incomplete somehow. Could you please make a complete example illustrating the problem you have and then post it to the tutor list? Oscar from pylab import * import matplotlib.pyplot as plt def drange(start, stop, step): r = start while r stop: yield r r += step a=[] b=[] z1=[] c=[] d=[] z2=[] plt.ion() fig = plt.figure(dpi=100) ax = fig.add_subplot(111) t = 0 dt = 1 tn= 50 for i in drange (t+dt, tn,dt): aa = sin(i) bb = cos(i) aa1 = 1.5 *sin(i) bb1 = 1.5*cos(i) a.append(aa) b.append(bb) c.append(aa1) d.append(bb1) clf() plot(a,b)#linestyle='None', marker='o', markersize = 5) plot(aa,bb, marker='o', linestyle='None') plot(c,d) plot(aa1,bb1, marker='o', linestyle='None') draw() #grid() #show() from pylab import * #import pylab from mpl_toolkits.mplot3d.axes3d import Axes3D import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d def drange(start, stop, step): r = start while r stop: yield r r += step a=[] b=[] z1=[] c=[] d=[] z2=[] plt.ion() fig = plt.figure(dpi=100) ax = axes3d.Axes3D(fig)#fig.add_subplot(111, projection = '3d') t = 0 dt = 1 tn= 50 for i in drange (t+dt, tn,dt): aa = sin(i) bb = cos(i) cc = aa*bb aa1 = 1.5 *sin(i) bb1 = 1.5*cos(i) cc1 = aa1*bb1 a.append(aa) b.append(bb) z1.append(cc) c.append(aa1) d.append(bb1) z2.append(cc1) #clf() ax.plot(a,b,z1)#linestyle='None', marker='o', markersize = 5) ax.plot(a,b,z1, marker='o', linestyle='None') ax.plot(c,d,z2) ax.plot(c,d,z2, marker='o', linestyle='None') plt.draw() #grid() #show() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] hi
Hello, Thanks for taking the time to reply! However, I had already solved the problem a few days ago on my own. The DOPRI 8(7)13 is the Dormand Prince 8th order with 13 stages method for solving http://en.wikipedia.org/wiki/Ordinary_differential_equations ordinary differential equations. It is a member of the Runge-Kutta family of ODE solvers. I have been able to reproduce it in Python with a multi-variable capability. On a particular test equation the error of the RK4 is about 1e-4 whereas the DOPRI 8(7)13 is about 1e-13. I have then used the multi-variable DOPRI to compute for the n-body problem using 1st order ODEs which requires you to have 4 equations for 1 planet. I have already made a 10-body problem through an n-body solver in python and using DOPRI as my integrator. It works fine. Thanks again for your time and consideration. Regards Vick -Original Message- From: Oscar Benjamin [mailto:oscar.j.benja...@gmail.com] Sent: Monday, 22 July, 2013 15:59 To: Vick Cc: Tutor@python.org Subject: Re: [Tutor] hi On 12 July 2013 11:08, Vick mailto:vick1...@orange.mu vick1...@orange.mu wrote: Hi, Hi Vick, Sorry for the delayed response I didn't see this email until a while after you sent it. I have written a code to perform a numerical solution to 1st order Ordinary Differential Equations (ODEs). I have written codes for the famous Runge Kutta 4th order and the DOPRI 8(7)13. However the codes are for 1 variable only; viz. the y variable. It would be good to show us the code for this in your email (not in an attachment). Also the code should be complete: the code uses a function rungkdp8 which is not shown. Where did that come from? Until you know what you're doing you should test your integrator on a simpler set of equations. Also when posting to a mailing list you should simplify the problem as much as possible which would mean using simpler ODEs. In short read this: http://sscce.org/ http://sscce.org/ The code attached is incorrect as it applies each stage of the Runge-Kutta method to all time-steps sequentially before moving on to the next stage. It should apply each stage for one time step and then use the output of that for the next time-step. In other words you need to change the order of the loops. Here is an example of how to implement an Euler stepper that should hopefully get you started on the right track. I've deliberately avoided using numpy in this example even though it makes most of this easier. I did this to focus on the basics of Python which you should learn first. # integrator.py nan = float('nan') # indices for the two variables in the system POS = 0 VEL = 1 VARS = ['pos', 'vel'] # system has one parameter OMEGA OMEGA = 10 # Frequency in Hz is OMEGA / 2pi # function for the derivative of the system def shm(t, x, dxdt): '''Equation of motion for a mass in a spring with freq OMEGA''' dxdt[POS] = x[VEL] # Python uses square brackets for indexing dxdt[VEL] = - OMEGA**2 * x[POS] # Initial conditions for the problem x0 = [nan] * 2 x0[POS] = 1 x0[VEL] = 0 # This is the function that you should replace with e.g. rk4 or dopri8 def euler(t1, x1, t2): '''Take 1 Euler step from x1 at t1 to x2 at t2''' # Create empty lists for answer x2 = [nan] * len(x1) dxdt = [nan] * len(x1) # Call derivative function to fill in dxdt shm(t1, x1, dxdt) # Compute x2 and return dt = t2 - t1 for n in range(len(x1)): x2[n] = x1[n] + dt * dxdt[n] return x2 def solve(ts, x0): '''Compute states corresponding to the times in ts x0 is the state at ts[0] (the initial condition). ''' # Create an empty list of lists for the solution Xt = [x0[:]] # The initial conditions # Loop through timesteps computing the next value for n in range(len(ts) - 1): Xt.append(euler(ts[n], Xt[n], ts[n+1])) return Xt def print_line(*items): print(', '.join(str(i) for i in items)) def print_solution(ts, Xt, vars): print_line('t', *vars) for t, x in zip(times, Xt): print_line(t, *x) # Numerical parameters for the solution DT = 0.001 t0 = 0 T = 1 times = [t0] while times[-1] T: times.append(times[-1] + DT) # Solve and print Xt = solve(times, x0) print_solution(times, Xt, VARS) I have written another code in Excel VBA for DOPRI 8 for a multi-variable capability. However I have not been able to reproduce it in Python. I'm having trouble in making arrays or lists, I don't know which is supposed to work. I have attached my Excel VBA code for a multi-variable numerical integrator in PDF format. This does work in Excel. I have also attached my python code. I'm not familiar with Excel VBA but I think that this code suffers from the same problem that the loop over stages takes place outside the loop over time-steps so I believe
Re: [Tutor] hi
On Fri, Jul 12, 2013 at 6:08 AM, Vick vick1...@orange.mu wrote: Hi, ** ** I’m using Windows 7 and Python 2.7.3 ** ** I have written a code to perform a numerical solution to 1st order Ordinary Differential Equations (ODEs). I have written codes for the famous Runge Kutta 4th order and the DOPRI 8(7)13. However the codes are for 1 variable only; viz. the “y” variable. ** ** I have written another code in Excel VBA for DOPRI 8 for a multi-variable capability. However I have not been able to reproduce it in Python. I’m having trouble in making arrays or lists, I don’t know which is supposed to work. ** ** I have attached my Excel VBA code for a multi-variable numerical integrator in PDF format. This does work in Excel. I have also attached my python code. ** ** Can anyone help me out please? So are you saying your python code doesn't run, or it runs but doesn't give the same answers as your vb code? If your python code throws an exception you should list the traceback for better help. Also, try using a better subject line next time. Thanks Vick ** ** ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick http://joelgoldstick.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Hi, First question
Hi so I am making a bit of code to extract a bit of numbers data from a file and then find the average of that data, however while I can get the code to extract each specific piece of data I need, I can't seem to get the numbers to add separately so I can get a proper average. My sum1 variable seems to only take the last bit of data entered. I was just wondering if anyone knows what I'm doing wrong, the course I'm following hadn't started using regex (or even proper lists) at this point, so there must be a way to do it without. here's the code. the average of the data should be 0.6789 or something, but I get 0.0334343 or something. count=0 lst=list() fname='mbox-short.txt' fhand=open(fname) for line in fhand: if line.startswith('X-DSPAM-Confidence:'): count=count+1 colpos=line.find(':') zpos=line.find('0',colpos) num=float(line[zpos:50]) sum1=0+num avg=float(sum1)/int(count) print 'Count-', count,'--', 'Average-', avg Any help at all is appreciated, and thanks in advance. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi, First question
On Sat, Jun 15, 2013 at 1:22 AM, Patrick Williams pdw0...@gmail.com wrote: Hi so I am making a bit of code to extract a bit of numbers data from a file and then find the average of that data, however while I can get the code to extract each specific piece of data I need, I can't seem to get the numbers to add separately so I can get a proper average. My sum1 variable seems to only take the last bit of data entered. I was just wondering if anyone knows what I'm doing wrong, the course I'm following hadn't started using regex (or even proper lists) at this point, so there must be a way to do it without. here's the code. the average of the data should be 0.6789 or something, but I get 0.0334343 or something. count=0 lst=list() fname='mbox-short.txt' fhand=open(fname) for line in fhand: if line.startswith('X-DSPAM-Confidence:'): count=count+1 colpos=line.find(':') zpos=line.find('0',colpos) num=float(line[zpos:50]) sum1=0+num avg=float(sum1)/int(count) print 'Count-', count,'--', 'Average-', avg Any help at all is appreciated, and thanks in advance. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Please include the mbox-short.txt file. Also you should include the output of your code (copy and paste it). -- Alexander ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi, First question
On Sat, Jun 15, 2013 at 7:22 AM, Patrick Williams pdw0...@gmail.com wrote: Hi so I am making a bit of code to extract a bit of numbers data from a file and then find the average of that data, however while I can get the code to extract each specific piece of data I need, I can't seem to get the numbers to add separately so I can get a proper average. My sum1 variable seems to only take the last bit of data entered. I was just wondering if anyone knows what I'm doing wrong, the course I'm following hadn't started using regex (or even proper lists) at this point, so there must be a way to do it without. here's the code. the average of the data should be 0.6789 or something, but I get 0.0334343 or something. count=0 lst=list() `lst = []` is the preferred syntax. fname='mbox-short.txt' fhand=open(fname) for line in fhand: if line.startswith('X-DSPAM-Confidence:'): count=count+1 colpos=line.find(':') zpos=line.find('0',colpos) num=float(line[zpos:50]) sum1=0+num avg=float(sum1)/int(count) print 'Count-', count,'--', 'Average-', avg Any help at all is appreciated, and thanks in advance. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor I don’t know what file you used, but the message you sent got this header from Gmail, and the format doesn’t seem to be much different: X-Spam-Evidence: '*H*': 0.79; '*S*': 0.00; 'separately': 0.09; 'wrong,': 0.09; 'subject:question': 0.10; 'code.': 0.18; 'variable': 0.18; 'bit': 0.19; 'advance.': 0.19; 'seems': 0.21; '8bit%:5': 0.22; 'print': 0.22; 'skip:l 30': 0.24; '\xa0so': 0.24; [snip 11 more lines] (replaced tabstops with spaces) Can you guess what’s wrong in your code? You are reading only the first line. There are more. How do you handle that? You need to make your algorithm read all the further lines that begin with the indentation your thing uses (it might be the tab character '\t' or some spaces), and stop when it encounters another header. This can be done either by checking if the line begins with the indentation OR by checking match with regexp '[A-Za-z]+: .+' -- Kwpolska http://kwpolska.tk | GPG KEY: 5EAAEA16 stop html mail| always bottom-post http://asciiribbon.org| http://caliburn.nl/topposting.html ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi, First question
On 16/06/2013 16:55, Chris “Kwpolska” Warrick wrote: On Sat, Jun 15, 2013 at 7:22 AM, Patrick Williams pdw0...@gmail.com wrote: Hi so I am making a bit of code to extract a bit of numbers data from a file and then find the average of that data, however while I can get the code to extract each specific piece of data I need, I can't seem to get the numbers to add separately so I can get a proper average. My sum1 variable seems to only take the last bit of data entered. I was just wondering if anyone knows what I'm doing wrong, the course I'm following hadn't started using regex (or even proper lists) at this point, so there must be a way to do it without. here's the code. the average of the data should be 0.6789 or something, but I get 0.0334343 or something. count=0 lst=list() `lst = []` is the preferred syntax. fname='mbox-short.txt' fhand=open(fname) for line in fhand: if line.startswith('X-DSPAM-Confidence:'): count=count+1 colpos=line.find(':') zpos=line.find('0',colpos) num=float(line[zpos:50]) sum1=0+num avg=float(sum1)/int(count) I'll assume unless someone tells me differently that sum1 does not need reinitialising every time, and that avg needs to be calculated when the loop has finished. print 'Count-', count,'--', 'Average-', avg Any help at all is appreciated, and thanks in advance. I don’t know what file you used, but the message you sent got this header from Gmail, and the format doesn’t seem to be much different: X-Spam-Evidence: '*H*': 0.79; '*S*': 0.00; 'separately': 0.09; 'wrong,': 0.09; 'subject:question': 0.10; 'code.': 0.18; 'variable': 0.18; 'bit': 0.19; 'advance.': 0.19; 'seems': 0.21; '8bit%:5': 0.22; 'print': 0.22; 'skip:l 30': 0.24; '\xa0so': 0.24; [snip 11 more lines] (replaced tabstops with spaces) Can you guess what’s wrong in your code? You are reading only the first line. What does for line in fhand: do then? -- Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green. Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi, First question
On 16-Jun-2013, at 09:21, Mark Lawrence breamore...@yahoo.co.uk wrote: On 16/06/2013 16:55, Chris “Kwpolska” Warrick wrote: On Sat, Jun 15, 2013 at 7:22 AM, Patrick Williams pdw0...@gmail.com wrote: Hi so I am making a bit of code to extract a bit of numbers data from a file and then find the average of that data, however while I can get the code to extract each specific piece of data I need, I can't seem to get the numbers to add separately so I can get a proper average. My sum1 variable seems to only take the last bit of data entered. I was just wondering if anyone knows what I'm doing wrong, the course I'm following hadn't started using regex (or even proper lists) at this point, so there must be a way to do it without. here's the code. the average of the data should be 0.6789 or something, but I get 0.0334343 or something. count=0 lst=list() `lst = []` is the preferred syntax. fname='mbox-short.txt' fhand=open(fname) for line in fhand: if line.startswith('X-DSPAM-Confidence:'): count=count+1 colpos=line.find(':') zpos=line.find('0',colpos) num=float(line[zpos:50]) sum1=0+num avg=float(sum1)/int(count) I'll assume unless someone tells me differently that sum1 does not need reinitialising every time, and that avg needs to be calculated when the loop has finished. print 'Count-', count,'--', 'Average-', avg Any help at all is appreciated, and thanks in advance. I don’t know what file you used, but the message you sent got this header from Gmail, and the format doesn’t seem to be much different: X-Spam-Evidence: '*H*': 0.79; '*S*': 0.00; 'separately': 0.09; 'wrong,': 0.09; 'subject:question': 0.10; 'code.': 0.18; 'variable': 0.18; 'bit': 0.19; 'advance.': 0.19; 'seems': 0.21; '8bit%:5': 0.22; 'print': 0.22; 'skip:l 30': 0.24; '\xa0so': 0.24; [snip 11 more lines] (replaced tabstops with spaces) Can you guess what’s wrong in your code? You are reading only the first line. What does for line in fhand: do then? I think what that was referring to was the assumption that you're reading mail header lines from that file, and they can be split out over multiple lines (see the example cited above). If that's the case, then for line in fhand will iterate over each line in the file, but you're only looking for lines which start with X-Spam-.. which would only be the FIRST part of the header if it's split out like that. If your file is NOT organized like that, then your situation is different. However, if your files are like that, you're going to randomly miss data if the fields you're looking for don't happen to be on the first line of the multi-line header. Now if you are reading RFC-822 (et al) standard mail messages in those files, there are bits of the Python standard library which will be immensely useful to you in parsing out those headers rather than trying to do it yourself. That's something you're going to find to be the case frequently with Python. -- Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green. Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi, First question
On 15/06/13 06:22, Patrick Williams wrote: Hi so I am making a bit of code to extract a bit of numbers data from a file and then find the average of that data, however while I can get the code to extract each specific piece of data I need, I can't seem to get the numbers to add separately so I can get a proper average. My sum1 variable seems to only take the last bit of data entered. for line in fhand: if line.startswith('X-DSPAM-Confidence:'): count=count+1 colpos=line.find(':') zpos=line.find('0',colpos) num=float(line[zpos:50]) sum1=0+num Are you sure that last line is right? Its effectively just doing sum1 = num adding zero does nothing interesting. So sum1 ends up at whatever num was at the end of the loop. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Hi Folks...Need help with a modified version of the Subset sum problem.
Hi there Tutor folks I need your help with a modified version of the subset sum problem [ http://en.wikipedia.org/wiki/Subset_sum_problem]. The problem i am facing is a bit hard to describe (as most complex problem always are :D ), so please bear with my longish articulation :) Here it goes : After scrubbing some input data, i have two lists 'minutes' (elements are positive integers) 'names' (elements are strings). They are the exact same length and each element of one corresponds exactly with the respective element of the other. The elements in the minutes list are not unique; a sample list is : minutes = [60, 45, 30, 45, 45, 5, 60, 45, 30, 30, 45, 60, 60, 45, 30, 30, 60, 30, 30 ] names = ['abc', 'ghi', 'jkl', 'def', 'zab', 'wux', ... ] Now i need to pick some elements from the 'minutes' list (i.e. a subset of minutes) which add up to a certain sum ('target_sum1'). I have to then do some processing with the *respective elements from the 'names' list, corresponding to, the elements i just picked from the 'minutes' list which sum upto target_sum1.* I now have to remove these elements i picked (which add up to 'target_sum1' ) from the 'minutes' list, and essentially do a second pass, picking some elements, which add up to a certain other sum ('target_sum2'). Again, *retrieve the elements from the 'names' list*, *corresponding to the elements i just picked which sum upto 'target_sum2'*, do some processing on them. And so on. Picking a subset of numbers, which add up to a certain target sum, is a well-known problem[1] i have found the following code for it [2] : I also have the code on a github gist https://gist.github.com/anonymous/5620886 def subset_sum_recursive(numbers,target,partial): s = sum(partial) #check if the partial sum is equals to target if s == target: print sum(%s)=%s%(partial,target) if s = target: return # if we reach the number why bother to continue for i in range(len(numbers)): n = numbers[i] remaining = numbers[i+1:] subset_sum_recursive(remaining,target,partial + [n]) def subset_sum(numbers,target): #we need an intermediate function to start the recursion. #the recursion starts with an empty list as partial solution. subset_sum_recursive(numbers,target,list()) if __name__ == __main__: minutes = [3,9,8,4,5,7,10] target_sum = 15 subset_sum(minutes,target_sum) #Outputs: #sum([3, 8, 4])=15 #sum([3, 5, 7])=15 #sum([8, 7])=15 #sum([5, 10])=15 This above code returns the elements of the 'minutes' list(subset of the 'minutes' list) which add up to 'target_sum'. *I am stuck on this point : * *I am unable to determine the list indices, of the elements of 'minutes' which add upto 'target_sum1', so i can retrieve the corresponding elements from the 'names' list, do my processing on them.* * * *I also need the list indices to remove the elements which add upto target_sum1, and then run a second pass, to determine the elements which add upto 'target_sum2'.* Any all explanations/links/code snippets/thoughts/ideas/suggestions/feedback/comments/ of the Python tutor community would be greatly appreciated. Thanks a ton, calvin spiff...@gmail.com References 1. http://en.wikipedia.org/wiki/Subset_sum_problem 2. http://stackoverflow.com/a/4633515/559456 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi Folks...Need help with a modified version of the Subset sum problem.
spiff007 wrote: Hi there Tutor folks I need your help with a modified version of the subset sum problem [ http://en.wikipedia.org/wiki/Subset_sum_problem]. The problem i am facing is a bit hard to describe (as most complex problem always are :D ), so please bear with my longish articulation :) Here it goes : After scrubbing some input data, i have two lists 'minutes' (elements are positive integers) 'names' (elements are strings). They are the exact same length and each element of one corresponds exactly with the respective element of the other. The elements in the minutes list are not unique; a sample list is : minutes = [60, 45, 30, 45, 45, 5, 60, 45, 30, 30, 45, 60, 60, 45, 30, 30, 60, 30, 30 ] names = ['abc', 'ghi', 'jkl', 'def', 'zab', 'wux', ... ] Now i need to pick some elements from the 'minutes' list (i.e. a subset of minutes) which add up to a certain sum ('target_sum1'). I have to then do some processing with the *respective elements from the 'names' list, corresponding to, the elements i just picked from the 'minutes' list which sum upto target_sum1.* I now have to remove these elements i picked (which add up to 'target_sum1' ) from the 'minutes' list, and essentially do a second pass, picking some elements, which add up to a certain other sum ('target_sum2'). Again, *retrieve the elements from the 'names' list*, *corresponding to the elements i just picked which sum upto 'target_sum2'*, do some processing on them. And so on. Picking a subset of numbers, which add up to a certain target sum, is a well-known problem[1] i have found the following code for it [2] : I also have the code on a github gist https://gist.github.com/anonymous/5620886 def subset_sum_recursive(numbers,target,partial): s = sum(partial) #check if the partial sum is equals to target if s == target: print sum(%s)=%s%(partial,target) if s = target: return # if we reach the number why bother to continue for i in range(len(numbers)): n = numbers[i] remaining = numbers[i+1:] subset_sum_recursive(remaining,target,partial + [n]) def subset_sum(numbers,target): #we need an intermediate function to start the recursion. #the recursion starts with an empty list as partial solution. subset_sum_recursive(numbers,target,list()) if __name__ == __main__: minutes = [3,9,8,4,5,7,10] target_sum = 15 subset_sum(minutes,target_sum) #Outputs: #sum([3, 8, 4])=15 #sum([3, 5, 7])=15 #sum([8, 7])=15 #sum([5, 10])=15 This above code returns the elements of the 'minutes' list(subset of the 'minutes' list) which add up to 'target_sum'. *I am stuck on this point : * *I am unable to determine the list indices, of the elements of 'minutes' which add upto 'target_sum1', so i can retrieve the corresponding elements from the 'names' list, do my processing on them.* I think the easiest approach is to combine the two lists into a single one pairs = zip(names, minutes) or, if you really need the indices pairs = list(enumerate(minutes)) and invoke subset_sum() with these pairs instead of minutes alone. Of course you have to modify the sum() call to unpack the pairs: s = sum(value for index, value in partial) *I also need the list indices to remove the elements which add upto target_sum1, and then run a second pass, to determine the elements which add upto 'target_sum2'.* Any all explanations/links/code snippets/thoughts/ideas/suggestions/feedback/comments/ of the Python tutor community would be greatly appreciated. Thanks a ton, calvin spiff...@gmail.com References 1. http://en.wikipedia.org/wiki/Subset_sum_problem 2. http://stackoverflow.com/a/4633515/559456 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi
Luke Pettit petl...@gmail.com wrote I was interested in which video tutorials Glen was watching, and if anyone else could recommend some video tutorials to watch, I don;t know what Glen was watching but thhere are a whole bunch of videos at showmedo.com Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi
Thanks Alan I found those about an hour ago :) On 6 November 2010 20:11, Alan Gauld alan.ga...@btinternet.com wrote: Luke Pettit petl...@gmail.com wrote I was interested in which video tutorials Glen was watching, and if anyone else could recommend some video tutorials to watch, I don;t know what Glen was watching but thhere are a whole bunch of videos at showmedo.com Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Luke Pettit ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi
Luke, I used a video from Lynda.com, simply because I already had a subscription. The price was about $25 per month which I think is more expensive that showmedo. Or you could buy it for $99 (Python 3 Essential Training (DVD-ROM)). The video's were very good for me personally because he was straight to the point which kept me from getting bored. I have recently found showmedo though and they does loog very good also. It seems to have a lot of content on there. Regards, Glen On Sat, 2010-11-06 at 21:29 +1100, Luke Pettit wrote: Thanks Alan I found those about an hour ago :) On 6 November 2010 20:11, Alan Gauld alan.ga...@btinternet.com wrote: Luke Pettit petl...@gmail.com wrote I was interested in which video tutorials Glen was watching, and if anyone else could recommend some video tutorials to watch, I don;t know what Glen was watching but thhere are a whole bunch of videos at showmedo.com Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Luke Pettit ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi
Also, if you have not yet chosen an IDE I recommend eclipse with the pydev extension. Google them or if you use gnu/linux (like ubuntu) you can get it from the package manager. It is a very simple interface, with syntax highlighting, debug mode and console. On Sat, 2010-11-06 at 14:45 +, Glen Clark wrote: Luke, I used a video from Lynda.com, simply because I already had a subscription. The price was about $25 per month which I think is more expensive that showmedo. Or you could buy it for $99 (Python 3 Essential Training (DVD-ROM)). The video's were very good for me personally because he was straight to the point which kept me from getting bored. I have recently found showmedo though and they does loog very good also. It seems to have a lot of content on there. Regards, Glen On Sat, 2010-11-06 at 21:29 +1100, Luke Pettit wrote: Thanks Alan I found those about an hour ago :) On 6 November 2010 20:11, Alan Gauld alan.ga...@btinternet.com wrote: Luke Pettit petl...@gmail.com wrote I was interested in which video tutorials Glen was watching, and if anyone else could recommend some video tutorials to watch, I don;t know what Glen was watching but thhere are a whole bunch of videos at showmedo.com Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Luke Pettit ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi
I'd also point out that Google has created a very awesome Python course which is heavily dependent on video lectures by Nick Parlante. Included in the course are downloadable exercises and examples (all mentioned in the video lectures). After you review all of this quality (not to mention free) material... I think you'll fully understand what separates Google from its competitors. (By this, I simply mean that you will not see similar offerings from, say, Facebook, Apple, or MS.) http://code.google.com/edu/languages/google-python-class/index.html http://code.google.com/edu/languages/google-python-class/index.htmlThis is a part of Google's Google Code University. Here's the root URL for the entire project: http://code.google.com/edu/ -- definitely worth checking out. -trench On Fri, Nov 5, 2010 at 8:12 PM, Luke Pettit petl...@gmail.com wrote: Hi everyone, I'm just about to begin to learn python and have bookmarked a number of sites to learn from http://www.alan-g.me.uk/ is the main one but after reading this On Nov 4, 2010, at 3:10 PM, Glen Clark gle...@gmail.com wrote: Hello, I have completed my first python script. This is after watching a video guide on python and is my first attempt at writing code in python. While the code is not very useful I got the idea for it when googling python projects for beginners. I was interested in which video tutorials Glen was watching, and if anyone else could recommend some video tutorials to watch, mainly because of a mild dyslexia and preference for video tutorials. I have been learning Autodesk 3d Studio Max http://south-apac.autodesk.com/adsk/servlet/pc/index?siteID=1157326id=15474303 for several years and learning it's scripting language Maxscript http://rosettacode.org/wiki/Category:MAXScript and since Autodesk now own all the competitors software and they all (except Max) use Python for their coding I thought it would be the way to go when learning a new language. Blender also uses Python btw. My 3d site http://lukepettit-3d.blogspot.com/ -- Luke Pettit ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- - t ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi
Wow information overload lol Thanks everyone this is great. On 7 November 2010 13:43, trench trenchc...@gmail.com wrote: I'd also point out that Google has created a very awesome Python course which is heavily dependent on video lectures by Nick Parlante. Included in the course are downloadable exercises and examples (all mentioned in the video lectures). After you review all of this quality (not to mention free) material... I think you'll fully understand what separates Google from its competitors. (By this, I simply mean that you will not see similar offerings from, say, Facebook, Apple, or MS.) http://code.google.com/edu/languages/google-python-class/index.html http://code.google.com/edu/languages/google-python-class/index.htmlThis is a part of Google's Google Code University. Here's the root URL for the entire project: http://code.google.com/edu/ -- definitely worth checking out. -trench On Fri, Nov 5, 2010 at 8:12 PM, Luke Pettit petl...@gmail.com wrote: Hi everyone, I'm just about to begin to learn python and have bookmarked a number of sites to learn from http://www.alan-g.me.uk/ is the main one but after reading this On Nov 4, 2010, at 3:10 PM, Glen Clark gle...@gmail.com wrote: Hello, I have completed my first python script. This is after watching a video guide on python and is my first attempt at writing code in python. While the code is not very useful I got the idea for it when googling python projects for beginners. I was interested in which video tutorials Glen was watching, and if anyone else could recommend some video tutorials to watch, mainly because of a mild dyslexia and preference for video tutorials. I have been learning Autodesk 3d Studio Max http://south-apac.autodesk.com/adsk/servlet/pc/index?siteID=1157326id=15474303 for several years and learning it's scripting language Maxscript http://rosettacode.org/wiki/Category:MAXScript and since Autodesk now own all the competitors software and they all (except Max) use Python for their coding I thought it would be the way to go when learning a new language. Blender also uses Python btw. My 3d site http://lukepettit-3d.blogspot.com/ -- Luke Pettit ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- - t -- Luke Pettit ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Hi
Hi everyone, I'm just about to begin to learn python and have bookmarked a number of sites to learn from http://www.alan-g.me.uk/ is the main one but after reading this On Nov 4, 2010, at 3:10 PM, Glen Clark gle...@gmail.com wrote: Hello, I have completed my first python script. This is after watching a video guide on python and is my first attempt at writing code in python. While the code is not very useful I got the idea for it when googling python projects for beginners. I was interested in which video tutorials Glen was watching, and if anyone else could recommend some video tutorials to watch, mainly because of a mild dyslexia and preference for video tutorials. I have been learning Autodesk 3d Studio Max http://south-apac.autodesk.com/adsk/servlet/pc/index?siteID=1157326id=15474303 for several years and learning it's scripting language Maxscript http://rosettacode.org/wiki/Category:MAXScript and since Autodesk now own all the competitors software and they all (except Max) use Python for their coding I thought it would be the way to go when learning a new language. Blender also uses Python btw. My 3d site http://lukepettit-3d.blogspot.com/ -- Luke Pettit ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi everybody stuck on some error need help please thank you!!
(Don't top-post. Either put your remarks immediately after the part they reference, or at the end of the message. Otherwise, everything's thoroughly out of order.) Marco Rompré wrote: I tried to enter model = Modele (nom_fichier) but it still does not work. You didn't define the global nom_fichier till after that line. In general, while you're learning, please avoid using the same names for global values, class attributes, instance attributes, function parameter names, and local variables. The rules for what a name means changes depending on where the name is used. snip On Fri, Apr 23, 2010 at 11:22 PM, Steven D'Aprano st...@pearwood.infowrote: On Sat, 24 Apr 2010 01:07:11 pm Marco Rompré wrote: Here's my code: [...] class Modele: La definition d'un modele avec les magasins. def __init__(self, nom_fichier, magasins =[]): self.nom_fichier = nom_fichier self.magasins = magasins [...] if __name__ == '__main__': modele = Modele() This is where you got the error, because there's a required argument, for parameter nom_fichier. So you could use modele = Modele(thefile.txt) nom_fichier = magasinmodele.txt I'd call this something else, like g_nom_fichier. While you're learning, you don't want to get confused between the multiple names that look the same. modele.charger(nom_fichier) if modele.vide(): modele.initialiser(nom_fichier) modele.afficher() And here's my error : Traceback (most recent call last): File F:\School\University\Session 4\Programmation SIO\magasingolfmodele.py, line 187, in module modele = Modele() TypeError: __init__() takes at least 2 arguments (1 given) You define Modele to require a nom_fichier argument, but then you try to call it with no nom_fuchier. snip ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Hi everybody stuck on some error need help please thank you!!
Hi everybody, I would appreciate your help on this one In this program I want to create 2 concepts each with 2 or 3 properties My first concept is magasin(shop in french) and my shop has 3 attributes: nom(name in french), items and ville (city in french) the second one is items and its 2 attributes are nom(name in french) and prix (price in french) I want to be able to show a modele with the name of my magasins (stores) and the city theyre located in, what are the names of the items i have in each magasin and their prices. Here's my code: class Magasin: Le concept magasin pour la gestion d'inventaire des items de golf. def __init__(self, nom =, items =[], ville= ): self.nom = nom self.items = items self.vile = ville def set_nom(self, nom): self.nom = nom nom = property(None, set_nom) def set_items(self, items): self.items = items items = property(None, set_items) def set_ville(self, ville): self.ville = ville items = property(None, set_ville) def __str__(self): return self.nom class Item: Le concept item pour la gestion d'inventaire des items de golf. def __init__(self, nom =, prix = 100): self.nom = nom self.prix = prix def set_nom(self, nom): self.nom = nom nom = property(None, set_nom) def set_prix(self, prix): self.prix = prix prix = property(None, set_prix) def __str__(self): return self.nom class Modele: La definition d'un modele avec les magasins. def __init__(self, nom_fichier, magasins =[]): self.nom_fichier = nom_fichier self.magasins = magasins def set_nom_fichier(self, nom_fichier): self.nom_fichier = nom_fichier nom_fichier = property(None, set_nom_fichier) def set_magasins(self, magasins): self.magasins = magasins magasins = property(None, set_magasins) def sauvegarder(self): modele_fichier = open(self.nom_fichier, 'w') for magasin in self.magasins: modele_fichier.write(===MAGASIN=== + \n) modele_fichier.write(nom : + magasin.nom + \n) modele_fichier.write(items : + \n) for item in magasin.items: modele_fichier.write(---ITEM--- + \n) modele_fichier.write(nom : + item.nom + \n) modele_fichier.write(prix : + item.prix + \n) modele_fichier.write(---FIN ITEM--- + \n) modele_fichier.write(===FIN MAGASIN=== + \n) modele_fichier.close() def charger(self): magasins = [] try: modele_fichier = open(self.nom_fichier, 'r') except IOError: print(Le fichier + self.nom_fichier + n'existe pas.) else: fin_fichier = False while not fin_fichier: ligne = modele_fichier.readline() if ligne == : self.set_magasins(magasins) modele_fichier.close() fin_fichier = True break magasin = Magasin() items = [] fin_magasin = False while not fin_magasin: ligne = modele_fichier.readline().strip() if ligne.startswith(===FIN MAGASIN===): magasin.set_items(items) magasins.append(magasin) fin_magasin = True elif ligne.startswith(nom): nom = ligne.split(':')[1] magasin.set_nom(nom.strip()) elif ligne.startswith(---ITEM---): item = Item() fin_item = False while not fin_item: ligne = modele_fichier.readline().strip() if ligne.startswith(nom): nom = ligne.split(':')[1] item.set_nom(nom.strip()) elif ligne.startswith(prix): prix = ligne.split(':')[1] item.set_prix(float()) elif ligne.startswith(---FIN ITEM---): items.append(item) fin_item = True def vide(self): if self.magasins == []: return True else: return False def initialiser(self): magasin01 = Magasin (Swing de golf) magasin02 = Magasin (Golftown) magasin03 = Magasin (PointGolf) item01 = Item (Ensemble de fers Titleist) item01.set_prix(1099.99) item02 = Item (Ensemble de fers Callaway) item02.set_prix(1299.99) item03 = Item (Ensemble de fers Taylormade Burner Graphite) item03.set_prix(2499.99)
Re: [Tutor] Hi everybody stuck on some error need help please thank you!!
On Sat, 24 Apr 2010 01:07:11 pm Marco Rompré wrote: Here's my code: [...] class Modele: La definition d'un modele avec les magasins. def __init__(self, nom_fichier, magasins =[]): self.nom_fichier = nom_fichier self.magasins = magasins [...] if __name__ == '__main__': modele = Modele() nom_fichier = magasinmodele.txt modele.charger(nom_fichier) if modele.vide(): modele.initialiser(nom_fichier) modele.afficher() And here's my error : Traceback (most recent call last): File F:\School\University\Session 4\Programmation SIO\magasingolfmodele.py, line 187, in module modele = Modele() TypeError: __init__() takes at least 2 arguments (1 given) You define Modele to require a nom_fichier argument, but then you try to call it with no nom_fuchier. Also, I see that you do this: def __init__(self, nom_fichier, magasins =[]): You probably shouldn't do this -- it doesn't do what you probably think it does. You probably think that what happens is that if you call Modele(nom_fichier), the magasins attribute will be set to an empty list. But that's not what happens. Default values in Python are defined when the method is created, not when it is run. Watch this example: class Test: ... def __init__(self, x=[]): ... self.x = x ... a = Test() a.x [] b = Test() b.x [] a.x.append(Surprise!) b.x ['Surprise!'] How does this happen? Because every instance shares the same default list. When you append to it, all the other instances see the same change. You don't notice this with default values that are strings or numbers, because you can't modify them, only replace them: x = y = 2 # Make two variables that point to the same value. x is y # Make sure they are identical, not just equal. True x = 3 # Make x point to something else. x is y # And no longer identical. False x = y = [] # Make two variables that point to the same thing. x is y True x.append('something') # Modify that list in place. x is y # Still identical. True y ['something'] If this is the behaviour you want, then you don't need to do anything. Otherwise you need to move the creation of the empty list inside the method: def __init__(self, nom_fichier, magasins=None): if magasins is None: magasins = [] self.nom_fichier = nom_fichier self.magasins = magasins -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi everybody stuck on some error need help please thank you!!
I tried to enter model = Modele (nom_fichier) but it still does not work. And for the list I don't understand very well, Do you know where I can pay someone to help with my programming. Because I feel to annoy tutors with my basic stuff On Fri, Apr 23, 2010 at 11:22 PM, Steven D'Aprano st...@pearwood.infowrote: On Sat, 24 Apr 2010 01:07:11 pm Marco Rompré wrote: Here's my code: [...] class Modele: La definition d'un modele avec les magasins. def __init__(self, nom_fichier, magasins =[]): self.nom_fichier = nom_fichier self.magasins = magasins [...] if __name__ == '__main__': modele = Modele() nom_fichier = magasinmodele.txt modele.charger(nom_fichier) if modele.vide(): modele.initialiser(nom_fichier) modele.afficher() And here's my error : Traceback (most recent call last): File F:\School\University\Session 4\Programmation SIO\magasingolfmodele.py, line 187, in module modele = Modele() TypeError: __init__() takes at least 2 arguments (1 given) You define Modele to require a nom_fichier argument, but then you try to call it with no nom_fuchier. Also, I see that you do this: def __init__(self, nom_fichier, magasins =[]): You probably shouldn't do this -- it doesn't do what you probably think it does. You probably think that what happens is that if you call Modele(nom_fichier), the magasins attribute will be set to an empty list. But that's not what happens. Default values in Python are defined when the method is created, not when it is run. Watch this example: class Test: ... def __init__(self, x=[]): ... self.x = x ... a = Test() a.x [] b = Test() b.x [] a.x.append(Surprise!) b.x ['Surprise!'] How does this happen? Because every instance shares the same default list. When you append to it, all the other instances see the same change. You don't notice this with default values that are strings or numbers, because you can't modify them, only replace them: x = y = 2 # Make two variables that point to the same value. x is y # Make sure they are identical, not just equal. True x = 3 # Make x point to something else. x is y # And no longer identical. False x = y = [] # Make two variables that point to the same thing. x is y True x.append('something') # Modify that list in place. x is y # Still identical. True y ['something'] If this is the behaviour you want, then you don't need to do anything. Otherwise you need to move the creation of the empty list inside the method: def __init__(self, nom_fichier, magasins=None): if magasins is None: magasins = [] self.nom_fichier = nom_fichier self.magasins = magasins -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Marc-O. Rompré ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi everybody stuck on some error need help please thank you!!
On Sat, 24 Apr 2010 01:33:46 pm Marco Rompré wrote: I tried to enter model = Modele (nom_fichier) but it still does not work. What does still does not work mean? Please copy and paste the error you get. And for the list I don't understand very well, Open an interactive session and do some experiments. a = [] # One empty list. b = [] # A different empty list. a.append(1) # Appends to the first list. print a, b [1] [] a = [] # An empty list. b = a # The SAME empty list. a.append(1) print a, b [1] [1] When you have a default value like magasins=[], it is like the second, not the first. -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Hi there!
Hi! Does anyone of you know where to find all the solutions of Gerard Swinnen Python tutorial exercises In the tutorial we just have the solutions to half of the exercises. Thank you -- Marc-O. Rompré ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi there :.)
mark-irel...@msn.com wrote Just introducing myself to say hiHi! Hi welcome, but please don't include lots of attachments. It blows up people's mailboxes and bandwidth allowances. Better to post them on a website and send a link. I'm very new to programming, ... place to start I found out that python and C++ are the usual starting place Actually there are many: VisualBasic, Lisp/Scheme and Java are all common starting points too. And each has its own merits depending on what you want to do. but when I found out that civilisation and eve are programmed using python (my favorite type of games), that helped make the decision. As good a reason as any! :-) My first aim is to get comfortable with python and move on to C++ (apparently python is slow ?!?). It is all relative. If you want to write fast moving graphics etc then yes, you probably need C++. For anything else you might find Python is fast enough. The problem i'm having with this is with the platform. I want the ball to fall if it goes off the edge but be able to jump when on the platform. it either will fall off the edge but won't jump or it will jump but it won't fall. I don't want to change the way the controls are worked (with the true/ false). test.py is the one file that didn't show up (at least for me) Lots of demos but no test.py. It is probably best if you can create the simplest possible example that shows the problem rather than expecting folks to read through half a dozen fairly big files and try to guess what the design looks like etc. (That may have beeen what test.py was!) Try to send some specific code that causes a problem, or at least that you think is causing the problem. Plus any error messages. It would help to tell us which OS and Python version you are using too. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] hi everyone!
i am new one to this programming language. i like to learn python,what i do? what i do to learn python in proper manner. -- Regards, S.Malathi. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] hi everyone!
malathi selvaraj malathira...@gmail.com wrote i am new one to this programming language. Hello and welcome. what i do to learn python in proper manner. First of all make sure you download Python v2.6 rather than v3. v3 is not ideal for learning just yet it is still rather new. Do you know any other programming language? If so go to the official tutorial on the python web site (or download the docs) and work through it. That should be enough to get you started. Ask questions here, show us the code and any errors you get (in full) http://docs.python.org/tutorial/ If this is your first programming language then well done, you made a good choice! :-) Go to here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers pick a tutorial(not the official one!) and work through it. Every time you get stuck - and you will, so don't worry - send a question here explaining what is bugging you and any code plus error messages. (It also helps to mention the Python version, the OS and the tutorial you are using) Either way have fun. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] HI
Sir/Madame, i'm a begginner to Python help me in putting the first step to this world With regards Vishnu S ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] HI
Vishnu S wrote: Sir/Madame, i'm a begginner to Python help me in putting the first step to this world Welcome! A useful first page may be http://wiki.python.org/moin/BeginnersGuide for an overview, and http://wiki.python.org/moin/BeginnersGuide/NonProgrammers where you can find a lot of links to Python tutorials. Read one you like, download Python, and start experimenting and/or solving exercises and/or solving problems you like to solve. When you get stuck, explain us your problem (usually wih a example program), and we will try to answer your question. Albert ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Hi,
Hi, I am trying to write a program in python that solves a system of nonlinear equations using newton's method. I don't know what I am doing wrong. Please help from scipy import* x = array([0.0,0.0,0.0]) n=len(x) tol= 0.1 N=30 k=1 while k = N: def f(x): f= zeros((len(x)),float) f[0][k]= x[0][k]**2 + x[1][k]-37 f[1][k]=x[0][k]- x[1][k]**2- 5 f[2][k]= x[0][k] + x[1][k]+ x[2][k]- 3 return f[k] def J(x): J= zeros((n,n),float) for i in range(n): ei=zeros(n,float) ei[i]=1.0 J[:i]=(f(x[k]+tol*ei)-f(x[k]))/tol return J y[k] = -(J.I)*f[k] x[k+1]=x[k]+y[k] if sqrt(dot(f0,f0)/len(x)) tol: print x else: k=k+1 print 'Too many iterations' -- This message is subject to the CSIR's copyright terms and conditions, e-mail legal notice, and implemented Open Document Format (ODF) standard. The full disclaimer details can be found at http://www.csir.co.za/disclaimer.html. This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. MailScanner thanks Transtec Computers for their support. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi,
Kgotlelelo Legodi wrote: Hi, I am trying to write a program in python that solves a system of nonlinear equations using newton's method. I don't know what I am doing wrong. Please help Mostly what you are doing wrong is failing to tell us why you think there is a problem! What results are you expecting and what are you getting? from scipy import* x = array([0.0,0.0,0.0]) n=len(x) tol= 0.1 N=30 k=1 while k = N: def f(x): f= zeros((len(x)),float) f[0][k]= x[0][k]**2 + x[1][k]-37 f[1][k]=x[0][k]- x[1][k]**2- 5 f[2][k]= x[0][k] + x[1][k]+ x[2][k]- 3 return f[k] def J(x): J= zeros((n,n),float) for i in range(n): ei=zeros(n,float) ei[i]=1.0 J[:i]=(f(x[k]+tol*ei)-f(x[k]))/tol return J y[k] = -(J.I)*f[k] x[k+1]=x[k]+y[k] if sqrt(dot(f0,f0)/len(x)) tol: print x else: k=k+1 print 'Too many iterations' -- Bob Gailer Chapel Hill NC 919-636-4239 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Hi
Hi, I'm new and just starting to learn Python. Just testing if this works or not and if anybody reads it lol. Eddie ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi
On Mon, Jun 8, 2009 at 7:30 AM, Eddieeddie9...@gmail.com wrote: Hi, I'm new and just starting to learn Python. Just testing if this works or not and if anybody reads it lol. Yes, it works. Welcome! Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi
Eddie wrote: Hi, I'm new and just starting to learn Python. Just testing if this works or not and if anybody reads it lol. Eddie ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor Welcome to the list and enjoy your stay. :) -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi
Eddie eddie9...@gmail.com wrote Hi, I'm new and just starting to learn Python. Just testing if this works or not and if anybody reads it lol. Welcome! If you take a look at the archive on the web site you'll see that quite a lot of folks read it - and many reply too! You might even find answers to a lot of your own questions :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi everyone
Doug Reid wrote: Now here is the code I'm having trouble following: while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):] position = random.randrange(len(word)). This will create a starting point for the program to pick a letter out of a word at random using the length of the word as a range I think. Like if the word is 'python' and since it has 6 letters, random.randrange(len(word)) will pick a random starting point such as the letter 'y' for example. It's gonna be inside a while loop, so the next time it runs, 'python' will be 'pthon' and the random range will be 5 letters and on down till there is no more letters, is this right? `position` is an integer. It is the index of the letter we want to put into `jumble`. The first line generates a random index, the second line copies the letter and append it to `jumble`, and the third line removes that letter from `word`. Ok, so everyone of the letters that was 'extracted' from the word 'python' will be put into the variable 'jumble' that was defined as empty. This is the part that troubles me: word = word[:position] + word[(position + 1):] How do we remove a single letter? In python, string is immutable; we must create a new string that has the required property (i.e. letter in `position` removed). Rather than removing, we copied the part of string before `position` (word[:position]) and after `position` (word[position+1:]) and concatenating them together to become our new `word`. How does the slicing works? The standard model for slicing and indexing in python is like this: -6 -5 -4 -3 -2 -1 +---+---+---+---+---+---+ | p | y | t | h | o | n | +---+---+---+---+---+---+ 0 1 2 3 4 5 6 Let's say `position` is 3 (i.e. the letter h). word[:3] is: -6 -5 -4 -3 -2 -1 +---+---+---+---+---+---+ | p | y | t | h | o | n | +---+---+---+---+---+---+ 0 1 2 3 4 5 6 |___| word[0:3] which is pyt while word[3+1:] - word[4:] is: -6 -5 -4 -3 -2 -1 +---+---+---+---+---+---+ | p | y | t | h | o | n | +---+---+---+---+---+---+ 0 1 2 3 4 5 6 |___| word[4:6] which is on concatenating pyt + on, we get pyton (i.e. h removed) An extended version of the line that may be more easily digestible: letters_before_position = word[:position] letters_after_position = word[position+1:] word = letters_before_position + letters_after_position ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi everyone
Le Wed, 20 May 2009 18:25:07 -0700 (PDT), Doug Reid rnrcr...@yahoo.com s'exprima ainsi: The next line in the loop, word = word[:position] + word[(position + 1):] creates a new version of word minus the one letter at position position. Using slicing, the computer creates two new strings from word. The first slice, word[:position], is every letter up to, but not including, word[position]. The next slice, word[(position + 1):], is every letter after word[position]. These two string are joined together and assigned to word, which is now equal to its old self, minus the one letter word[position]. Can someone explain this in simpler terms? I'm sorry this is so lengthy for my first post:) It's confusing because abstract and without any example. In the case you wrote where the word is python, the letter 'y', and so the position is 1, you get: wordpython word[:position] p word[position+1:] thon glued together pthon Also, a confusing part of the program id the loop header: while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):] In python, a container such as a string is considered 'False' when it's empty. Right? So that the loop header above is equivalent to: while len(word) 0: and the loop will stop when every letter has been extracted from the word. Denis -- la vita e estrany ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi everyone
On Thu, May 21, 2009 at 2:42 AM, spir denis.s...@free.fr wrote: snip while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):] Something that many of us use for debugging, and is also useful for comprehension is a simple print statement. If you were to convert the loop to this: while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):] print jumble print word # Optional - for further understanding print word[:position] print word[(position+1):] you would basically see what Denis wrote - only every step through the loop. HTH, Wayne p.s. - When you start graphical programming, I'd look at pyglet or pygame. Although to really understand event driven programming, it really helped me to start writing programs with Tkinter. YMMV ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi everyone....thanks for the help
Thank you all for the help. I believe I understand now, and think this will be a great group to learn from. Doug ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Hi everyone
Hi, I'm teaching myself Python mainly for to use as a hobby. I'd like to do graphical programs eventually and maybe some simple graphic games. I feel I'm doing well with the tutorial I'm using but it would be nice to have some real people to ask questions and opinions, so on that note, I'm having a little trouble understanding the following code. I grasp the basics of what it does but am wondering if someone could explain it in simpler terms.. In the tutorial, I'm using Tuples and there is a Word Jumble game given to show how this can be used. A tuple of words is created: WORDS = (python, jumble, easy, difficult, answer, xylophone) correct=word Then a variable that will hold the jumbled word is defined: jumble=' ' Ok, then a variable: word=random.choice(WORDS) is created to pick a random element from WORDS. I get this part. Now here is the code I'm having trouble following: while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):] position = random.randrange(len(word)). This will create a starting point for the program to pick a letter out of a word at random using the length of the word as a range I think. Like if the word is 'python' and since it has 6 letters, random.randrange(len(word)) will pick a random starting point such as the letter 'y' for example. It's gonna be inside a while loop, so the next time it runs, 'python' will be 'pthon' and the random range will be 5 letters and on down till there is no more letters, is this right? Ok, so everyone of the letters that was 'extracted' from the word 'python' will be put into the variable 'jumble' that was defined as empty. This is the part that troubles me: word = word[:position] + word[(position + 1):] I know basically it is creating a new string through the while loop for extracint letters. But I don't feel I understand it fully, The expression is confusing to me. Here is an excerpt from the tutorial that explains it and confuses me more: The next line in the loop, word = word[:position] + word[(position + 1):] creates a new version of word minus the one letter at position position. Using slicing, the computer creates two new strings from word. The first slice, word[:position], is every letter up to, but not including, word[position]. The next slice, word[(position + 1):], is every letter after word[position]. These two string are joined together and assigned to word, which is now equal to its old self, minus the one letter word[position]. Can someone explain this in simpler terms? I'm sorry this is so lengthy for my first post:) Any help will be appreciated Thanks, Doug ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] HI, #Include like in python
wesley chun wrote: import listen You can use the __import__ function if you want, but generally you want the import statement as above. The equivalent to 'import listen' is: listen = __import__('listen') See the tutorial here: http://docs.python.org/tutorial/modules.html you also have to make sure that your .py file is in one of the folders/directories listed in sys.path (to see it, import sys then do print sys.path). if the file is not in one of those folders, you will also get an import error. you can either add the correct directory to your PYTHONPATH environment variable, or manually add it at run-time using sys.path.append/insert. A simpler form is to put listen.py and usbconnection.py in the same directory. In the latter you can do something like import listen listener = listen.ListenClass(param1, param2) listener.begin() # Call the 'begin' method of the ListenClass object. You can use the ListenClass like normal, just state that Python should look for it in the listen file. Albert ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] HI, #Include like in python
Hi \o I'm asking if there is any #include( C) like or any include('File.php') (php) like in python. I have 2 files: usbconnection.py and listen.py, And i want to use some classes avaiable in listen.py on my main file usbconnection.py. I've tryed to do __import__(listen.py) but obviously it gave me an error... ImportError: No module named /home/andrefsp/projects/sigre/listen.py So, if anybody knows how to do an include in python please reply me =) Bye the way, i've sent an email in last week asking how to read data from USB port. So, i've finally did it, yesterday i was able to read data from my USB port, if anybody is interested in some information about it just need to ask, i don't mind to help =) it is impossible to make eggs without omelettes ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] hi...
I have a problem with python, I'm begginner in python. How clear the screen of GUI python interactive and which is the difference between interactive mode and not interactive mode because when I run a program in interactive mode, the program run very good, but if run in not interactive mode not show me error, but the return of function returns no value, this is the source code: def suma(no1,no2):total=no1+no2return total print 'hola'opcion=input()if opcion==1:print 'suma'a=input() b=input()suma(a,b) the result of this code is: hola1suma57 totalTraceback (most recent call last): File pyshell#0, line 1, in moduletotalNameError: name 'total' is not defined why this happens??? what I did wrong??? and why run very good in interactive mode??? thanks for help me and sorry for my bad english, I from Mexico and I english student. Thank you. _ Juega y gana, tenemos 3 Xbox a la semana. http://club.prodigymsn.com/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] hi...
On Sun, Aug 24, 2008 at 2:31 AM, Alberto Perez [EMAIL PROTECTED] wrote: I have a problem with python, I'm begginner in python. How clear the screen of GUI python interactive I'm not sure what you mean by GUI interactive? However, at the Python interactive prompt, I can clear the screen using a simple, old-fashioned way: for i in range(1,50): print(\n) That prints 50 newlines, thus effectively clearing the screen. Happy Programming! -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] hi...
Alberto Perez [EMAIL PROTECTED] wrote . How clear the screen of GUI python interactive bhaaaluu answered that and which is the difference between interactive mode and not interactive mode WW answered that because when I run a program in interactive mode, the program run very good, but if run in not interactive mode not show me error, How are you running your program in non interactive mode Are you using IDLE or Pythonwin? Or are you running it from a command window? If you are running it from IDLE are you creating a new file and typing in the code then saving it and running it from the menu (or F5 key)? That's what it looks like... but the return of function returns no value It returns a value but you don't print it. One big difference between and non interactive mode is that the prompt prints the values of expressions, including function calls. Non interacticve mode does not print these, you have to use print. (This is why in my tutorial I always use print even in the prompt; because it avoids this confusion.) Thus print suma(a,b) would show the result. Or as WW said you could store the result in a variable called total def suma(no1,no2): total=no1+no2 return total print 'hola' opcion=input()# could replace with: opcion = input(hola\n) if opcion==1: print 'suma' a=input() # its good to give a prompt string of some kind b=input() print suma(a,b) total ... name 'total' is not defined why this happens??? As the error says total is not defined in your shells namespace. It only exists within your program. As WW said, it only exists inside suma() in your code. Thasts why you need to create a global level variable or just print the result of suma() directly. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] hi...
- Message from [EMAIL PROTECTED] - Date: Sun, 24 Aug 2008 01:31:28 -0500 From: Alberto Perez [EMAIL PROTECTED] Reply-To: Alberto Perez [EMAIL PROTECTED] Subject: [Tutor] hi... To: tutor@python.org run a program in interactive mode, the program run very good, but if run in not interactive mode not show me error, but the return of function returns no value, this is the source code: def suma(no1,no2): total=no1+no2 return total print 'hola' opcion=input() if opcion==1: print 'suma' a=input() b=input() suma(a,b) the result of this code is: hola 1 suma 5 7 total Traceback (most recent call last): File pyshell#0, line 1, in moduletotalNameError: name 'total' is not defined why this happens??? what I did wrong??? and why run very good in Hi, Welcome to python and the tutor list. An earlier response pointed out that you need to bind the returned value to total as in total = suma(a, b) but I thought a bit of explanation might help. In your function, you define total. That makes `total' a name in the scope of the function. That means that `total' can be seen by code in your function, but not code outside of your function. This might seem confusing now, but in the long run, it makes life easier. How? Well, you can define all sorts of names in the body of your functions without having them clutter up the name-space of your overall code. That makes things cleaner. It also makes them less error prone. If total defined in your function was visible everywhere by default, then you would have to make sure that your function didn't define any names that higher level code did. (You'd have to make sure that total defined in a function didn't overwrite total defined outside of the function.) You can make names defined in functions be globally available, but until you've got some experience, don't do that. (Arguably, once you have experience, don't do that then either ;-) Hope that helps some, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Hi
Hi, I want Tutors mailing List ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi
Firoze Khan wrote: Hi, I want Tutors mailing List You seem to have found it. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi
Firoze Khan wrote: Hi, I want Tutors mailing List If you want to subscribe visit: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi,every one
On 6/23/07, Yang Yang [EMAIL PROTECTED] wrote: 1.what is the best book for python study. Try Byte of Python http://byteofpython.info/ 2.what's is the better IDE for python Start off with IDLE, which comes with the Python installer. Go through this IDLE tutorial, http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/ (If you're not satisfied, there are numerous Python IDEs available) -- http://srid.nearfar.org/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Hi,every one
i am a newman for python world i have some word want to ask 1.what is the best book for python study. 2.what's is the better IDE for python Thanks for all___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi,every one
Yang Yang escreveu: i am a newman for python world i have some word want to ask 1.what is the best book for python study. I like Dive into Python. ( http://www.diveintopython.org/ ) 2.what's is the better IDE for python That depends on what OS you are. Thanks for all ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- _ ASCII ribbon campaign ( ) - against HTML email X vCards / \ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hi
On 3/16/07, Ben [EMAIL PROTECTED] wrote: Is anyone can point me where I can find a good tutorial about pywin for someone like me? Pywin itself is not a package for making GUIs, it's merely a IDE for Windows and got the win32all-package included. For GUIs, you want to look at wxPython, pygtk or similiar packages. Those will let you do what you are looking for. -- - Rikard. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] hi, learning python
print Guesses you've taken: ,i, \nGuess letter: letter_guess = raw_input()' this is a line of my program, and raw_input only takes one argument. I want it to display like this Guesses you've taken: 0 Guess letter: (letter would go here) instead of Guesses you've taken: 0 Guess letter: (leter you've taken) is there a way to continue the input line, like in java you would just do System.out.print? thanks _ Experience the magic of the holidays. Talk to Santa on Messenger. http://clk.atdmt.com/MSN/go/msnnkwme008001msn/direct/01/?href=http://imagine-windowslive.com/minisites/santabot/default.aspx?locale=en-us ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] hi, learning python
Raven Of Night Raven Of Night wrote: print Guesses you've taken: ,i, \nGuess letter: letter_guess = raw_input()' this is a line of my program, and raw_input only takes one argument. I want it to display like this Guesses you've taken: 0 Guess letter: (letter would go here) instead of Guesses you've taken: 0 Guess letter: (leter you've taken) is there a way to continue the input line, like in java you would just do System.out.print? print Guesses you've taken: ,i letter_guess = raw_input(Guess letter: ) -- Bob Gailer 510-978-4454 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] hi, learning python
Raven Of Night Raven Of Night [EMAIL PROTECTED] wrote print Guesses you've taken: ,i, \nGuess letter: letter_guess = raw_input()' this is a line of my program, and raw_input only takes one argument. Yes, and that argument is the prompt to display to the user, which is what you want... letter_guess = raw_input('Guess letter. ') is there a way to continue the input line, like in java you would just do System.out.print? As to simulating Java's print style, yes, there are a couple of ways. 1) put a comma at the end of the string to be printed: print 'hello , print 'world' prints hello world 2) use sys.stdout.write() sys.stdout.write('hello ') sys.stdout.write('world') 3) use string formatting to create the string before printing outstring = %s %s % % (var1,var2,var3) It all depends what you are trying to do which one suits best... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Hi, need help on terminal input
Hi, Does anybody know how to create a pygtk widget which can accept and diplay input from a serial port? Thanks and Rgds, Shashikanth Ramakrishnan Embedded Product Division Cell: +6-0122977087 e-mail :[EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor