Re: [Tutor] Input to python executable code and design question
> >To help you out. You need some sort of error checking to be sure that > >within your given range you won't get something like a math domain > >error. > > > > > Yes, I thought that: > try: > #function > exception: > pass Hi Ismael, Python's keyword for exception handling is 'except', so this can be something like: ### try: some_function() except: pass ### ... Except that the 'except' block should seldom be so vacant like that. *grin* There are two things we should try to do when exception handling: handle only what we need, and report exception information when we do. We really want to get the system to handle only domain errors, and otherwise let the exception raise errors. But because the block above catches every Python error, even silly things like misspellings, it will sweep programmer errors under the carpet. For example, the code snippet: ### >>> def sqrt(x): ... return y**0.5 ## bug: typo, meant to type 'x' ... >>> try: ... sqrt("hello") ... except: ... pass ... ### tries to make it look like we're catching domain errors, but the overzealous exception catching disguises a really silly bug. We can make the exception more stringent, so that we only catch domain errors. According to: http://www.python.org/doc/lib/module-exceptions.html there's are a few standard exceptions that deal with domains, like ArithmeticError, ValueError, or TypeError. Let's adjust the code block above so we capture only those three: ### >>> try: ... sqrt("hello") ... except (ArithmeticError, ValueError, TypeError): ... pass ... Traceback (most recent call last): File "", line 2, in ? File "", line 2, in sqrt NameError: global name 'y' is not defined ### Also, it might be a good idea to print out that a certain exception happened, just so that you can tell the user exactly what's causing the domain error. The 'traceback' module can help with this: http://www.python.org/doc/lib/module-traceback.html For example: ### try: 1 / 0 except: print "There's an error!" ### tells us that some wacky thing happened, but: ### import traceback try: 1 / 0 except: print "Error:", traceback.format_exc() ### tells us that the error was caused by a ZeroDivisionError. Best of wishes to you! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Input to python executable code and design question
Ismael Garrido wrote: > [EMAIL PROTECTED] wrote: > >> Quoting Ismael Garrido <[EMAIL PROTECTED]>: >> >> >> >>> I am trying to make a program that will plot functions. For that, I >>> need >>> to be able to get an input (the function to be plotted) and execute it. >>> > > > > > >So you want the user to be able to type something like "f(x) = > sin(2*x)" and > >then your program will plot it --- is that correct? > > Yes, that's what I want. I can understand you fear. Check out this post that Danny made in October I found it very helpful. http://mail.python.org/pipermail/tutor/2004-October/032364.html This one by kent at the same time was good too. http://mail.python.org/pipermail/tutor/2004-October/032340.html I felt this was a very good and helpful. __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Input to python executable code and design question
I have grown to like VPython as the curve attribute really seems to do the trick. If you get it working on a Tkinter canvas, I would like to see the code as I haven't quite found a way to plot points on to one of those. A simple graph function in VPython... (it isn't the whole thing, believe me...) It already is more powerful than most graphing calculators--see except comment. def graphit(function): m = curve(color=color.blue) x = -15 while -15<=x<=15: try: m.append(pos=(x,eval(function),0)) except: m = curve(color=color.red) # This is to catch domain errors and keep the curve from connecting points across asymptotes x = x+0.05 # Yes it might be too high a precision, but I usually use 0.005 I would like to see the executable. I don't know anything about Qbasic 4.5, so I don't know if I could view the source, etc... Tell me if you want cut and paste or attachment to see the program. By the way, I don't want to give the impression that I'm anything much better than a newbie myself. I just have a big mouth It might help setting it up. It supports x functions and polar graphs as well. Perhaps for the future I will try 3d graphs, since VPython supports 3d. Hah! There's something I don't remember Tkinter Canvas being able to do. Jacob > Jacob S. wrote: > > >eval() is good and it can be done using it. > >I wrote a -- IMHO -- really great functiongraphing program using vpython. > >If you would like to see it, just reply and say so. > > > > > Out of curiosity, I would like to see your program. There's always > something to learn (and even more so for me, being a newbie) > > >Please tell me what you are using to plot the points. (big grin) Vpython, > >wxpython, what? > >I'm curious--it's just someone else is working on a project that I'm working > >on... > > > > > At the moment, nothing :-s > I'm learning Phyton, and I thought that this would be an interesting > challenge. For what I've seen, Tkinter's Canvas 'could possibly' do the > job. I still have to try it out. In case that didn't work, I was > thinking in looking through wxpython. > > > >To help you out. > >You need some sort of error checking to be sure that within your given range > >you > >won't get something like a math domain error. > > > > > Yes, I thought that: > try: > #function > exception: > pass > > > >If you want more suggestions, ask > >Please, tell me how you're doing. It sounds interesting. > > > > > At the moment, I have almost nothing. After John Fouhy's replies I have > rewritten the few lines I had at least three times :o) > It will be simple, I intend to support viewing specific parts of the > function (instead of a fixed view), multiple graphs, perhaps an option > to save/load functions. I first made a program like this in Qbasic 4.5, > and thought doing it again in Python with an interface and more advanced > options may be very entretaining. :-) I can send you the source/exe if > you want (sadly you can't choose what you want to see in the exe > version, the function must be hard-coded). > > Thanks > Ismael > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Input to python executable code and design question
Jacob S. wrote: eval() is good and it can be done using it. I wrote a -- IMHO -- really great functiongraphing program using vpython. If you would like to see it, just reply and say so. Out of curiosity, I would like to see your program. There's always something to learn (and even more so for me, being a newbie) Please tell me what you are using to plot the points. (big grin) Vpython, wxpython, what? I'm curious--it's just someone else is working on a project that I'm working on... At the moment, nothing :-s I'm learning Phyton, and I thought that this would be an interesting challenge. For what I've seen, Tkinter's Canvas 'could possibly' do the job. I still have to try it out. In case that didn't work, I was thinking in looking through wxpython. To help you out. You need some sort of error checking to be sure that within your given range you won't get something like a math domain error. Yes, I thought that: try: #function exception: pass If you want more suggestions, ask Please, tell me how you're doing. It sounds interesting. At the moment, I have almost nothing. After John Fouhy's replies I have rewritten the few lines I had at least three times :o) It will be simple, I intend to support viewing specific parts of the function (instead of a fixed view), multiple graphs, perhaps an option to save/load functions. I first made a program like this in Qbasic 4.5, and thought doing it again in Python with an interface and more advanced options may be very entretaining. :-) I can send you the source/exe if you want (sadly you can't choose what you want to see in the exe version, the function must be hard-coded). Thanks Ismael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Input to python executable code and design question
I wondered when someone would ask something like this. eval() is good and it can be done using it. I wrote a -- IMHO -- really great functiongraphing program using vpython. If you would like to see it, just reply and say so. Pros and cons of calculating all first: pro - easier to read code con - user may feel insecure while the points are being calculated -- for example, say you type in a big, complicated function, and while the computer sits there and calculates the points, the user might feel that something is wrong. On the other hand, if you calculate each point on its own, points are immediately put on the screen so your user knows that the thing is working (if you get my drift) Please tell me what you are using to plot the points. (big grin) Vpython, wxpython, what? I'm curious--it's just someone else is working on a project that I'm working on... To help you out. You need some sort of error checking to be sure that within your given range you won't get something like a math domain error. Ex. y = 'sqrt(x)' x = -15 while -15<=x<=15: print eval(y) Gives you something like Traceback blah, blah ... Math domain error If you want more suggestions, ask Please, tell me how you're doing. It sounds interesting. HTH, Jacob Schmidt > Hello > > I am trying to make a program that will plot functions. For that, I need > to be able to get an input (the function to be plotted) and execute it. > So, my question is, how do I use the input? I have found no way to > convert the string to some kind of executable code. > > I did research the problem. And found two things, first, an > unsatisfactory solution from: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52217 > The code there, by means I cannot understand at all, executes a string > as code. To be usable I have to make my code a huge string. It is not > very elegant. > > The second possible solution I found was using eval, compile and/or > exec. But I do not understand what do they do, or how to use them, for > the matter. > > Related to the program I intend to do, which design would you say is > more intelligent: one that first calculates the whole function, stores > it, and then plots it; or one that calculates-plots-calc.-plot, and so on? > > Thanks for any information, and for your time. > Ismael > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Input to python executable code and design question
[EMAIL PROTECTED] wrote: Quoting Ismael Garrido <[EMAIL PROTECTED]>: (Newbie looking scared) That's kind of hard for me... Parsing it myself is too complex for me. Also, I hoped Python's math would do the job for me, so I wouldn't have to make what's already done in Python. Writing (and understanding) grammar is probably easier than you think --- once you get over the syntax. And they are fantastically useful things for doing any sort of parsing. But no matter.. If you are interested in learning about parsing, I suggest looking at pyparsing - it is IMO the easiest of the Python parsing frameworks. It has an example that implements a four-function calculator so that would get you off in the right direction. http://pyparsing.sourceforge.net/ Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Input to python executable code and design question
You can you the exec statement to execute Python code from a string. The string could be from user input. So for example a user could input 'x*x' and you could do >>> inp = 'x*x' >>> func='def f(x): return ' + inp >>> func 'def f(x): return x*x' >>> exec func >>> f(3) 9 Now you have f(x) defined as a regular function and you can plot it the same as a function you wrote in your code. The user will have to use whatever variable name you expect. And this is a huge security hole, you shouldn't do it if you don't trust the users. Kent Ismael Garrido wrote: Hello I am trying to make a program that will plot functions. For that, I need to be able to get an input (the function to be plotted) and execute it. So, my question is, how do I use the input? I have found no way to convert the string to some kind of executable code. I did research the problem. And found two things, first, an unsatisfactory solution from: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52217 The code there, by means I cannot understand at all, executes a string as code. To be usable I have to make my code a huge string. It is not very elegant. The second possible solution I found was using eval, compile and/or exec. But I do not understand what do they do, or how to use them, for the matter. Related to the program I intend to do, which design would you say is more intelligent: one that first calculates the whole function, stores it, and then plots it; or one that calculates-plots-calc.-plot, and so on? Thanks for any information, and for your time. Ismael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Input to python executable code and design question
Quoting Ismael Garrido <[EMAIL PROTECTED]>: > (Newbie looking scared) That's kind of hard for me... Parsing it myself > is too complex for me. Also, I hoped Python's math would do the job for > me, so I wouldn't have to make what's already done in Python. Writing (and understanding) grammar is probably easier than you think --- once you get over the syntax. And they are fantastically useful things for doing any sort of parsing. But no matter.. > For what I understood of Mr. Clarke's mail, eval() would do the job (in > spite of the security problem, I'm not concerned about that). Is that > correct? I guess I'll go read about that a bit more. Yeah, probably. For example: >>> from math import * >>> x = 3 >>> y = 2 >>> eval("2*x + 3*sin(x + y)") 3.1232271760105847 Note that if I had done "import math" instead of "from math import *", it would not have worked, because "sin" would not have been defined. So you could do something like: def evalAt(function, x): """ Evaluate a function (as a string) at a given point. """ return eval(function) # This is equivalent to: evalAt = lambda function, x: eval(function) myFun = "2*x + 3*sin(x + y)" evalFunction = lambda x: evalAt(myFun, x) xPoints = [x / 1.0 for x in xrange(1)] yPoints = map(evalFunction, xPoints) One problem with this approach is that you are required to use 'x' as the variable when you are typing in your function. Oh, to answer your other question: It is almost certainly better to calculate the points first, and then plot them. -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Input to python executable code and design question
[EMAIL PROTECTED] wrote: Quoting Ismael Garrido <[EMAIL PROTECTED]>: I am trying to make a program that will plot functions. For that, I need to be able to get an input (the function to be plotted) and execute it. > > >So you want the user to be able to type something like "f(x) = sin(2*x)" and >then your program will plot it --- is that correct? Yes, that's what I want. >Maybe you could parse it yourself? I have found SimpleParse quite easy to use >--- http://simpleparse.sourceforge.net/ . You will need to write your own >grammar to describe functions (Newbie looking scared) That's kind of hard for me... Parsing it myself is too complex for me. Also, I hoped Python's math would do the job for me, so I wouldn't have to make what's already done in Python. For what I understood of Mr. Clarke's mail, eval() would do the job (in spite of the security problem, I'm not concerned about that). Is that correct? I guess I'll go read about that a bit more. Thanks for your replies. Ismael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Input to python executable code and design question
Eep. On Mon, 10 Jan 2005 13:04:33 +1300, Liam Clarke <[EMAIL PROTECTED]> wrote: > I think you're looking for eval() - but that's a big security hole, > and wouldn't handle f(x) notation overly well, unless you parse like > John said. > > > On Mon, 10 Jan 2005 12:52:24 +1300 (NZDT), [EMAIL PROTECTED] > <[EMAIL PROTECTED]> wrote: > > Quoting Ismael Garrido <[EMAIL PROTECTED]>: > > > > > I am trying to make a program that will plot functions. For that, I need > > > to be able to get an input (the function to be plotted) and execute it. > > > So, my question is, how do I use the input? I have found no way to > > > convert the string to some kind of executable code. > > > > So you want the user to be able to type something like "f(x) = sin(2*x)" and > > then your program will plot it --- is that correct? > > > > Maybe you could parse it yourself? I have found SimpleParse quite easy to > > use > > --- http://simpleparse.sourceforge.net/ . You will need to write your own > > grammar to describe functions --- something like this, I guess: > > > > eqn := fname, '(', varlist, ')=', expr > > varlist := var, (',', var)* > > > > expr := atom, (binop, atom)? > > atom := var / (fun, '(', expr, ')') / num > > fun := 'sin' / 'cos' / 'tan' / ... > > > > var := char > > fname := char+ > > num := digit+ > > binop := '+' / '*' / '/' / '-' > > > > char := [a-zA-Z] > > digit := [0-9] > > > > although you will need to work on that to get the precedence right and avoid > > undesired recursion and the like. SimpleParse will give you a tree (made of > > nested tuples) representing your function. You can then have a go at > > converting > > the tree to a function. > > > > I guess the standard way to do this would be something like: > > > > def convert(node): > > functionName = node[0] > > children = node[1] > > if functionName == '*': > > return convert(children[0]) * convert(children[1]) > > elif functionName == '+': > > ... > > > > But you may be able to come up with something more clever. > > > > Hope this helps. > > > > -- > > John. > > ___ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > 'There is only one basic human right, and that is to do as you damn well > please. > And with it comes the only basic human duty, to take the consequences. > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Input to python executable code and design question
Quoting Ismael Garrido <[EMAIL PROTECTED]>: > I am trying to make a program that will plot functions. For that, I need > to be able to get an input (the function to be plotted) and execute it. > So, my question is, how do I use the input? I have found no way to > convert the string to some kind of executable code. So you want the user to be able to type something like "f(x) = sin(2*x)" and then your program will plot it --- is that correct? Maybe you could parse it yourself? I have found SimpleParse quite easy to use --- http://simpleparse.sourceforge.net/ . You will need to write your own grammar to describe functions --- something like this, I guess: eqn := fname, '(', varlist, ')=', expr varlist := var, (',', var)* expr := atom, (binop, atom)? atom := var / (fun, '(', expr, ')') / num fun := 'sin' / 'cos' / 'tan' / ... var := char fname := char+ num := digit+ binop := '+' / '*' / '/' / '-' char := [a-zA-Z] digit := [0-9] although you will need to work on that to get the precedence right and avoid undesired recursion and the like. SimpleParse will give you a tree (made of nested tuples) representing your function. You can then have a go at converting the tree to a function. I guess the standard way to do this would be something like: def convert(node): functionName = node[0] children = node[1] if functionName == '*': return convert(children[0]) * convert(children[1]) elif functionName == '+': ... But you may be able to come up with something more clever. Hope this helps. -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Input to python executable code and design question
Hello I am trying to make a program that will plot functions. For that, I need to be able to get an input (the function to be plotted) and execute it. So, my question is, how do I use the input? I have found no way to convert the string to some kind of executable code. I did research the problem. And found two things, first, an unsatisfactory solution from: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52217 The code there, by means I cannot understand at all, executes a string as code. To be usable I have to make my code a huge string. It is not very elegant. The second possible solution I found was using eval, compile and/or exec. But I do not understand what do they do, or how to use them, for the matter. Related to the program I intend to do, which design would you say is more intelligent: one that first calculates the whole function, stores it, and then plots it; or one that calculates-plots-calc.-plot, and so on? Thanks for any information, and for your time. Ismael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor