[Tutor] While truth
I was reading a tutorial that had these examples in it: >>> while False: print("False is the new True.") >>> while 6: print("Which numbers are True?") while -1: print("Which numbers are True?") while 0: print("Which numbers are True?") Unfortunately the author never explained these statements. I was wondering if the gist of a while statement could be explained in the context of these examples. e.g. while False: means while True is False, which is never True because True is of course True not False. but while 6: means. err while 6 is True? and this is True because... err. Anyway I am a bit lost with this. Can anyone shed any light please? Thanks. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] While truth
Or should I have said While False is True, which is never True, because False is False not True > From: dux...@hotmail.com > To: tutor@python.org > Date: Tue, 20 May 2014 08:25:48 + > Subject: [Tutor] While truth > > I was reading a tutorial that had these examples in it: > > while False: > > print("False is the new True.") > > while 6: > > print("Which numbers are True?") > > > while -1: > > print("Which numbers are True?") > > > while 0: > > print("Which numbers are True?") > > > > Unfortunately the author never explained these statements. > > > I was wondering if the gist of a while statement could be explained in the > context of these examples. > > > e.g. while False: > > > means while True is False, which is never True because True is of course True > not False. > > > but while 6: > > > means. err while 6 is True? and this is True because... err. > > > Anyway I am a bit lost with this. > > > Can anyone shed any light please? > > > Thanks. > ___ > 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] While truth
Hi, 6, -1 or 0 are not bools (True or False): >>> 6 is True False >>> 0 is False False If you had to design a language and want to think about using numbers in a logical context you could do at least two things: 1) convert the number to bool, ie define a set of rules to assign to each number a logical value, or 2) don't convert and raise an error. In python, like in many other languages, option 1) has been chosen. The rules are roughly: when using a number in a logical context 0 is casted to False, and the other numbers are considered True. The "while" statement expects an expression that returns a logical value. Put both things together and I think you get your answer, if I well understood. Best 2014-05-20 10:25 GMT+02:00 Ian D : > I was reading a tutorial that had these examples in it: > > while False: > > print("False is the new True.") > > while 6: > > print("Which numbers are True?") > > > while -1: > > print("Which numbers are True?") > > > while 0: > > print("Which numbers are True?") > > > > Unfortunately the author never explained these statements. > > > I was wondering if the gist of a while statement could be explained in the > context of these examples. > > > e.g. while False: > > > means while True is False, which is never True because True is of course True > not False. > > > but while 6: > > > means. err while 6 is True? and this is True because... err. > > > Anyway I am a bit lost with this. > > > Can anyone shed any light please? > > > Thanks. > ___ > 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] While truth
On 20May2014 08:25, Ian D wrote: I was reading a tutorial that had these examples in it: while False: print("False is the new True.") while 6: print("Which numbers are True?") while -1: print("Which numbers are True?") while 0: print("Which numbers are True?") Unfortunately the author never explained these statements. That is a pity. Sounds badly written. I would imagine the intent is that you could try these and see what happens. I think that exercise would be more effective with if-statements instead of while-statements. Basicly, the point is likely to show that you do not need to use a "bool" as the while condition; any value considered "truthy" by Python will do if it matches what you are working with. Broadly, None and 0 and False and "empty" collections (empty lists, empty sets, zero length strings, etc) are "false", and most other things are "true". Cheers, Cameron Simpson Rugby is a beastly game played by gentlemen; soccer is a gentleman's game played by beasts; football is a beastly game played by beasts. - Henry Blaha ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Return Variable from Function.
Hello, (im using python 2.7) I've been having some problems to return the variable from a function so i decided to try to do it with with global variables, but the script is not working good. I've been reading tutorials but i just don't get how to do it and i would like to ask for some help >.< ( at the end, it's the part of the script that is not working, you can copy it to easily understand the problem) what i would like create a function that creates a window for taking a choice and returns a variable in order to proceed using the choice of that variable. ( i've removed the variable from the script posted below because i tried to do it with the global variables ) The problem that i have using the global variables is that the: if Prompt_Desition==1: if os.path.exists(Script_Location+"/program-data"): os.system("rm -r "+Script_Location+"/program-data") print "Program-data deleted" else: print "No program-data" if os.path.exists(Script_Location+"/computer-data"): os.system("rm -r "+Script_Location+"/computer-data") print "Computer-Data Deleted" else: print "No computer-data" Prompt_Desition=0 is executed when the main_window_gui() window is closed. i don't understand why. It should be executed when the def cancel_label_desition() is executed. because thePompt_desition variable changes to 1. Also i would like to ask if is there any way to put a definition with arguments on the command of a button? when i do this i get errors >.< i define message, proceed_label, cancel_label then: b100 = Button(window1, text="Delete",command=prompt_desition(message, proceed_label, cancel_label)) b100.pack() ___ Thanks so much for helping me! I appreciate it a lot !! ___ import Tkinter, tkFileDialog, os, csv, shutil, time, getpass, pwd from os import stat from Tkinter import * ## Global Variables Script_Location=os.path.dirname(os.path.realpath(__file__)) Script_Title="Fresh Install v1.1" Prompt_Desition=0 # def prompt_desition(message, proceed_label, cancel_label): "Display a window with the selected message with two buttons in way to take a desition. If cancel_label: return_var=0 , if proceed_label: return_var=1." def cancel_label_desition(): prompt_window.destroy() def proceed_label_desition(): global Prompt_Desition Prompt_Desition=1 prompt_window.destroy() prompt_window=Tk() prompt_window.configure() prompt_window.wm_title() prompt_window.resizable(0,0) lb1 = Label(prompt_window, text=message) lb1.pack() button_proceed_label = Button(prompt_window, text=proceed_label,command=proceed_label_desition) button_proceed_label.pack() button_cancel_label = Button(prompt_window, text=cancel_label,command=cancel_label_desition) button_cancel_label.pack() prompt_window.mainloop() def delete_program_data(): "Delete all the data stored by this program" global Prompt_Desition message="Do you want to delete all the data stored by this program?" prompt_desition(message, "Proceed", "Cancel") if Prompt_Desition==1: if os.path.exists(Script_Location+"/program-data"): os.system("rm -r "+Script_Location+"/program-data") print "Program-data deleted" else: print "No program-data" if os.path.exists(Script_Location+"/computer-data"): os.system("rm -r "+Script_Location+"/computer-data") print "Computer-Data Deleted" else: print "No computer-data" Prompt_Desition=0 def main_window_gui(): window1=Tk() window1.wm_title(Script_Title) window1.resizable(0,0) # dont resize b100 = Button(window1, text="Delete",command=delete_program_data) b100.pack() window1.mainloop() main_window_gui() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] While truth
On Tue, May 20, 2014 at 08:25:48AM +, Ian D wrote: > I was reading a tutorial that had these examples in it: > > >>> while False: > > print("False is the new True.") [... snip examples ...] > I was wondering if the gist of a while statement could be explained in > the context of these examples. > > e.g. while False: > > means while True is False, which is never True because True is of > course True not False. > > but while 6: > > means. err while 6 is True? and this is True because... err. Not quite "6 is True", except figuratively speaking. It might be easier to consider if...else rather than while, although the rules are exactly the same. An if...else block looks at a value, and then decides which branch to take: the "if" part or the "else" part. So we might have something like: if condition: do_this() else: do_that() While-loops are similar, except that they repeat so long as the condition is a true value, rather than just once. while condition: do_this() Now, why did I say "the condition is a true value" instead of "the condition is True"? To explain, let me contrast Python with some other programming languages. In some programming languages, the condition in an if or while statement is restricted to one of exactly two values, usually called True and False. These values are called "Booleans" (named after the mathematician who first worked on them, George Boole) or just "bools". Any other value, like 6, or None, or "Hello World", is an error. In those languages, "if condition" will take one branch if condition is True, and the other branch if False, and there are no other possibilities: if condition: print("condition is True") else: print("condition is False") *Python is not like this.* In languages like Python, the value being tested can have many different values. We can describe this in various ways: # This is what Python does. if condition: print("condition is a truthy value") print("condition is true-ish") print("in a boolean context, condition is true") print("condition is something") else: print("condition is a falsey value") print("condition is false-ish") print("in a boolean context, condition is false") print("condition is nothing") Think of this as "duck-typing for bools". Most of the time, we don't care if condition is *actually* True or False, only whether it is true-like or false-like. Many other languages do something similar to this, e.g. Javascript, PHP, Ruby, and so on. Notice that I use (big T) True and (big F) False to refer to the actual Python constants True and False, and (small t) true and (small f) false to refer to things which are truthy or falsey. Back to our if...else statement, or while statement: the condition doesn't have to be an actual bool True or False, it can be any value at all. Try running this bit of code and see what it prints: for condition in ("Hello World", 23, [], "", None, 1.5, 0.0, [1, 2, 3]): if condition: print("%r is a truthy value" % condition) else: print("%r is a falsey value" % condition) Can you see the pattern? I suggest you run the above before reading on. Don't worry, I'll wait... W E A R E W A I T I N G Can you see the pattern? In Python, values which represent "something" are considered truthy. Those which represent "nothing" or "empty" are considered falsey. So we have: Falsey values: None 0 0.0 empty string "" empty list [] empty tuple () empty dict {} and of course False Truthy values: any non-zero integer, like 1, 2, -3, ... any non-zero float, like 2.5, 17.8, -100.1, ... any non-empty string, like "spam", "eggs", ... any non-empty list, like [1, 2, 3] any non-empty tuple, like (0, 1) any non-empty dict, like {23: "twenty-three"} and of course True 99% of the time, you shouldn't care whether something is actually True or False. Well, perhaps 90% of the time. But, if you do care, you can convert any object you like to True or False by calling bool() on it: bool(None) => returns False, because None is falsey bool(101) => returns True, because 101 is truthy What do you think bool("False") will return? Since it's a string, and it is not the empty string "", it will return True. If you need to convert the string "False" to False, you need to test for it yourself. A few words of advice. Never write something like this: while bool(value): ... since the call to bool() is redundant. Python already checks to see whether value is truthy, calling bool() just does it twice. But even worse is this: while bool(value) is True: ... That just displays unfamiliarity with boolean logic and makes you look ignorant. bool(value) will return True or False, so comparing it to True is redundant. If you don't trust that, where do you stop? while bool(value): ... while bool(value) is True: ... while (bool(value) is True) is True: ... while ((bo
Re: [Tutor] Return Variable from Function.
On 20/05/14 13:33, rsm wrote: I've been having some problems to return the variable from a function so i decided to try to do it with with global variables, That's usually a bad idea. However, what you have not shown us is what you did try that didn't work. (Unless thats what the snippet below is?) In principle its easy you just type return variable and the function terminates at that point and returns the variable. what i would like create a function that creates a window for taking a choice and returns a variable in order to proceed using the choice of that variable. However, that is usually a standard feature of any GUI toolkit so you should probably look a little closer at your widget set and seee if three are any standard dialogs available. You don;t say which GUI toolkit you are using but if it were Tkinter (and it looks like it may be) you'd do something like (for python3) import tkinter.messagebox as mbox or (for Python2) import tkmessagebox result = mbox.askyesno("Your title here", "Your yes/no question here") if result: print ("You said yes!") else: print("Sorry, no go") With several other options available... You can see more in my GUI topic of my tutor...(look in Version 2) Most GUIs will have similar facilities. if Prompt_Desition==1: if os.path.exists(Script_Location+"/program-data"): os.system("rm -r "+Script_Location+"/program-data") print "Program-data deleted" else: print "No program-data" You probably shouldn't mix print statements and GUI input it tends to be look confusing. GUI output from text input is often OK but if the user is interacting with a GUI they tend not to expect output in a terminal. if os.path.exists(Script_Location+"/computer-data"): os.system("rm -r "+Script_Location+"/computer-data") print "Computer-Data Deleted" else: print "No computer-data" Prompt_Desition=0 is executed when the main_window_gui() window is closed. i don't understand why. See below b100 = Button(window1, text="Delete",command=prompt_desition(message, proceed_label, cancel_label)) b100.pack() Here you are calling the function prompt_desition() rather than referencing it. Also the button command function must not take any a.rguments They way rtound that is to do this: >b100 = Button(window1, text="Delete", command=lambda m=message, pl=proceed_label, cl=cancel_label : prompt_desition(m,pl,cl)) def prompt_desition(message, proceed_label, cancel_label): "Display a window with the selected message with two buttons in way to take a desition. If cancel_label: return_var=0 , if proceed_label: return_var=1." those should probably be triple quotes... def cancel_label_desition(): prompt_window.destroy() def proceed_label_desition(): global Prompt_Desition Prompt_Desition=1 prompt_window.destroy() prompt_window=Tk() prompt_window.configure() prompt_window.wm_title() prompt_window.resizable(0,0) lb1 = Label(prompt_window, text=message) lb1.pack() button_proceed_label = Button(prompt_window, text=proceed_label,command=proceed_label_desition) button_proceed_label.pack() button_cancel_label = Button(prompt_window, text=cancel_label,command=cancel_label_desition) button_cancel_label.pack() prompt_window.mainloop() def delete_program_data(): "Delete all the data stored by this program" global Prompt_Desition message="Do you want to delete all the data stored by this program?" prompt_desition(message, "Proceed", "Cancel") if Prompt_Desition==1: if os.path.exists(Script_Location+"/program-data"): os.system("rm -r "+Script_Location+"/program-data") print "Program-data deleted" else: print "No program-data" if os.path.exists(Script_Location+"/computer-data"): os.system("rm -r "+Script_Location+"/computer-data") print "Computer-Data Deleted" else: print "No computer-data" Prompt_Desition=0 def main_window_gui(): window1=Tk() window1.wm_title(Script_Title) window1.resizable(0,0) # dont resize b100 = Button(window1, text="Delete",command=delete_program_data) b100.pack() window1.mainloop() main_window_gui() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscrib
Re: [Tutor] Return Variable from Function.
>Thanks so much for your answer Alan! it gave me something to work with :), unfortunately it stills not working :/ > >I've made several comments in the code... >def prompt_desition(message, proceed_label, cancel_label,return_value): > "Display a window with the selected message with two buttons in way to take a desition. If cancel_label: return_var=0 , if proceed_label: return_var=1." > > def cancel_label_desition(return_value): > prompt_window.destroy() > return_value=0 > > print "no" > > return return_value > > def proceed_label_desition(return_value): > prompt_window.destroy() > return_value=1 > > print "yes" > > return return_value > >These two functions should probably be left outside your prompt_desition >function. There is no real need to define these every time this function is called. They don't change. Also note that although they both define return_value and indeed return it that does not make the variable known to the outer function, it is still only local to the two functions. prompt_window=Tk() > >You already have a top level window (Tk) so you should either use it or >instead create a dialog window using Toplevel() instead of Tk() button_proceed_label = Button(prompt_window, text=proceed_label,command=lambda :proceed_label_desition(return_value)) > >The lambda calls the function with a return_value argument but return_value is not known at this point. It is not a defined name within this functions scope. button_cancel_label = Button(prompt_window, text=cancel_label,command=lambda :cancel_label_desition(return_value)) > > >Same here prompt_window.mainloop() > > > >You really only want a single mainloop() running in your GUI, and that's >the top level one defined in main() >def delete_program_data(): > "Delete all the data stored by this program" > message="Do you want to delete all the data stored by this program?" > prompt_desition(message, "Proceed", "Cancel", "choice") > >You shouldn't really mix event handler/command functions with functions you >call directly. It can get awfully confusing. Sometimes it works but often it gets messy. Better to define the general function and then have an event handler call that indirectly. (Or use a lambda such as you are almost doing...) But the real issue here is that you are not storing the return value from the prompt_desition() function anywhere, so what is your choice (in the next line) based on? if choice==1: > > if os.path.exists(Script_Location+"/program-data"): > os.system("rm -r "+Script_Location+"/program-data") > print "Program-data deleted" > else: > print "No program-data" > > if os.path.exists(Script_Location+"/computer-data"): > os.system("rm -r "+Script_Location+"/computer-data") > print "Computer-Data Deleted" > else: > print "No computer-data" > > > I think you need to rethink the structure of your GUI. Lookingt at the code below it defines a window containing nothing but a single button. That button then calls another function which then builds another window. Can you think of any popular GUI application that works like that? I can't. Try to envision what the GUI should look and feel like to the user, Then build your code around that. Think about the data displayed and the actions that your user will do to perform work. Then link those actions to the functions that perform it. This design feels like you are trying to build a text oriented CLI using a GUI rather than design an event driven true GUI program. def main_window_gui(): > > window1=Tk() > window1.wm_title() > window1.resizable(0,0) # dont resize > > b100 = Button(window1, text="Delete", command=delete_program_data) > b100.pack() > > window1.mainloop() > > >main_window_gui() > >___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] While truth
On Tue, May 20, 2014 at 1:25 AM, Ian D wrote: > I was reading a tutorial that had these examples in it: > > while False: > print("False is the new True.") > > while 6: > print("Which numbers are True?") > > > while -1: > print("Which numbers are True?") > > > while 0: > print("Which numbers are True?") > > Unfortunately the author never explained these statements. The statements above are trying to talk about what Python considers to be "true". In some languages, there is a single distinguished true value. Python chooses a broader definition that allows everything to be considered true, with the exception of the following values: False None Numeric zero Empty collection Empty string Reference: https://docs.python.org/3/reference/expressions.html#booleans We care about what values are true, because they are the switch that controls which way we're flowing through a conditional statement like "if" or "while". As people are pointing out, the examples above are a bit disappointing. They are demonstrating this with infinite while loops, and that's probably not a great idea because the output will be so overwhelming to be actively distracting. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] While truth
You can test out a condition like this in IDLE like so: while 6: print "yes its true" break while 0: print "yes its true" break while -1: print "yes its true" break emptyList = [] while emtpyList: print "yes its true" break This way you don't have to deal with an infinite loop. It will print "yes its true" once, if it IS true and then "break" will break you out of the loop. On Tue, May 20, 2014 at 2:00 PM, Danny Yoo wrote: > On Tue, May 20, 2014 at 1:25 AM, Ian D wrote: >> I was reading a tutorial that had these examples in it: >> >> > while False: >> print("False is the new True.") >> >> > while 6: >> print("Which numbers are True?") >> >> >> while -1: >> print("Which numbers are True?") >> >> >> while 0: >> print("Which numbers are True?") >> >> Unfortunately the author never explained these statements. > > > The statements above are trying to talk about what Python considers to > be "true". In some languages, there is a single distinguished true > value. Python chooses a broader definition that allows everything to > be considered true, with the exception of the following values: > > False > None > Numeric zero > Empty collection > Empty string > > Reference: https://docs.python.org/3/reference/expressions.html#booleans > > We care about what values are true, because they are the switch that > controls which way we're flowing through a conditional statement like > "if" or "while". > > As people are pointing out, the examples above are a bit > disappointing. They are demonstrating this with infinite while loops, > and that's probably not a great idea because the output will be so > overwhelming to be actively distracting. > ___ > 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] While truth
On Tue, May 20, 2014 at 11:44 AM, C Smith wrote: > You can test out a condition like this in IDLE like so: > while 6: > print "yes its true" > break > > > while 0: > print "yes its true" > break > > > while -1: > print "yes its true" > break > > > emptyList = [] > while emtpyList: > print "yes its true" > break > > This way you don't have to deal with an infinite loop. > It will print "yes its true" once, if it IS true and then "break" will > break you out of the loop. That being said, if we're going to go through these contortions, we might as well use "if", right? :P The infinite loops in the examples above are a complete distraction from the main point, I think. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] While truth
Of course that isn't very useful code. I thought it might be a useful quick test for someone learning how while loops treat different values. On Tue, May 20, 2014 at 2:46 PM, Danny Yoo wrote: > On Tue, May 20, 2014 at 11:44 AM, C Smith > wrote: >> You can test out a condition like this in IDLE like so: >> while 6: >> print "yes its true" >> break >> >> >> while 0: >> print "yes its true" >> break >> >> >> while -1: >> print "yes its true" >> break >> >> >> emptyList = [] >> while emtpyList: >> print "yes its true" >> break >> >> This way you don't have to deal with an infinite loop. >> It will print "yes its true" once, if it IS true and then "break" will >> break you out of the loop. > > > That being said, if we're going to go through these contortions, we > might as well use "if", right? :P > > > The infinite loops in the examples above are a complete distraction > from the main point, I think. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Main function
I am a beginner at python programming and right now we have to write the text to design a program that will make a histogram for Benford's law which says that in a natural set of data 1 will appear more than 2 which will appear more than 3 and so on. So given a set of data I want a list showing how many times each number appears. Since I'm new to python and don't really know how to write programs yet, my first question would be what exactly is the main function, because we did a similar assignment before this one that included it, and I'm not sure what exactly it does. Gabe Wheeler (512)964-5421 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Main function
> Since I'm new to python and don't really know how to write programs yet, my > first question would be what exactly is the main function, because we did a > similar assignment before this one that included it, and I'm not sure what > exactly it does. When you write a program, you write a collection of function and variable definitions. But they don't have to be in too particular of an order. For example, we might have something like # def f(x): return x * x def g(x): return x**0.5 def h(a, b): return g(f(a) + f(b)) # But nothing stops us from writing the definitions in a different order: # def h(a, b): return g(f(a) + f(b)) def g(x): return x**0.5 def f(x): return x * x # However, it does leave the question of: how do you start a program, and from where do things begin? In most programming languages, you choose a particular function and designate it as the "main" entry point into your program. # def h(a, b): return g(f(a) + f(b)) def g(x): return x**0.5 def f(x): return x * x def main(): print("The hypotenuse is: %d" % h(3, 4)) # In Python, you don't have to call it "main", but in several other languages, you do. There's one more piece you add to the bottom of the program to start things going, a snippet that looks like this: if __name__ == '__main__': main() This is a purely Python issue. It says that if the file is being run as the main program (in which case, the __name__ is '__main__'), then kick things off by calling the main function. You put this at the bottom of your program. # def h(a, b): return g(f(a) + f(b)) def g(x): return x**0.5 def f(x): return x * x def main(): print("The hypotenuse is: %d" % h(3, 4)) if __name__ == '__main__': main() # See: http://effbot.org/pyfaq/tutor-what-is-if-name-main-for.htm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] How to create web interface?
On May 14, Danny Yoo wrote: > > Another option might be to turn your program into a web site, so that > > the interface is the web browser, which everyone is getting used to > > these days. But this, too, is also... involved. :P I have a little volunteer scheduling application I've written as a module, with about a dozen functions, that reads and writes to a Sqlite database. I'd like to run a web server on my machine just for my local use. I don't understand how precisely the web page would communicate with the python program. If anyone has a suggestion on specific modules, and tutorials to use to create a web interface for a python program, I'd love to hear it. I'm using python 2.7 on OSX Mavericks. I'm fairly new to python. I have some experience with apache, and php, I comfortable with HTML. I'm also happy to know where a better forum for this question would be. Thank you, Paul McCombs ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to create web interface?
> I don't understand how precisely the web page would communicate with > the python program. In the simplest case, the webserver software executes your script. Whatever you print() _is_ the webpage. The webserver sends whatever you print() to the user's browser. http://en.wikipedia.org/wiki/Common_Gateway_Interface Alan ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to create web interface?
> I don't understand how precisely the web page would communicate with > the python program. Whenever you're communicating to a web site, you are contacting a live program, a "web server". In typical usage, a web server delivers static files from its file system. But it doesn't have to be that way. The server is running an arbitrary program. When we use the term "web page", we're hiding a lot of the fundamental, dynamic details: there's a program that's backing the generation of a web page. See: https://developers.google.com/appengine/docs/python/gettingstartedpython27/helloworld for example. In contrast to traditional programs, in web programs, the "entry point" is no longer a main function. Instead, your program is continuously running, and you're in a loop that responds to web requests. In the example above, the loop is implicit, because the framework is doing the looping for us, and calling into our code for each request. Other frameworks make the loop a lot more explicit. e.g. https://docs.python.org/2/library/basehttpserver.html#more-examples where you can see that there's a while loop that handles "requests". A "web request" will happen when someone is visiting your "web page", or when you're submitting a form to the "web page". Those requests hit the server, and that's where you can do something to interact with the user. You treat the values of form elements as if they were parameters, and you treat the request handling as if it were a regular function call. The output of the "function call" will be the response that's sent back to the web browser. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to create web interface?
Hi, On 20 May 2014 21:00, P McCombs wrote: > On May 14, Danny Yoo wrote: >> > Another option might be to turn your program into a web site, so that >> > the interface is the web browser, which everyone is getting used to >> > these days. But this, too, is also... involved. :P > > I have a little volunteer scheduling application I've written as a > module, with about a dozen functions, that reads and writes to a > Sqlite database. I'd like to run a web server on my machine just for > my local use. > > I don't understand how precisely the web page would communicate with > the python program. > > If anyone has a suggestion on specific modules, and tutorials to use > to create a web interface for a python program, I'd love to hear it. You might want to work through this: http://pythonpaste.org/do-it-yourself-framework.html Or this, a newer version: http://docs.webob.org/en/latest/do-it-yourself.html (but it contains a lot more detail and a lot more advanced Python concepts...) Alternatively you can have a look at one of the many small and micro web frameworks available for Python, e.g web2py, flask, bottle, cherrypy etc. Links: http://www.web2py.com/ (tutorial: http://mherman.org/blog/2012/11/27/crash-course-in-web2py-part-1/#.U3vVpvldVSk also: http://web2py.com/books/default/chapter/29/01/introduction) http://flask.pocoo.org/ (tutorial: http://flask.pocoo.org/docs/tutorial/ also: http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world ) http://bottlepy.org/docs/dev/index.html (tutorial: http://bottlepy.org/docs/dev/tutorial.html) http://www.cherrypy.org/ (tutorial: http://docs.cherrypy.org/en/latest/tutorial/index.html) Cherrypy is perhaps a nice one for you to start with. Hope that helps! Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to create web interface?
On 20/05/14 21:00, P McCombs wrote: On May 14, Danny Yoo wrote: Another option might be to turn your program into a web site, so that the interface is the web browser, which everyone is getting used to these days. But this, too, is also... involved. :P I have a little volunteer scheduling application I've written as a module, with about a dozen functions, that reads and writes to a Sqlite database. I'd like to run a web server on my machine just for my local use. I don't understand how precisely the web page would communicate with the python program. If you want to understand the basics then the cgi module in the standard lib is a good starting point. It makes life a bit easier than nothing but exposes the underlying technology. But if you want something to keep you sane and make web programming easy then Pyhon has more web frameworks than you can shake a stick at. From very simple (Flask, CherryPy) to very complex (Django, Zope). There is a good page on the python.org web site that summarises the technology and many of the most popular frameworks but ultimately you just pick one and work through its tutorial. Start here for theory: https://docs.python.org/3/howto/webservers.html and go here for the list: https://wiki.python.org/moin/WebFrameworks HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to create web interface?
Thank you all for your responses. This is exactly the information I was looking for. Paul McCombs On Tue, May 20, 2014 at 4:36 PM, Alan Gauld wrote: > On 20/05/14 21:00, P McCombs wrote: >> >> On May 14, Danny Yoo wrote: Another option might be to turn your program into a web site, so that the interface is the web browser, which everyone is getting used to these days. But this, too, is also... involved. :P >> >> >> I have a little volunteer scheduling application I've written as a >> module, with about a dozen functions, that reads and writes to a >> Sqlite database. I'd like to run a web server on my machine just for >> my local use. >> >> I don't understand how precisely the web page would communicate with >> the python program. > > > If you want to understand the basics then the cgi module in the standard lib > is a good starting point. It makes life a bit > easier than nothing but exposes the underlying technology. > > But if you want something to keep you sane and make web > programming easy then Pyhon has more web frameworks than > you can shake a stick at. From very simple (Flask, CherryPy) > to very complex (Django, Zope). > > There is a good page on the python.org web site that summarises > the technology and many of the most popular frameworks but > ultimately you just pick one and work through its tutorial. > > Start here for theory: > > https://docs.python.org/3/howto/webservers.html > > and go here for the list: > > https://wiki.python.org/moin/WebFrameworks > > > HTH > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Find Daily max - create lists using date and add hourly data to that list for the day
I have hourly 2D temperature data in a monthly netcdf and I would like to find the daily maximum temperature. The shape of the netcdf is (744, 106, 193) I would like to use the year-month-day as a new list name (i.e. 2009-03-01, 2009-03-022009-03-31) and then add each of the hours worth of temperature data to each corresponding list. Therefore each new list should contain 24 hours worth of data and the shape should be (24,106,193) . This is the part I cannot seem to get to work. I am using datetime and then groupby to group by date but I am not sure how to use the output to make a new list name and then add the data for that day into that list. see below and attached for my latest attempt. Any feedback will be greatly appreciated. from netCDF4 import Dataset import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from netcdftime import utime from datetime import datetime as dt import os import gc from numpy import * import pytz from itertools import groupby MainFolder=r"/DATA/2009/03" dailydate=[] alltime=[] lists={} ncvariablename='T_SFC' for (path, dirs, files) in os.walk(MainFolder): for ncfile in files: print ncfile fileext='.nc' if ncfile.endswith(ncvariablename+'.nc'): print "dealing with ncfiles:", path+ncfile ncfile=os.path.join(path,ncfile) ncfile=Dataset(ncfile, 'r+', 'NETCDF4') variable=ncfile.variables[ncvariablename][:,:,:] TIME=ncfile.variables['time'][:] ncfile.close() for temp, time in zip((variable[:]),(TIME[:])): cdftime=utime('seconds since 1970-01-01 00:00:00') ncfiletime=cdftime.num2date(time) timestr=str(ncfiletime) utc_dt = dt.strptime(timestr, '%Y-%m-%d %H:%M:%S') au_tz = pytz.timezone('Australia/Sydney') local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(au_tz) alltime.append(local_dt) for k, g in groupby(alltime, key=lambda d: d.date()): kstrp_local=k.strftime('%Y-%m-%d_%H') klocal_date=k.strftime('%Y-%m-%d') dailydate.append(klocal_date) for n in dailydate: lists[n]=[] lists[n].append(temp) big_array=np.ma.concatenate(lists[n]) DailyTemp=big_array.max(axis=0) from netCDF4 import Dataset import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from netcdftime import utime from datetime import datetime as dt import os import gc from numpy import * import pytz from itertools import groupby MainFolder=r"/DATA/2009/03" dailydate=[] alltime=[] lists={} ncvariablename='T_SFC' for (path, dirs, files) in os.walk(MainFolder): for ncfile in files: print ncfile fileext='.nc' if ncfile.endswith(ncvariablename+'.nc'): print "dealing with ncfiles:", path+ncfile ncfile=os.path.join(path,ncfile) ncfile=Dataset(ncfile, 'r+', 'NETCDF4') variable=ncfile.variables[ncvariablename][:,:,:] TIME=ncfile.variables['time'][:] ncfile.close() for temp, time in zip((variable[:]),(TIME[:])): cdftime=utime('seconds since 1970-01-01 00:00:00') ncfiletime=cdftime.num2date(time) timestr=str(ncfiletime) utc_dt = dt.strptime(timestr, '%Y-%m-%d %H:%M:%S') au_tz = pytz.timezone('Australia/Sydney') local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(au_tz) alltime.append(local_dt) for k, g in groupby(alltime, key=lambda d: d.date()): kstrp_local=k.strftime('%Y-%m-%d_%H') klocal_date=k.strftime('%Y-%m-%d') dailydate.append(klocal_date) for n in dailydate: lists[n]=[] lists[n].append(temp) big_array=np.ma.concatenate(lists[n]) DailyTemp=big_array.max(axis=0) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor