From ben+python at benfinney.id.au Sat Oct 1 00:22:46 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 01 Oct 2016 14:22:46 +1000 Subject: [Tutor] Passing functions as arguments to other functions References: Message-ID: <85ponkk8a1.fsf@benfinney.id.au> boB Stepp writes: > I think this was my key point of confusion. I was mistakenly thinking > of f(x) as referring to the function object. Right. ?f? is an expression, that Python resolves as whatever object ?f? references. ?f(x)? is an expression, that Python resolves by *calling* the object referenced by ?f?, and resolves to whatever object that call returns. Both of them are expressions. ?f? is rightly termed a reference in both of them. Only the first expression (the name ?f? alone) is reasonably termed a reference. > Instead, it is calling that object with argument x I hope it will help for you to think in terms of ?What value does this expression resolve to?? -- \ ?Alternative explanations are always welcome in science, if | `\ they are better and explain more. Alternative explanations that | _o__) explain nothing are not welcome.? ?Victor J. Stenger, 2001-11-05 | Ben Finney From robertvstepp at gmail.com Sat Oct 1 00:24:36 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Fri, 30 Sep 2016 23:24:36 -0500 Subject: [Tutor] Testing print In-Reply-To: <20160930100707.GY22471@ando.pearwood.info> References: <20160930100707.GY22471@ando.pearwood.info> Message-ID: On Fri, Sep 30, 2016 at 5:07 AM, Steven D'Aprano wrote: [snip] > and preferably three: > > (1) function that does the calculation; > (2) function that does the output; > (3) function that calls (1) and then (2) > > > If (1) and (2) are well-designed, then (3) is so trivial it needs no > tests: > > def main(): > x = calculate(stuff) > report(x) > > but of course it's not always that simple. Nevertheless, that's the > ideal you should aim for. OK, I want to make sure I have this thoroughly comprehended. I have rewritten my once simple program into the following: =============================================================================== '''Exerise 3.1 from "Think Python 2" by Allen Downey. This module will take a string and right justify it so that the last character of the line will fall in column 70 of the display. The results will be printed to stdout.''' def right_justify(a_string): '''This fucntion will take the string, "a_string", and right justify it by padding it with spaces until its last character falls in column 70 of the display. If "a_string" has more than 70 characters, then "a_string" will be truncated to 70 characters. The padded or truncated string will be returned along with a message if "a_string" is truncated.''' if len(a_string) <= 70: num_pad_spcs = 70 - len(a_string) return ((' ' * num_pad_spcs) + a_string), # Note trailing comma. else: msg = ("The string has too many characters (> 70)!\n" + "Only a partial, 70 character line will be returned.") return msg, a_string[:70] def print_msgs(*msgs): '''Prints messages to stdout.''' for msg in msgs: print(msg) def main(input_strings): '''Run main program.''' print('0123456789' * 7) # Print a number guide to check length of line. for input_string in input_strings: print_msgs(*right_justify(input_string)) if __name__ == '__main__': input_strings = [ "Monty Python", "She's a witch!", "Beware of the rabbit!!! She is a vicious beast who will rip" " your throat out!", ""] main(input_strings) ============================================================================= Does this meet the criteria of each function doing its specific thing? Or is there something else I need to decouple/improve? -- boB From robertvstepp at gmail.com Sat Oct 1 01:23:46 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 1 Oct 2016 00:23:46 -0500 Subject: [Tutor] Testing print In-Reply-To: <510831294.3536646.1475298756603@mail.yahoo.com> References: <20160930100707.GY22471@ando.pearwood.info> <510831294.3536646.1475298756603@mail.yahoo.com> Message-ID: On Sat, Oct 1, 2016 at 12:12 AM, Richard Doksa wrote: > unsubscibe please If you wish to unsubscribe, go to the bottom of this page and follow its instructions: https://mail.python.org/mailman/listinfo/tutor boB From alan.gauld at yahoo.co.uk Sat Oct 1 03:02:23 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 1 Oct 2016 08:02:23 +0100 Subject: [Tutor] Testing print In-Reply-To: References: <20160930100707.GY22471@ando.pearwood.info> Message-ID: On 01/10/16 05:24, boB Stepp wrote: > =============================================================================== > '''Exerise 3.1 from "Think Python 2" by Allen Downey. > > This module will take a string and right justify it so that the last character > of the line will fall in column 70 of the display. The results will be > printed to stdout.''' > > def right_justify(a_string): > def print_msgs(*msgs): > '''Prints messages to stdout.''' > > for msg in msgs: > print(msg) > > def main(input_strings): > '''Run main program.''' > > print('0123456789' * 7) # Print a number guide to check length of line. > for input_string in input_strings: > print_msgs(*right_justify(input_string)) Do you need print_msgs()? Won't it work the same with print(right_justify(input_string)) You are only feeding one line at a time into the print msgs. You could do it all in a new print_msgs() like: def print_msgs(formatter, msgs): for msg in msgs: print(formatter(msg)) And main() reduces to def main(): print_msgs(right_justify, input_strings) But I think I'd just leave it as you have it but without the print_msgs()... -- 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 From robertvstepp at gmail.com Sat Oct 1 11:12:10 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 1 Oct 2016 10:12:10 -0500 Subject: [Tutor] Testing print In-Reply-To: References: <20160930100707.GY22471@ando.pearwood.info> Message-ID: On Sat, Oct 1, 2016 at 2:02 AM, Alan Gauld via Tutor wrote: > On 01/10/16 05:24, boB Stepp wrote: > >> =============================================================================== >> '''Exerise 3.1 from "Think Python 2" by Allen Downey. >> >> This module will take a string and right justify it so that the last character >> of the line will fall in column 70 of the display. The results will be >> printed to stdout.''' >> >> def right_justify(a_string): > >> def print_msgs(*msgs): >> '''Prints messages to stdout.''' >> >> for msg in msgs: >> print(msg) >> >> def main(input_strings): >> '''Run main program.''' >> >> print('0123456789' * 7) # Print a number guide to check length of line. >> for input_string in input_strings: >> print_msgs(*right_justify(input_string)) > > Do you need print_msgs()? > Won't it work the same with > > print(right_justify(input_string)) > > You are only feeding one line at a time into the print msgs. [snip] > But I think I'd just leave it as you have it but > without the print_msgs()... I would still need to unpack the arguments returned by right_justify() that get fed to print(): print(*right_justify(input_string)) And I would have to add an additional "\n" to msg in the else clause of right_justify(): msg = ("The string has too many characters (> 70)!\n" + "Only a partial, 70 character line will be returned.\n") so that the result formats the same as the original intent. This gives me main() now as: def main(input_strings): '''Run main program.''' print('0123456789' * 7) # Print a number guide to check length of line. for input_string in input_strings: print(*right_justify(input_string)) Doing this did not occur to me because I was blind to treating print(*args) like any other function in regards to argument unpacking. One of the many wonderful things about Python is its consistency! Thanks, Alan! -- boB From robertvstepp at gmail.com Sat Oct 1 11:31:58 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 1 Oct 2016 10:31:58 -0500 Subject: [Tutor] Testing print In-Reply-To: References: <20160930100707.GY22471@ando.pearwood.info> Message-ID: On Sat, Oct 1, 2016 at 2:02 AM, Alan Gauld via Tutor wrote: > Do you need print_msgs()? > Won't it work the same with > > print(right_justify(input_string)) > > You are only feeding one line at a time into the print msgs. > > You could do it all in a new print_msgs() like: > > def print_msgs(formatter, msgs): > for msg in msgs: > print(formatter(msg)) > > And main() reduces to > > def main(): > print_msgs(right_justify, input_strings) I have to say this thought you gave ties in nicely with the other thread ([Tutor] Passing functions as arguments to other functions) I started in parallel with this one. A practical example of passing a function to another function... -- boB From spawgi at gmail.com Sat Oct 1 11:39:11 2016 From: spawgi at gmail.com (spawgi at gmail.com) Date: Sat, 1 Oct 2016 08:39:11 -0700 Subject: [Tutor] Unsubscribe Message-ID: On Sat, Oct 1, 2016 at 8:12 AM, boB Stepp wrote: > On Sat, Oct 1, 2016 at 2:02 AM, Alan Gauld via Tutor > wrote: > > On 01/10/16 05:24, boB Stepp wrote: > > > >> ============================================================ > =================== > >> '''Exerise 3.1 from "Think Python 2" by Allen Downey. > >> > >> This module will take a string and right justify it so that the last > character > >> of the line will fall in column 70 of the display. The results will be > >> printed to stdout.''' > >> > >> def right_justify(a_string): > > > >> def print_msgs(*msgs): > >> '''Prints messages to stdout.''' > >> > >> for msg in msgs: > >> print(msg) > >> > >> def main(input_strings): > >> '''Run main program.''' > >> > >> print('0123456789' * 7) # Print a number guide to check length > of line. > >> for input_string in input_strings: > >> print_msgs(*right_justify(input_string)) > > > > Do you need print_msgs()? > > Won't it work the same with > > > > print(right_justify(input_string)) > > > > You are only feeding one line at a time into the print msgs. > > [snip] > > > But I think I'd just leave it as you have it but > > without the print_msgs()... > > I would still need to unpack the arguments returned by right_justify() > that get fed to print(): > > print(*right_justify(input_string)) > > And I would have to add an additional "\n" to msg in the else clause > of right_justify(): > > msg = ("The string has too many characters (> 70)!\n" + > "Only a partial, 70 character line will be returned.\n") > > so that the result formats the same as the original intent. This > gives me main() now as: > > def main(input_strings): > '''Run main program.''' > > print('0123456789' * 7) # Print a number guide to check length of > line. > for input_string in input_strings: > print(*right_justify(input_string)) > > Doing this did not occur to me because I was blind to treating > print(*args) like any other function in regards to argument unpacking. > > One of the many wonderful things about Python is its consistency! > > Thanks, Alan! > > > > -- > boB > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- We can do it and do it better. From anish198519851985 at gmail.com Sat Oct 1 04:16:56 2016 From: anish198519851985 at gmail.com (anish singh) Date: Sat, 1 Oct 2016 01:16:56 -0700 Subject: [Tutor] receiving regular expression from command line Message-ID: I am trying to implement grep to just increase my knowledge about regular expression. Below is the program usage: python test.py -i Documents/linux/linux/ -s '\w+_readalarm*' However, due to my lack of knowledge about string handling in python, I am getting wrong results. def read_file(file, pattern): with open(file, 'r') as outfile: for line in outfile: match = re.compile(str(pattern)).match(line) if match: print(file + " " + match.group()) Can someone let me know how can I pass regular expression from command line? Whole code: http://ideone.com/KxLJP2 Any other comments about the code are most welcome. From alan.gauld at yahoo.co.uk Sat Oct 1 12:35:07 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 1 Oct 2016 17:35:07 +0100 Subject: [Tutor] Testing print In-Reply-To: References: <20160930100707.GY22471@ando.pearwood.info> Message-ID: On 01/10/16 16:12, boB Stepp wrote: >>> This module will take a string and right justify it so that the last character >>> of the line will fall in column 70 of the display. The results will be >>> printed to stdout.''' >>> >> Do you need print_msgs()? >> Won't it work the same with >> >> print(right_justify(input_string)) >> > I would still need to unpack the arguments returned by right_justify() > that get fed to print(): Ah, I read the assignment spec but not your comment (or code) so didn't notice that your justify function sometimes returns multiple arguments. Personally I don't like functions that sometimes return one and sometimes two results. I'd rather you returned a None first argument in the first case to make it consistent. But given you are returning multiple arguments then yes you need: > print(*right_justify(input_string)) But coming back to the issue of mixing display and logic I'd probably just raise a ValueError if the input string is too long and leave it as a user requirement to check the length of the input or catch the error and display whatever message they felt appropriate. (You can include the error message in the raise if you feel the need) -- 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 From alan.gauld at yahoo.co.uk Sat Oct 1 12:42:40 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 1 Oct 2016 17:42:40 +0100 Subject: [Tutor] receiving regular expression from command line In-Reply-To: References: Message-ID: On 01/10/16 09:16, anish singh wrote: > I am trying to implement grep to just increase my knowledge > about regular expression. > > Below is the program usage: > python test.py -i Documents/linux/linux/ -s '\w+_readalarm*' > > However, due to my lack of knowledge about string handling > in python, I am getting wrong results. Possibly, but we can't tell because a) You don't show us the code that parses your input b) You don't show us your output/error message How are you parsing the input? Are you using the argparse module? Or one of the older ones? Or are you trying to just test the values in sys.argv? How do you determine the input filename and the pattern? Have you proved that those values are correct before you call your read_file() function? > def read_file(file, pattern): > with open(file, 'r') as outfile: Since you are reading it it probably should be called infile? > for line in outfile: > match = re.compile(str(pattern)).match(line) > if match: > print(file + " " + match.group()) > Can someone let me know how can I pass regular expression > from command line? The real issue here is probably how you parse the input line but we can't tell. The recommended module for doing that is argparse. Try reading the module documentation which includes many examples. If you are still having problems show us your full program plus any error messages > Whole code: http://ideone.com/KxLJP2 Unless its very long (>100lines?) just post it in your email. -- 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 From robertvstepp at gmail.com Sat Oct 1 17:59:37 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 1 Oct 2016 16:59:37 -0500 Subject: [Tutor] Unsubscribe In-Reply-To: References: Message-ID: Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -- boB From robertvstepp at gmail.com Sat Oct 1 18:08:25 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 1 Oct 2016 17:08:25 -0500 Subject: [Tutor] Testing print In-Reply-To: References: <20160930100707.GY22471@ando.pearwood.info> Message-ID: On Sat, Oct 1, 2016 at 11:35 AM, Alan Gauld via Tutor wrote: > ... Personally I don't like functions that > sometimes return one and sometimes two results. I'd rather > you returned a None first argument in the first case > to make it consistent. Why don't you like doing this? What are the pluses and minuses as you see them? I actually almost wrote it to return None as you suggest, but as I had not yet had an opportunity to play with argument unpacking until now, I thought I would do so. After all, it is about the learning for me, not always doing things the same way I have been doing them. -- boB From alan.gauld at yahoo.co.uk Sat Oct 1 20:19:09 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 2 Oct 2016 01:19:09 +0100 Subject: [Tutor] Testing print In-Reply-To: References: <20160930100707.GY22471@ando.pearwood.info> Message-ID: On 01/10/16 23:08, boB Stepp wrote: > On Sat, Oct 1, 2016 at 11:35 AM, Alan Gauld via Tutor wrote: > >> ... Personally I don't like functions that >> sometimes return one and sometimes two results. I'd rather >> you returned a None first argument in the first case >> to make it consistent. > > Why don't you like doing this? What are the pluses and minuses as you > see them? Because client code has to guess which return value is relevant consider def f(x): if x%2: # is odd return x,x+1 else: return x Now I want to use f on a collection of integers: nums = [1,2,3,4] for n in nums: result = f(n) if result <= 3: # broken for 1 and 3 print("success") else: .... But if I change it to for n in nums: result = f(n) if result[0] <= 3: # now broken for 2 and 4 print("success") else: .... So I need to introduce code to determine whether I got an int or a tuple back and then separate code for each case. If I know that the result is always an int I can use the first case if I know its always a tuple I can use the second. But not knowing which is just plain messy. -- 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 From robertvstepp at gmail.com Sat Oct 1 21:46:46 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 1 Oct 2016 20:46:46 -0500 Subject: [Tutor] Testing print In-Reply-To: References: <20160930100707.GY22471@ando.pearwood.info> Message-ID: On Sat, Oct 1, 2016 at 7:19 PM, Alan Gauld via Tutor wrote: > On 01/10/16 23:08, boB Stepp wrote: >> On Sat, Oct 1, 2016 at 11:35 AM, Alan Gauld via Tutor wrote: >> >>> ... Personally I don't like functions that >>> sometimes return one and sometimes two results. I'd rather >>> you returned a None first argument in the first case >>> to make it consistent. >> >> Why don't you like doing this? What are the pluses and minuses as you >> see them? > > > Because client code has to guess which return value is relevant [snip] > So I need to introduce code to determine whether I got > an int or a tuple back and then separate code for each > case. If I know that the result is always an int I can > use the first case if I know its always a tuple I can > use the second. But not knowing which is just plain > messy. So in which sorts of scenarios would you use argument unpacking? -- boB From anish198519851985 at gmail.com Sat Oct 1 22:50:18 2016 From: anish198519851985 at gmail.com (anish singh) Date: Sat, 1 Oct 2016 19:50:18 -0700 Subject: [Tutor] Tutor Digest, Vol 152, Issue 3 In-Reply-To: References: Message-ID: > On 01/10/16 09:16, anish singh wrote: > > I am trying to implement grep to just increase my knowledge > > about regular expression. > > > > Below is the program usage: > > python test.py -i Documents/linux/linux/ -s '\w+_readalarm*' > > > > However, due to my lack of knowledge about string handling > > in python, I am getting wrong results. > > Possibly, but we can't tell because > a) You don't show us the code that parses your input > import os, sys, getopt import re import glob def get_full_path(path, pattern): for (dirpath, dirnames, filenames) in os.walk(path): match = re.search(pattern, dirpath) for filename in filenames: if filename.endswith(('.c', '.h')): yield os.path.join(dirpath, filename) def read_file(file, pattern): with open(file, 'r') as infile: for line in infile: match = re.compile(str(pattern)).match(line) if match: print(file + " " + match.group()) def main(argv): path, f_pattern, s_pattern = '', '', '' try: opts, args = getopt.getopt(argv,"hi:p:f:s:",["ifile=","file_pattern=","string_pattern="]) except getopt.GetoptError: print 'test.py -i -p ' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'test.py -i ' sys.exit() elif opt in ("-i", "--ifile"): path = arg elif opt in ("-f", "--file_pattern"): f_pattern = arg elif opt in ("-s", "--string_pattern"): s_pattern = arg.encode().decode('unicode_escape') print(s_pattern) files = get_full_path(path, f_pattern) for file in files: read_file(file, s_pattern) if __name__ == "__main__": main(sys.argv[1:]) > b) You don't show us your output/error message > output is only file names. I don't see any other output. I am running it like this: python test.py -i ~/Documents/linux-next/ -s '\w*_read_register\w*' > > How are you parsing the input? Are you using > the argparse module? Or one of the older ones? > Or are you trying to just test the values in sys.argv? > You can see the code now. > > How do you determine the input filename and the pattern? > Yes. Those are correct that is why i am getting all the file names. You can run this code on any directory and see it just provides the output as file names. > Have you proved that those values are correct before you > call your read_file() function? > Yes. > > > > def read_file(file, pattern): > > with open(file, 'r') as outfile: > > Since you are reading it it probably should be > called infile? > Done. > > > for line in outfile: > > match = re.compile(str(pattern)).match(line) > > if match: > > print(file + " " + match.group()) > > > > Can someone let me know how can I pass regular expression > > from command line? > > The real issue here is probably how you parse the > input line but we can't tell. The recommended module > for doing that is argparse. Try reading the module > documentation which includes many examples. > > If you are still having problems show us your full > program plus any error messages > > > Whole code: http://ideone.com/KxLJP2 > > Unless its very long (>100lines?) just post it > in your email. > > > From alan.gauld at yahoo.co.uk Sun Oct 2 04:42:21 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 2 Oct 2016 09:42:21 +0100 Subject: [Tutor] Testing print In-Reply-To: References: <20160930100707.GY22471@ando.pearwood.info> Message-ID: On 02/10/16 02:46, boB Stepp wrote: >> case. If I know that the result is always an int I can >> use the first case if I know its always a tuple I can >> use the second. But not knowing which is just plain >> messy. > > So in which sorts of scenarios would you use argument unpacking? Any time a tuple is returned. The problem I had with your code is that sometimes you return a string and sometimes a tuple. So I can only use argument unpacking when I get the tuple. If I always get a tuple then I can always use unpacking. Its the mix of incompatible return types that causes problems. -- 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 From alan.gauld at yahoo.co.uk Sun Oct 2 05:47:05 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 2 Oct 2016 10:47:05 +0100 Subject: [Tutor] Tutor Digest, Vol 152, Issue 3 In-Reply-To: References: Message-ID: On 02/10/16 03:50, anish singh wrote: >> Possibly, but we can't tell because >> a) You don't show us the code that parses your input Thanks, that helps. > import os, sys, getopt > import re > import glob > > > def get_full_path(path, pattern): > for (dirpath, dirnames, filenames) in os.walk(path): > match = re.search(pattern, dirpath) > for filename in filenames: > if filename.endswith(('.c', '.h')): > yield os.path.join(dirpath, filename) > def read_file(file, pattern): > with open(file, 'r') as infile: > for line in infile: > match = re.compile(str(pattern)).match(line) match() only matches at the beginning of a line. Are you sure you don't want search() which will find your pattern anywhere on the line? Also compiling the regex each time round is wasteful, you should use compile before the loop: regex = re.compile(str(pattern)) # do it once for line in infile: match = regex.match(line) Finally, you shouldn't need the str() call since your input arguments should already be strings. > if match: > print(file + " " + match.group()) > > def main(argv): > path, f_pattern, s_pattern = '', '', '' > try: > opts, args = > getopt.getopt(argv,"hi:p:f:s:",["ifile=","file_pattern=","string_pattern="]) > except getopt.GetoptError: > print 'test.py -i -p ' > sys.exit(2) > > for opt, arg in opts: > if opt == '-h':... > elif opt in ("-i", "--ifile"):... > elif opt in ("-f", "--file_pattern"):... > elif opt in ("-s", "--string_pattern"):... > files = get_full_path(path, f_pattern) Are you sure that line should be part of the opt for loop? > for file in files: > read_file(file, s_pattern) > output is only file names. I don't see any other output. Have you tested your regex function on a string that you know should match? eg at the interpreter? Without seeing your files it's hard to tell whether your regex is right or wrong, but that's what I would suspect - that it returns an empty string. Maybe try using a simpler pattern to test it? Something without any wildcard patterns, say? -- 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 From robertvstepp at gmail.com Sun Oct 2 18:47:51 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 2 Oct 2016 17:47:51 -0500 Subject: [Tutor] How to test a function which runs a passed in function twice? Message-ID: In exercise 3.2 of Downey's "Think Python 2" he has a function: def do_twice(f): f() f() As you know, I am trying to learn testing/TDD while doing these exercises. How do I test such a *general* function? Should I create a variety of arbitrary functions in my test file, call the do_twice function with each of these made up functions and see if I get the expected results? I can see doing this, but since the function to be tested is so general in nature, I do not see how I can feel confident that I am adequately testing it. I cannot even conceive of what might be edge cases for this function. Something exploring the limits of Python's functionality? -- boB From steve at pearwood.info Sun Oct 2 19:00:02 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 3 Oct 2016 10:00:02 +1100 Subject: [Tutor] How to test a function which runs a passed in function twice? In-Reply-To: References: Message-ID: <20161002230001.GD22471@ando.pearwood.info> On Sun, Oct 02, 2016 at 05:47:51PM -0500, boB Stepp wrote: > In exercise 3.2 of Downey's "Think Python 2" he has a function: > > def do_twice(f): > f() > f() > > As you know, I am trying to learn testing/TDD while doing these > exercises. How do I test such a *general* function? Should I create > a variety of arbitrary functions in my test file, call the do_twice > function with each of these made up functions and see if I get the > expected results? Probably not need to use a variety of functions. Just one is sufficient. def test_dotwice(self): storage = [] def f(): storage.append(1) assert storage == [] do_twice(demo) self.assertEqual(storage, [1, 1]) Why do I use `assert` the first time, and `assertEqual` the second? The actual unit test is the assertEqual. That allows the unittest module to track errors, etc. But the first test, `assert storage == []`, is not testing the do_twice function. It is testing the internal logic of the test_dotwice code: it acts as a checked comment to the reader: storage must be an empty list, not just any old list, if it isn't, it will fail. As such, if it fails, it is inappropriate to count it as an failure of do_twice. It should count as an error in the test itself. Making it an assert makes that clear. -- Steve From alan.gauld at yahoo.co.uk Sun Oct 2 19:15:04 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 3 Oct 2016 00:15:04 +0100 Subject: [Tutor] How to test a function which runs a passed in function twice? In-Reply-To: References: Message-ID: On 02/10/16 23:47, boB Stepp wrote: > In exercise 3.2 of Downey's "Think Python 2" he has a function: > > def do_twice(f): > f() > f() > > As you know, I am trying to learn testing/TDD while doing these > exercises. How do I test such a *general* function? You are testing do_twice() not f. So you do not care at this point whether f() is correct, you are only interested in proving that do_twice() works. You can use a mocking framework or simply define an "empty" function that merely records it's being called. You could define the function to increment a global, for example, and then at the end of the test the global should be incremented by two. Of course the actual functions that you will pass in will have been unit tested too and, if they are stateful, you may wish to test what happens when they are called multiple times - does the state correctly reflect the number of calls. But that is a separate issue to testing this function. > I can see doing this, but since the function to be tested is so > general in nature, I do not see how I can feel confident that I am > adequately testing it. The function as written is trivial in its nature and therefore trivial to test. The concerns you have are, I suspect, more to do with integration testing than with unit testing. At that point you have indeed got a whole new can of worms to contend with. But unit testing should be done first. > I cannot even conceive of what might be edge > cases for this function. functions that under some cases raise exceptions, or even exit the program? Functions that request user input? functions that contain infinite loops. Functions that are stateful and are at their boundary states. etc... But these are all integration issues not unit test ones. Of course any real world function is likely to be less trivial - it may well have exception handlers for example and probably return some kind of value. Or make the calls conditional on some other parameter so that the function becomes do_zero_to_twice()... -- 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 From robertvstepp at gmail.com Sun Oct 2 19:45:14 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 2 Oct 2016 18:45:14 -0500 Subject: [Tutor] How to test a function which runs a passed in function twice? In-Reply-To: <20161002230001.GD22471@ando.pearwood.info> References: <20161002230001.GD22471@ando.pearwood.info> Message-ID: On Sun, Oct 2, 2016 at 6:00 PM, Steven D'Aprano wrote: > On Sun, Oct 02, 2016 at 05:47:51PM -0500, boB Stepp wrote: >> In exercise 3.2 of Downey's "Think Python 2" he has a function: >> >> def do_twice(f): >> f() >> f() >> >> As you know, I am trying to learn testing/TDD while doing these >> exercises. How do I test such a *general* function? Should I create >> a variety of arbitrary functions in my test file, call the do_twice >> function with each of these made up functions and see if I get the >> expected results? > > Probably not need to use a variety of functions. Just one is sufficient. Would you mind on elaborating on why one would be sufficient? I suppose I am overthinking this. It is just that I can imagine all kinds of gnarly, over-convoluted functions. Perhaps one of such theoretical monstrosities would break the function to be tested? But then again, it seems more like do_twice(f) is just exercising Python's well-tested function-calling facility, so I probably don't need to get over-excited about testing do_twice. Have I answered my own question yet? > > def test_dotwice(self): > storage = [] > def f(): > storage.append(1) > > assert storage == [] > do_twice(demo) > self.assertEqual(storage, [1, 1]) > > > Why do I use `assert` the first time, and `assertEqual` the second? > > The actual unit test is the assertEqual. That allows the unittest module > to track errors, etc. > > But the first test, `assert storage == []`, is not testing the do_twice > function. It is testing the internal logic of the test_dotwice code: it > acts as a checked comment to the reader: storage must be an empty list, > not just any old list, if it isn't, it will fail. As such, if it > fails, it is inappropriate to count it as an failure of do_twice. It > should count as an error in the test itself. Making it an assert makes > that clear. This brings to mind something else that I had meant to ask about. I watched a video of Ned Batchelder giving a talk on unit testing last week. In passing, at one point, he mentioned that one might need to test one's test code. And you are providing a little test of your example test code. When should one test test code? When it stops being *obviously* straightforward? After all, testing test code can get recursively ridiculous! -- boB From alan.gauld at yahoo.co.uk Sun Oct 2 20:00:42 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 3 Oct 2016 01:00:42 +0100 Subject: [Tutor] How to test a function which runs a passed in function twice? In-Reply-To: References: Message-ID: On 02/10/16 23:47, boB Stepp wrote: > adequately testing it. I cannot even conceive of what might be edge > cases for this function. I meant to add, the obvious boundaries for this actual function are passing in non-callable values, or callables that require arguments. And to handle those you might want a try/except to catch TypeErrors... Although what would you do with them having caught them??? -- 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 From nirajkumarpandey at gmail.com Mon Oct 3 05:54:48 2016 From: nirajkumarpandey at gmail.com (niraj pandey) Date: Mon, 3 Oct 2016 15:24:48 +0530 Subject: [Tutor] Need help Message-ID: Hi , I am new in python. Could you guys please help me here. I want to add every lebels value here (ie fetch from DB and display in front of every lebel or I had store every lable value in variable and display here). [image: Inline image 1] So that table looks like as follow [image: Inline image 2] Is there any function which I can use for this (like we have entry.get to get the value similar any function to put the value) Thanks in advance. Regards Niraj -- Success occurs when opportunity and preparation meet From alan.gauld at yahoo.co.uk Mon Oct 3 11:23:46 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 3 Oct 2016 16:23:46 +0100 Subject: [Tutor] Need help In-Reply-To: References: Message-ID: On 03/10/16 10:54, niraj pandey wrote: > I want to add every lebels value here (ie fetch from DB and display in > front of every lebel or I had store every lable value in variable and > display here). You need to tell us which OS, Python version and GUI toolkit you are using. > [image: Inline image 1] This is a text list so images usually get stripped off. If absolutely necessary to send an image use a link to an image gallery somewhere. But at least try to explain what you are trying to show us. > Is there any function which I can use for this (like we have entry.get to > get the value similar any function to put the value) Assuming you are using Tkinter there is an insert() method. To put text at the end of the entry use import tkinter as tk myText = "Hello world" top = tk.Tk() myEntry = tk.Entry(top) myEntry.pack() myEntry.insert(tk.END,mytext) top.mainloop() However a common alternative is to use a StringVar and associate it with the Entry so that changes in the StringVar are automatically shown in the Entry and changes in the Entrey are reflected to the StringVar. Most Tkinter tutorials will show that under StringVar. Of course if you are not using Tkinter most of that will be useless! -- 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 From nirajkumarpandey at gmail.com Mon Oct 3 12:32:57 2016 From: nirajkumarpandey at gmail.com (niraj pandey) Date: Mon, 3 Oct 2016 22:02:57 +0530 Subject: [Tutor] Need help In-Reply-To: References: Message-ID: Hello Alan , I am using python 2.7.10 and using RHEL6 Thanks On Mon, Oct 3, 2016 at 8:53 PM, Alan Gauld via Tutor wrote: > On 03/10/16 10:54, niraj pandey wrote: > > > I want to add every lebels value here (ie fetch from DB and display in > > front of every lebel or I had store every lable value in variable and > > display here). > > You need to tell us which OS, Python version and GUI > toolkit you are using. > > > [image: Inline image 1] > > This is a text list so images usually get stripped off. > If absolutely necessary to send an image use a link to an > image gallery somewhere. > > But at least try to explain what you are trying to show us. > > > Is there any function which I can use for this (like we have entry.get to > > get the value similar any function to put the value) > > Assuming you are using Tkinter there is an insert() method. > To put text at the end of the entry use > > import tkinter as tk > myText = "Hello world" > top = tk.Tk() > > myEntry = tk.Entry(top) > myEntry.pack() > myEntry.insert(tk.END,mytext) > > top.mainloop() > > > However a common alternative is to use a StringVar and associate it with > the Entry so that changes in the StringVar are automatically > shown in the Entry and changes in the Entrey are reflected to the > StringVar. Most Tkinter tutorials will show that under StringVar. > > Of course if you are not using Tkinter most of that will be useless! > > > -- > 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 at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Success occurs when opportunity and preparation meet From crusier at gmail.com Tue Oct 4 01:35:55 2016 From: crusier at gmail.com (Crusier) Date: Tue, 4 Oct 2016 13:35:55 +0800 Subject: [Tutor] beautifulsoup Message-ID: I am trying to scrap from the (span class= 'Number'). The code looks like this on the pages I am scrapping:
I have tried to use Beautifulsoup to scrape the data. However, it returns Nothing on the screen from bs4 import BeautifulSoup html = response.content soup = BeautifulSoup(html,"html.parser") title = soup.select('td.styleB')[0].next_sibling title1 = soup.find_all('span', attrs={'class': 'Number'}).next_sibling print(title1) I am hoping that I could retrieve the number as follows: Max Quantity: 100 Average Quantity: 822 Previous Order: 96 Max Price: 104 Number of Trades:383 Min Price: 59 Total Amount:800 Start:10 Low: 98 Please advise what is the problem with my code from handling the query. Thank you From cs at zip.com.au Tue Oct 4 02:08:15 2016 From: cs at zip.com.au (cs at zip.com.au) Date: Tue, 4 Oct 2016 17:08:15 +1100 Subject: [Tutor] beautifulsoup In-Reply-To: References: Message-ID: <20161004060815.GA106@cskk.homeip.net> On 04Oct2016 13:35, Crusier wrote: >I am trying to scrap from the (span class= 'Number'). The code looks >like this on the pages I am scrapping: > >
>
99 10.00 (-0.1%) Menu Max Quantity
100.000
Average Quantity
822
Previous Order
96
Max Price
104
Number of Trades
383
Min Price
59
Total Amount
800
Start
10
Low
98
> > > > > > > > > > > > > > > > > > > > > > > >I have tried to use Beautifulsoup to scrape the data. However, it >returns Nothing on the screen > > from bs4 import BeautifulSoup > > html = response.content > soup = BeautifulSoup(html,"html.parser") > title = soup.select('td.styleB')[0].next_sibling > title1 = soup.find_all('span', attrs={'class': 'Number'}).next_sibling > print(title1) > >I am hoping that I could retrieve the number as follows: > >Max Quantity: 100 >Average Quantity: 822 >Previous Order: 96 >Max Price: 104 >Number of Trades:383 >Min Price: 59 >Total Amount:800 >Start:10 >Low: 98 > >Please advise what is the problem with my code from handling the >query. Thank you You perform several steps here before your print. Break them up. "soup.select", "[0]", "next_sibling" etc and print the intermediate values along the way. As a wide guess, might: title = soup.select('td.styleB')[0].next_sibling fetch this? I also suspect that next_sibling returns the next tags in the DOM tree. Not text. Your title1 might come out better as: title1 = str(soup.find_all('span', attrs={'class': 'Number'})[0]) if I recall how to grab the text inside a tag. Also, don't you want a loop around your find_all? Eg: for tag in soup.find_all('span', attrs={'class': 'Number'}): print(tag) print(str(tag)) # or tag.text() ? Anyway, put in more print()s in the middle of your traversal of the DOM. That should show where things are going wrong. Cheers, Cameron Simpson From nirajkumarpandey at gmail.com Tue Oct 4 02:35:26 2016 From: nirajkumarpandey at gmail.com (niraj pandey) Date: Tue, 4 Oct 2016 12:05:26 +0530 Subject: [Tutor] Need help In-Reply-To: References: Message-ID: Attaching two snapshots here. In first snapshot (1.png) I have the label windows without the values and in second window (2.png) every label have some value. I want to put these values in front of every label. I have already stored these values in a variable. Thanks Niraj On Mon, Oct 3, 2016 at 10:02 PM, niraj pandey wrote: > Hello Alan , > > I am using python 2.7.10 and using RHEL6 > > Thanks > > > On Mon, Oct 3, 2016 at 8:53 PM, Alan Gauld via Tutor > wrote: > >> On 03/10/16 10:54, niraj pandey wrote: >> >> > I want to add every lebels value here (ie fetch from DB and display in >> > front of every lebel or I had store every lable value in variable and >> > display here). >> >> You need to tell us which OS, Python version and GUI >> toolkit you are using. >> >> > [image: Inline image 1] >> >> This is a text list so images usually get stripped off. >> If absolutely necessary to send an image use a link to an >> image gallery somewhere. >> >> But at least try to explain what you are trying to show us. >> >> > Is there any function which I can use for this (like we have entry.get >> to >> > get the value similar any function to put the value) >> >> Assuming you are using Tkinter there is an insert() method. >> To put text at the end of the entry use >> >> import tkinter as tk >> myText = "Hello world" >> top = tk.Tk() >> >> myEntry = tk.Entry(top) >> myEntry.pack() >> myEntry.insert(tk.END,mytext) >> >> top.mainloop() >> >> >> However a common alternative is to use a StringVar and associate it with >> the Entry so that changes in the StringVar are automatically >> shown in the Entry and changes in the Entrey are reflected to the >> StringVar. Most Tkinter tutorials will show that under StringVar. >> >> Of course if you are not using Tkinter most of that will be useless! >> >> >> -- >> 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 at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Success occurs when opportunity and preparation meet > -- Success occurs when opportunity and preparation meet From nirajkumarpandey at gmail.com Tue Oct 4 02:51:08 2016 From: nirajkumarpandey at gmail.com (niraj pandey) Date: Tue, 4 Oct 2016 12:21:08 +0530 Subject: [Tutor] Need help In-Reply-To: References: Message-ID: Ok I got it from the solution you provided on your previous mail. Thanks again Thanks Niraj On Tue, Oct 4, 2016 at 12:05 PM, niraj pandey wrote: > Attaching two snapshots here. > > In first snapshot (1.png) I have the label windows without the values and > in second window (2.png) every label have some value. > I want to put these values in front of every label. I have already stored > these values in a variable. > > Thanks > Niraj > > On Mon, Oct 3, 2016 at 10:02 PM, niraj pandey > wrote: > >> Hello Alan , >> >> I am using python 2.7.10 and using RHEL6 >> >> Thanks >> >> >> On Mon, Oct 3, 2016 at 8:53 PM, Alan Gauld via Tutor >> wrote: >> >>> On 03/10/16 10:54, niraj pandey wrote: >>> >>> > I want to add every lebels value here (ie fetch from DB and display in >>> > front of every lebel or I had store every lable value in variable and >>> > display here). >>> >>> You need to tell us which OS, Python version and GUI >>> toolkit you are using. >>> >>> > [image: Inline image 1] >>> >>> This is a text list so images usually get stripped off. >>> If absolutely necessary to send an image use a link to an >>> image gallery somewhere. >>> >>> But at least try to explain what you are trying to show us. >>> >>> > Is there any function which I can use for this (like we have entry.get >>> to >>> > get the value similar any function to put the value) >>> >>> Assuming you are using Tkinter there is an insert() method. >>> To put text at the end of the entry use >>> >>> import tkinter as tk >>> myText = "Hello world" >>> top = tk.Tk() >>> >>> myEntry = tk.Entry(top) >>> myEntry.pack() >>> myEntry.insert(tk.END,mytext) >>> >>> top.mainloop() >>> >>> >>> However a common alternative is to use a StringVar and associate it with >>> the Entry so that changes in the StringVar are automatically >>> shown in the Entry and changes in the Entrey are reflected to the >>> StringVar. Most Tkinter tutorials will show that under StringVar. >>> >>> Of course if you are not using Tkinter most of that will be useless! >>> >>> >>> -- >>> 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 at python.org >>> To unsubscribe or change subscription options: >>> https://mail.python.org/mailman/listinfo/tutor >>> >> >> >> >> -- >> Success occurs when opportunity and preparation meet >> > > > > -- > Success occurs when opportunity and preparation meet > -- Success occurs when opportunity and preparation meet From badouglas at gmail.com Tue Oct 4 10:02:37 2016 From: badouglas at gmail.com (bruce) Date: Tue, 4 Oct 2016 10:02:37 -0400 Subject: [Tutor] xpath - html entities issue -- & Message-ID: Hi. Just realized I might have a prob with testing a crawl. I get a page of data via a basic curl. The returned data is html/charset-utf-8. I did a quick replace ('&','&') and it replaced the '&' as desired. So the content only had '&' in it.. I then did a parseString/xpath to extract what I wanted, and realized I have '&' as representative of the '&' in the returned xpath content. My issue, is there a way/method/etc, to only return the actual char, not the html entiy (&) I can provide a more comprehensive chunk of code, but minimized the post to get to the heart of the issue. Also, I'd prefer not to use a sep parse lib. ------------------------------------ code chunk import libxml2dom q1=libxml2dom s2= q1.parseString(a.toString().strip(), html=1) tt=s2.xpath(tpath) tt=tt[0].toString().strip() print "tit "+tt ------------------------------------- the content of a.toString() (shortened) . . .

Organization Development & Change Edition: 10th

. . . the xpath results are

Organization Development & Change Edition: 10th

As you can see.. in the results of the xpath (toString()) the & --> & I'm wondering if there's a process that can be used within the toString() or do you really have to wrap each xpath/toString with a unescape() kind of process to convert htmlentities to the requisite chars. Thanks From agnieszka.socha29 at gmail.com Tue Oct 4 13:41:27 2016 From: agnieszka.socha29 at gmail.com (Agnieszka Socha) Date: Tue, 4 Oct 2016 19:41:27 +0200 Subject: [Tutor] Error Message-ID: I began to learn Python and after saving a file gra.py tried to reopen it and got an error (in the Annex). Agnieszka Socha From random832 at fastmail.com Tue Oct 4 10:41:21 2016 From: random832 at fastmail.com (Random832) Date: Tue, 04 Oct 2016 10:41:21 -0400 Subject: [Tutor] xpath - html entities issue -- & In-Reply-To: References: Message-ID: <1475592081.3177401.745492385.40D3B6EB@webmail.messagingengine.com> On Tue, Oct 4, 2016, at 10:02, bruce wrote: > import libxml2dom > > q1=libxml2dom > > s2= q1.parseString(a.toString().strip(), html=1) > tt=s2.xpath(tpath) > > tt=tt[0].toString().strip() > print "tit "+tt > > ------------------------------------- > > > the content of a.toString() (shortened) What type is a? What is tpath? Please post a complete self-contained example that actually runs and shows your problem. > I'm wondering if there's a process that can be used within the > toString() or do you really have to wrap each xpath/toString with > a unescape() kind of process to convert htmlentities to the > requisite chars. Why are you using toString? I can't tell if you want a text string or HTML - if you want HTML then you should be fine with the & - if you want text, then shouldn't the be a bigger problem than the entity? From rkoeman at smcdsb.on.ca Tue Oct 4 10:04:51 2016 From: rkoeman at smcdsb.on.ca (Richard Koeman) Date: Tue, 4 Oct 2016 10:04:51 -0400 Subject: [Tutor] please help me modify this code so that I can utilize raw_input Message-ID: I would like to modify this code so that instead of me calling the function with the list as shown [1,2,3,4], the user inputs the list with raw_input. Thanks in advance """Define a function sum() and a function multiply() that sums and multiplies (respectively) all the numbers in a list of numbers. For example, sum([1, 2, 3, 4]) should return 10, and multiply([1, 2, 3, 4]) should return 24.""" def sum(mylist = [], *args): print mylist sum_of_number = 0 for i in mylist: sum_of_number += i print "The sum of the digits in your number is %s" %(sum_of_number) def multiply(mylist = [], *args): product_of_number = 1 for i in mylist: product_of_number = product_of_number * i print "The product of the digits in your number is %s" %(product_of_number) sum([1,2,3,4]) multiply([1,2,3,4]) -- This is a staff email account managed by Simcoe Muskoka Catholic District School Board. This email and any files transmitted with it are confidential and intended solely for the use of the individual or entity to whom they are addressed. If you have received this email in error please notify the sender. From alan.gauld at yahoo.co.uk Tue Oct 4 14:11:54 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 4 Oct 2016 19:11:54 +0100 Subject: [Tutor] please help me modify this code so that I can utilize raw_input In-Reply-To: References: Message-ID: On 04/10/16 15:04, Richard Koeman wrote: > I would like to modify this code so that instead of me calling the function > with the list as shown [1,2,3,4], the user inputs the list with raw_input. > You don't need to modify your code you just need ton write a function that reads a list from the user. Notice that this can e done by either repeatedly asking the user to input values until they are done or by reading a string containing the values and converting the string to a list of numbers. > """Define a function sum() and a function multiply() that sums and > multiplies (respectively) all the numbers in a list of numbers. For > example, sum([1, 2, 3, 4]) should return 10, and multiply([1, 2, 3, 4]) > should return 24.""" I do wish teachers would not ask students to reinvent the wheel. Python already has a perfectly good sum() function. And both problems become trivial if using functools.reduce() > > def sum(mylist = [], *args): > print mylist > sum_of_number = 0 > for i in mylist: > sum_of_number += i > print "The sum of the digits in your number is %s" %(sum_of_number) > def multiply(mylist = [], *args): > product_of_number = 1 > for i in mylist: > product_of_number = product_of_number * i > print "The product of the digits in your number is %s" > %(product_of_number) > > sum([1,2,3,4]) > multiply([1,2,3,4]) Incidentally, notice that the assignment asks you to *return* the results not print them. This is good practice, keep the printing separate from the calculation. You can then print the result, if you wish, with print( sum([....]) ) 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 From alan.gauld at yahoo.co.uk Tue Oct 4 14:18:26 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 4 Oct 2016 19:18:26 +0100 Subject: [Tutor] xpath - html entities issue -- & In-Reply-To: References: Message-ID: On 04/10/16 15:02, bruce wrote: > I did a quick replace ('&','&') and it replaced the '&' as desired. > So the content only had '&' in it.. You are preonbably better using your parseers escape/unescape facilities. Simple string replacement is notioriously hard to get right. > I can provide a more comprehensive chunk of code, but minimized the post to > get to the heart of the issue. Also, I'd prefer not to use a sep parse lib. Define separate? There are several options in the standard library. All will be more effective than trying to do it by hand. And libxml2dom is not one of them (at least I've never seen it before) so you appear to be breaking your own rules? > ------------------------------------ > code chunk > > import libxml2dom > q1=libxml2dom You can get the same effect with import libxml2dom as ql > s2= q1.parseString(a.toString().strip(), html=1) > tt=s2.xpath(tpath) > > tt=tt[0].toString().strip() > print "tit "+tt > > ------------------------------------- You may have over-simplified a tad, it has become fairly meaningless to us - what are 'a' and 'tpath'? -- 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 From alan.gauld at yahoo.co.uk Tue Oct 4 14:21:05 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 4 Oct 2016 19:21:05 +0100 Subject: [Tutor] Error In-Reply-To: References: Message-ID: On 04/10/16 18:41, Agnieszka Socha wrote: > I began to learn Python and after saving a file gra.py tried to reopen it > and got an error (in the Annex). This is a text only list so attachments tend to get stripped off. We need a lot more information I'm afraid. What are you using to "reopen" the file? Are you using a text editor or an IDE (like IDLE or eclipse?). Show us the full error text and your code - just paste it into the mail message. It also might help to tell us the Python version and the OS. -- 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 From Pierre.PERRAS at technidata-web.com Tue Oct 4 15:14:05 2016 From: Pierre.PERRAS at technidata-web.com (PERRAS Pierre) Date: Tue, 4 Oct 2016 19:14:05 +0000 Subject: [Tutor] remove ^ in field Message-ID: <0F6B08047391894EBE7FAECEE5B15C01016B1DC71D@TDMAILBOX1.technidata.net> Hi, Sending lab result in HL7. In the following example, I want everything (^^^^PATNUMBER~000925015-001) after 000925015 in PID3-1. I want also to remove everything (^^^^^^L) after PID5-2. [cid:image002.jpg at 01D21E51.F1A0B0B0] Regards, Pierre Perras From rus.cahimb at gmail.com Tue Oct 4 13:59:46 2016 From: rus.cahimb at gmail.com (Ramanathan Muthaiah) Date: Tue, 04 Oct 2016 17:59:46 +0000 Subject: [Tutor] Error In-Reply-To: References: Message-ID: > > I began to learn Python and after saving a file gra.py tried to reopen it > and got an error (in the Annex). > > What's the error on re-opening the file ? Also, share what version of Python, OS and editor you are using. FYI, this is a text only list, images of attachments will be filtered. /Ram From alan.gauld at yahoo.co.uk Wed Oct 5 04:44:41 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 5 Oct 2016 09:44:41 +0100 Subject: [Tutor] remove ^ in field In-Reply-To: <0F6B08047391894EBE7FAECEE5B15C01016B1DC71D@TDMAILBOX1.technidata.net> References: <0F6B08047391894EBE7FAECEE5B15C01016B1DC71D@TDMAILBOX1.technidata.net> Message-ID: On 04/10/16 20:14, PERRAS Pierre wrote: > Hi, > > Sending lab result in HL7. You need to give us much more information. Do not assume we know what HL7 is, I certainly don't. Also this is a text list and attachments are usually stripped off, so if you sent something it didn't get through. > In the following example, I want everything (^^^^PATNUMBER~000925015-001) I assume the bit in parens is the "example"? > after 000925015 in PID3-1. But I have no idea what PID3-1 means Also is the 000925015 a fixed value or is there a more general pattern involved? If its fixed then extracting your data is easy but if its a pattern then we might need to use a regex. Also what version of Python are you using? And which OS? But you need to explain more clearly what you are trying to do, what the input and output data looks like and how you are approaching it, plus any errors you get. -- 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 From rakeshsharma14 at hotmail.com Wed Oct 5 05:03:41 2016 From: rakeshsharma14 at hotmail.com (rakesh sharma) Date: Wed, 5 Oct 2016 09:03:41 +0000 Subject: [Tutor] Help regarding reg exp. Message-ID: Hi all I have a string of pattern ({A,BC},{(A,B),(B,C)(C,A)}. I want to extract the inner brackets {A,B,C} etc. Please help. I have tried various methods of re to no avail. Get Outlook for Android From alan.gauld at yahoo.co.uk Wed Oct 5 06:14:40 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 5 Oct 2016 11:14:40 +0100 Subject: [Tutor] Help regarding reg exp. In-Reply-To: References: Message-ID: On 05/10/16 10:03, rakesh sharma wrote: > Hi all > > I have a string of pattern ({A,BC},{(A,B),(B,C)(C,A)}. I'm not sure what you mean, can you send some real examples of the data rather than just a generic pattern? For example what do A,B and C signify? Are they literals? Are they uppercase letters? Constant tokens? Something else? > I want to extract the inner brackets {A,B,C} etc. You don't have a pattern like that in your string. Do you mean the first term {A,BC}? And should it really be {A,B,C}? > Please help. I have tried various methods of re to no avail. Until we understand the data better we can't be sure a regex is the best solution. -- 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 From oscar.j.benjamin at gmail.com Wed Oct 5 06:55:30 2016 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 5 Oct 2016 11:55:30 +0100 Subject: [Tutor] please help me modify this code so that I can utilize raw_input In-Reply-To: References: Message-ID: On 4 October 2016 at 19:11, Alan Gauld via Tutor wrote: >> """Define a function sum() and a function multiply() that sums and >> multiplies (respectively) all the numbers in a list of numbers. For >> example, sum([1, 2, 3, 4]) should return 10, and multiply([1, 2, 3, 4]) >> should return 24.""" > > > I do wish teachers would not ask students to reinvent the wheel. You may be misunderstanding the teacher's objectives here. Sometimes Python is used to introduce the concept of programming more generally rather than specifically to prepare someone for professional programming using Python. I don't know about you but I came to Python after a number of other programming languages. Now that I teach programming I can see that it's important in a first programming introduction to cover nuts and bolts type algorithmic thinking. sum() is a good example of an algorithm that most people are already used to performing on pen and paper making it a good candidate for learning to use loops and functions. > Python already has a perfectly good sum() function. Writing your own sum function helps to understand what actually happens when using the standard sum function. I do the same thing with my students in C teaching them how to make their own e.g. strlen function. I will tell them that strlen exists afterwards but I want them to understand what the null byte is and writing your own (or just looking at a) strlen implementation helps with that. Likewise simply using a function e.g. strcat without understanding its implementation can lead to segfaults so there can be a relevance in understanding the implementation even if you don't intend to reimplement something in your own code. The implications of the implementation of sum are also non-trivial which is why the stdlib contains at least 3 different sum functions. It's great that Python comes with so many functions to do common tasks. However from personal experience teaching Python as a first language can lead to the disadvantage that many students become spoilt programmers. They will learn to assume that there is a function for exactly what they want and all they ever need to do is ask a precise question in a search engine and read the first stackoverflow page. That may be the correct approach for many problems but it isn't always. A programmer should have the ability to implement basic algorithms (e.g. sum) for themselves when necessary. > And both problems become trivial if using functools.reduce() > Different people think in different ways but I reckon most people - and especially most beginners - would find a loop more straightforward than reduce. I doubt that the OP is at a stage where using reduce seems trivial. -- Oscar From dyoo at hashcollision.org Wed Oct 5 12:26:45 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 5 Oct 2016 09:26:45 -0700 Subject: [Tutor] Help regarding reg exp. In-Reply-To: References: Message-ID: > On 05/10/16 10:03, rakesh sharma wrote: >> Hi all >> >> I have a string of pattern ({A,BC},{(A,B),(B,C)(C,A)}. > On Wed, Oct 5, 2016 at 3:14 AM, Alan Gauld via Tutor wrote: > Until we understand the data better we can't be sure > a regex is the best solution. Yes, I agree with Alan: we need to know more about the problem. You've given one example. Do you have a few more examples to give? Why is your input a string, and not a structured object? Where does this input come from? Generalizing a solution from an example set of size one is trivially easy. It doesn't need regexes or anything: it just needs a simple string comparison: ########################################### def solution(input): if input == "({A,BC},{(A,B),(B,C)(C,A)}": return "{A,B,C}" ########################################### You might think that I'm joking. This is a "ha, ha, just serious" sort of thing. In fact, this is exactly the first implementation I would write if I were writing in test-driven-development mode. It forces me to write good test cases that actually exercise the solution and to make sure I don't cheat like this. From 12306 at smcdsb.on.ca Thu Oct 6 10:15:02 2016 From: 12306 at smcdsb.on.ca (Zeel Solanki) Date: Thu, 6 Oct 2016 10:15:02 -0400 Subject: [Tutor] Python Word Problems(Student) Message-ID: Hello, I am a grade 11 high school student and I am having a hard time solving the problem below. I have been stuck on it for days and I would like some guidance from you. The Problem: Write a function filter_long_words() that takes a list of words and an integer n and returns the list of words that are longer than n. What I have written: def filter_long_words(words, n): for x in words.split(): return filter(lambda x: len(x) > n, words) print filter_long_words(raw_input("Enter a list of words with spaces in between."), raw_input("Enter a number.")) My problem: Every time i input a list and then the number, it print an empty list. However , if i replace the raw_inputs with any given list and a number in the editor, it works and gives me the list of words that are longer than the number. Please and thank you for your help. -- This is a student email account managed by Simcoe Muskoka Catholic District School Board. The contents of this email are governed by the laws of the state and the board policies of the school district. From bgailer at gmail.com Thu Oct 6 12:21:40 2016 From: bgailer at gmail.com (bob gailer) Date: Thu, 6 Oct 2016 12:21:40 -0400 Subject: [Tutor] Python Word Problems(Student) In-Reply-To: References: Message-ID: <4a80ae3b-a187-debc-a873-a284ac8a7e29@gmail.com> On 10/6/2016 10:15 AM, Zeel Solanki wrote: > def filter_long_words(words, n): > for x in words.split(): > return filter(lambda x: len(x) > n, words) > > print filter_long_words(raw_input("Enter a list of words with spaces in > between."), raw_input("Enter a number.")) raw_input() always returns a string. When you enter a number (say, 5) it will be a string ("5"). use int() to convert that string to numeric. From bgailer at gmail.com Thu Oct 6 12:43:43 2016 From: bgailer at gmail.com (bob gailer) Date: Thu, 6 Oct 2016 12:43:43 -0400 Subject: [Tutor] Python Word Problems(Student) MORE ISSUES In-Reply-To: References: Message-ID: On 10/6/2016 10:15 AM, Zeel Solanki wrote: > def filter_long_words(words, n): > for x in words.split(): > return filter(lambda x: len(x) > n, words) > > print filter_long_words(raw_input("Enter a list of words with spaces in > between."), raw_input("Enter a number.")) raw_input() always returns a string. When you enter a number (say, 5) it will be a string ("5"). use int() to convert that string to numeric. But there are more issues. The function logic is misleading: you can remove the line beginning with "for". the loop will get the first word, appply filter (ignoring the word), then the function will stop. "However , if i replace the raw_inputs with any given list and a number in the editor" Exactly what do you enter for a list? Remember that anything you enter in the editor for words and n must be a string. Your function will give incorrect results. From alan.gauld at yahoo.co.uk Thu Oct 6 12:50:35 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 6 Oct 2016 17:50:35 +0100 Subject: [Tutor] Python Word Problems(Student) In-Reply-To: References: Message-ID: On 06/10/16 15:15, Zeel Solanki wrote: > def filter_long_words(words, n): > for x in words.split(): > return filter(lambda x: len(x) > n, words) You are trying to be too clever here, you don't need the loop. words is the original string so your filter will only receive the full string each time. But you can remove the loop and just use: return filter(lambda x: len(x) > n, words.split()) Bob has already addressed your problem of reading n from raw_input(). BTW Nowadays this would more commonly be done using a list comprehension rather than reduce. I don't know if you have covered comprehensions yet? -- 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 From alan.gauld at yahoo.co.uk Thu Oct 6 13:39:12 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 6 Oct 2016 18:39:12 +0100 Subject: [Tutor] Python Word Problems(Student) In-Reply-To: References: Message-ID: On 06/10/16 17:50, Alan Gauld via Tutor wrote: > Nowadays this would more commonly be done using a list > comprehension rather than reduce. Sorry, I meant filter() not reduce(). -- 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 From 12306 at smcdsb.on.ca Thu Oct 6 18:16:43 2016 From: 12306 at smcdsb.on.ca (Zeel Solanki) Date: Thu, 6 Oct 2016 17:16:43 -0500 Subject: [Tutor] (no subject) Message-ID: HelloI just started using python and my teacher has given us some problem to solve and I am having some problem soving the question below. I have written some part of the code already, so can u please correct the code for me to make it work. Please and thank you. Question: Write a function filter_long_words() that takes a list of words and an integer n and returns the list of words that are longer than n. My code(not working- printing blank) def filter_long_words(words, n): W = words.split(" ") for x in W: return filter(lambda x: len(x) > n, words) print filter_long_words(raw_input("Enter a list of words with spaces in between."), raw_input("Enter a number.")) Please correct my code, please and thanks. -- This is a student email account managed by Simcoe Muskoka Catholic District School Board. The contents of this email are governed by the laws of the state and the board policies of the school district. From alan.gauld at yahoo.co.uk Thu Oct 6 20:10:44 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 7 Oct 2016 01:10:44 +0100 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On 06/10/16 23:16, Zeel Solanki wrote: > HelloI just started using python and my teacher has given us some problem > to solve and I am having some problem soving the question below. I have > written some part of the code already, so can u please correct the code for > me to make it work. Please and thank you. We don;t do your homework for you but we can offer suggestions and hints. Please refer to the thread posted earlier today, entitled "Python Word Problems(Student)", which appears to be from one of your fellow students. You can find the list archive on the Python web site or on gmane.org. > Please correct my code, please and thanks. Please note how he(or she?) wrote his post, his style is much more likely to get a response than yours. He provides much more information and is not looking for us to do his work for him. That's much more likely to get a useful response. -- 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 From alan.gauld at yahoo.co.uk Thu Oct 6 20:13:18 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 7 Oct 2016 01:13:18 +0100 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On 06/10/16 23:16, Zeel Solanki wrote: > HelloI just started using python and my teacher has given us some problem I just noticed that you are the same person who posted earlier. The replies you have already received should answer your questions. Please don't start a second thread with the same subject it just messes up the archives. And remember that this is a mailing list so it can take several hours(up to 24) for a post to reach the membership and for them to respond. -- 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 From rubenbog at yahoo.com Fri Oct 7 18:20:53 2016 From: rubenbog at yahoo.com (Anibal Fornari) Date: RANDOM_Sat, 8 Oct 2016 01:20:53 +0300 Subject: [Tutor] hard facts Message-ID: <0000a4d828cd$0185f878$79170440$@yahoo.com> Hi! I've read an interesting report lately which is based on hard facts, you may like it I guess, read it here Best Wishes, Anibal Fornari From robertvstepp at gmail.com Fri Oct 7 21:26:28 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Fri, 7 Oct 2016 20:26:28 -0500 Subject: [Tutor] TDD: How to test input()? Message-ID: I think I have this figured out, but I want to be certain I am doing it both correctly and in the preferred way. I have a need for a get_input() function and have written my first test for this function as follows: class TestGetInput(unittest.TestCase): '''Tests for the function get_input().''' def setUp(self): '''Establish conditions for running these tests.''' # Redirect sys.stdin in order to test input functions. self.old_stdin = sys.stdin sys.stdin = StringIO('5') def test_get_input(self): '''Test that get_input() returns the expected result.''' expected = 5 draw2x2grid.get_input() self.assertEqual(sys.stdin.getvalue(), expected) def tearDown(self): '''Clear temporary testing variables.''' # Return sys.stdin to its normal state. sys.stdin = self.old_stdin When I run my tests I get the promising: c:\thinkpython2\ch3\ex_3-3>py -m unittest F... ====================================================================== FAIL: test_get_input (test_draw2x2grid.TestGetInput) Test that get_input() returns the expected result. ---------------------------------------------------------------------- Traceback (most recent call last): File "c:\thinkpython2\ch3\ex_3-3\test_draw2x2grid.py", line 119, in test_get_input self.assertEqual(sys.stdin.getvalue(), expected) AssertionError: '5' != 5 ---------------------------------------------------------------------- Ran 4 tests in 0.000s FAILED (failures=1) Currently the get_input() function is: def get_input(): '''Get string input from the user and convert it to an integer. This integer is returned to the caller. :num_sides: Number of sides for the displayed grid.''' pass I was bored with the actual exercise 3.3 in the text which is just to print an ASCII 2x2 grid and then a 3x3 grid, so I am using the TDD process to created a generalized grid printing program. So please excuse the file names "test_draw2x2grid.py" and "draw2x2grid.py". Let me know if there is a better way to test input() (The heart of get_input()), or if I have outright misconceptions, etc. TIA! -- boB From robertvstepp at gmail.com Fri Oct 7 21:44:17 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Fri, 7 Oct 2016 20:44:17 -0500 Subject: [Tutor] TDD: How to test input()? In-Reply-To: References: Message-ID: Oops! On Fri, Oct 7, 2016 at 8:26 PM, boB Stepp wrote: > I think I have this figured out, but I want to be certain I am doing > it both correctly and in the preferred way. I have a need for a > get_input() function and have written my first test for this function > as follows: > > class TestGetInput(unittest.TestCase): > '''Tests for the function get_input().''' > > def setUp(self): > '''Establish conditions for running these tests.''' > > # Redirect sys.stdin in order to test input functions. > self.old_stdin = sys.stdin > sys.stdin = StringIO('5') > > def test_get_input(self): > '''Test that get_input() returns the expected result.''' > > expected = 5 > draw2x2grid.get_input() > self.assertEqual(sys.stdin.getvalue(), expected) My brain was scrambled. The test_get_input(self) should instead be: def test_get_input(self): '''Test that get_input() returns the expected result.''' expected = 5 self.assertEqual(draw2x2grid.get_input(), expected) boB From robertvstepp at gmail.com Fri Oct 7 23:16:59 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Fri, 7 Oct 2016 22:16:59 -0500 Subject: [Tutor] Do not understand why I am getting "EOFError: EOF when reading a line". Message-ID: My current get_input() function: ====================================================== def get_input(): '''Get string input from the user and convert it to an integer. This integer is returned to the caller. :num_sides: Number of sides for the displayed grid.''' while True: try: num_sides = int(input("Number of sides = ")) return num_sides except ValueError: print("'Number of sides' must be a positive integer. Please enter " "an integer.") ======================================================= My current TestGetInput class: ======================================================= class TestGetInput(unittest.TestCase): '''Tests for the function get_input().''' def setUp(self): '''Establish conditions for running these tests.''' # Redirect sys.stdin in order to test input functions. self.old_stdin = sys.stdin sys.stdin = StringIO('5') def test_get_input(self): '''Test that get_input() returns the expected result.''' expected = 5 self.assertEqual(draw2x2grid.get_input(), expected) def test_get_input_value_error(self): '''Test that get_input() raises a ValueError if improper input entered.''' sys.stdin = StringIO('a') with self.assertRaises(ValueError): draw2x2grid.get_input() def tearDown(self): '''Clear temporary testing variables.''' # Return sys.stdin to its normal state. sys.stdin = self.old_stdin ========================================================= When I run the tests I get: ========================================================== c:\thinkpython2\ch3\ex_3-3>py -m unittest Number of sides = .Number of sides = 'Number of sides' must be a positive integer. Please enter an integer. Number of sides = E... ====================================================================== ERROR: test_get_input_value_error (test_draw2x2grid.TestGetInput) Test that get_input() raises a ValueError if improper input ---------------------------------------------------------------------- Traceback (most recent call last): File "c:\thinkpython2\ch3\ex_3-3\test_draw2x2grid.py", line 126, in test_get_input_value_error draw2x2grid.get_input() File "c:\thinkpython2\ch3\ex_3-3\draw2x2grid.py", line 50, in get_input num_sides = int(input("Number of sides = ")) EOFError: EOF when reading a line ---------------------------------------------------------------------- Ran 5 tests in 0.004s FAILED (errors=1) ====================================================================== I do not understand what is causing the EOFError. If I change "sys.stdin = StringIO('a')" with "sys.stdin = StringIO('1')" I get what I expect: ====================================================================== c:\thinkpython2\ch3\ex_3-3>py -m unittest Number of sides = .Number of sides = F... ====================================================================== FAIL: test_get_input_value_error (test_draw2x2grid.TestGetInput) Test that get_input() raises a ValueError if improper input ---------------------------------------------------------------------- Traceback (most recent call last): File "c:\thinkpython2\ch3\ex_3-3\test_draw2x2grid.py", line 126, in test_get_input_value_error draw2x2grid.get_input() AssertionError: ValueError not raised ---------------------------------------------------------------------- Ran 5 tests in 0.003s FAILED (failures=1) ====================================================================== I am currently quite stumped. What is it I am not seeing? -- boB From robertvstepp at gmail.com Sat Oct 8 00:51:56 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Fri, 7 Oct 2016 23:51:56 -0500 Subject: [Tutor] Do not understand why I am getting "EOFError: EOF when reading a line". In-Reply-To: References: Message-ID: I think I now understand why I am getting this EOF exception. On Fri, Oct 7, 2016 at 10:16 PM, boB Stepp wrote: > My current get_input() function: > > ====================================================== > def get_input(): > '''Get string input from the user and convert it to an integer. This > integer is returned to the caller. > > :num_sides: Number of sides for the displayed grid.''' > > while True: > try: > num_sides = int(input("Number of sides = ")) > return num_sides > except ValueError: > print("'Number of sides' must be a positive integer. Please enter " > "an integer.") > ======================================================= Since the try/except is within a while loop, the input tries to read more input after the ValueError occurs. Of course, I don't have any more input strings stored in the StringIO buffer, so it sees this as an end of file condition. But now I do not see how to test get_input() to check for the ValueError. Any suggestions? boB From steve at pearwood.info Sat Oct 8 02:18:54 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 8 Oct 2016 17:18:54 +1100 Subject: [Tutor] TDD: How to test input()? In-Reply-To: References: Message-ID: <20161008061854.GK22471@ando.pearwood.info> On Fri, Oct 07, 2016 at 08:26:28PM -0500, boB Stepp wrote: > I think I have this figured out, but I want to be certain I am doing > it both correctly and in the preferred way. I have a need for a > get_input() function and have written my first test for this function > as follows: Testing code that depends on user input is always tricky. There are a few ways to deal with it: (1) Denial. Just don't test that part of your code at all. That's not ideal, but it may be "good enough" if any error in that code would be obvious enough. (2) Perform ad hoc non-automated tests that require user intavention. That's a bit better but still not great. (3) You can monkey-patch the input() function in your test: import mymodule # module being tested class MyTests(unittest.TestCase): def test_get_input(self): def myinput(prompt): return "5" mymodule.input = myinput try: result = mymodule.get_input("What number do you want?") self.assertEqual(result, 5) finally: del mymodule.input That's often a good solution for simple testing. (4) Python 3 unittest library now includes support for mocking: https://docs.python.org/3/library/unittest.mock.html which lets you replace parts of your code with fake code ("mocks") which are more easily tested, similar to the monkey-patch example in (3) above. For an example, look at the test suite for the "code" module: https://docs.python.org/3/library/code.html https://hg.python.org/cpython/file/3.5/Lib/test/test_code_module.py (5) Or you could manually monkey-patch sys.stdin as you do. I haven't studied your code in detail to comment on it yet. Time permitting, I shall do so later. -- Steve From alan.gauld at yahoo.co.uk Sat Oct 8 04:18:16 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 8 Oct 2016 09:18:16 +0100 Subject: [Tutor] TDD: How to test input()? In-Reply-To: <20161008061854.GK22471@ando.pearwood.info> References: <20161008061854.GK22471@ando.pearwood.info> Message-ID: On 08/10/16 07:18, Steven D'Aprano wrote: > Testing code that depends on user input is always tricky. There are a > few ways to deal with it: > > (5) Or you could manually monkey-patch sys.stdin as you do. A variation on this that I have used is to read the input from stdin as usual but redirect stdin when you run the code: python test_input.py < testdata.txt That way I can use multiple sets of test data and run the tests using the different data sets. The test suite is then exercised by a simple shell script that runs against each test file in turn. I find that easier and more flexible than using a StringIO buffer. You can catch EOF errors in your test rig or write the tests to read a finite set of data and create the data to match. -- 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 From jf_byrnes at comcast.net Sat Oct 8 18:29:45 2016 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Sat, 8 Oct 2016 17:29:45 -0500 Subject: [Tutor] Accessing Yahoo with Python? Message-ID: I realize that my question is not about the standard library. The only reason I am asking here is, if I remember correctly, a regular contributor, Danny Yoo, works at Yahoo. I am hoping he, or someone else here can help me understand what is happening. I am writing a program using the yahoo_finance module. Over the past week I have been testing and refining it. At first the only errors I was seeing were mine. Lately I have been a lot of these errors. Traceback (most recent call last): File "/usr/local/lib/python3.4/dist-packages/yahoo_finance/__init__.py", line 120, in _request _, results = response['query']['results'].popitem() KeyError: 'query' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/jfb/MyProgs/StockHistory/stock_history_oop.py", line 75, in Stocks().run() File "/home/jfb/MyProgs/StockHistory/stock_history_oop.py", line 38, in run self.get_stock_info() File "/home/jfb/MyProgs/StockHistory/stock_history_oop.py", line 53, in get_stock_info yahoo = Share(stk) File "/usr/local/lib/python3.4/dist-packages/yahoo_finance/__init__.py", line 178, in __init__ self.refresh() File "/usr/local/lib/python3.4/dist-packages/yahoo_finance/__init__.py", line 142, in refresh self.data_set = self._fetch() File "/usr/local/lib/python3.4/dist-packages/yahoo_finance/__init__.py", line 181, in _fetch data = super(Share, self)._fetch() File "/usr/local/lib/python3.4/dist-packages/yahoo_finance/__init__.py", line 134, in _fetch data = self._request(query) File "/usr/local/lib/python3.4/dist-packages/yahoo_finance/__init__.py", line 123, in _request raise YQLQueryError(response['error']['description']) yahoo_finance.YQLQueryError: Query failed with error: "'No definition found for Table yahoo.finance.quotes'". It has gotten to the point where if I run the program 10 times, 9 of them will return the above error before I get the data I want. The part of my program that retrieves the data from Yahoo has not changed in quite a while. Is it possible that I have exceeded a Yahoo limit on requests from one IP address? Test data I am using gets the historical info on 3 stocks over a 3 day period. Thanks, Jim From aclarke23 at toucansurf.com Sat Oct 8 15:43:39 2016 From: aclarke23 at toucansurf.com (Alan Clarke) Date: Sat, 8 Oct 2016 20:43:39 +0100 Subject: [Tutor] Python Shell Message-ID: Hi. I have just installed Python 2.7.12 ( i have windows xp). I created a program called HW.py that runs under a command prompt, but Python Shell gives the following error: Traceback (most recent call last): File "", line 1, in HW.py NameError: name 'HW' is not defined Can someone please tell me what I'm doing wrong? I have added the Python directory to the Path. Alan. From wprins at gmail.com Sat Oct 8 21:04:58 2016 From: wprins at gmail.com (Walter Prins) Date: Sun, 9 Oct 2016 02:04:58 +0100 Subject: [Tutor] Do not understand why I am getting "EOFError: EOF when reading a line". In-Reply-To: References: Message-ID: Hi On 8 October 2016 at 05:51, boB Stepp wrote: > I think I now understand why I am getting this EOF exception. > > On Fri, Oct 7, 2016 at 10:16 PM, boB Stepp wrote: >> My current get_input() function: >> >> ====================================================== >> def get_input(): >> '''Get string input from the user and convert it to an integer. This >> integer is returned to the caller. >> >> :num_sides: Number of sides for the displayed grid.''' >> >> while True: >> try: >> num_sides = int(input("Number of sides = ")) >> return num_sides >> except ValueError: >> print("'Number of sides' must be a positive integer. Please enter " >> "an integer.") >> ======================================================= > > Since the try/except is within a while loop, the input tries to read > more input after the ValueError occurs. Of course, I don't have any > more input strings stored in the StringIO buffer, so it sees this as > an end of file condition. > > But now I do not see how to test get_input() to check for the > ValueError. Any suggestions? Your test is written such that it checks/expect ValueError to be thrown from get_input(). However, you're in fact catching/trapping ValueError inside get_input() so it's never going to be seen by the test. You cannot have it both ways. Either your intention is that get_input() must raise ValueError as your test expects it (and therefore get_input() shouldn't be [responsible for] catching, printing and looping as it currently is), or it must not (and should keep trying until it successfully reads an int). If the latter is the case your test needs to change to reflect this reality (by e.g. perhaps altering what's in the StringIO() input for example, so that there is a valid in in the input in addition to the invalid 'a', to allow the loop to terminate. Then the test should simply check that get_input() successfully "ignores"/skips over the invalid input and retrieves that latter integer from the test "input stream" [e.g. what you put into the StringIO()] and not expect an exception to be raised.) Walter From lrglinda at gmail.com Sat Oct 8 20:50:53 2016 From: lrglinda at gmail.com (Linda Gray) Date: Sat, 8 Oct 2016 20:50:53 -0400 Subject: [Tutor] Decrypting a Password Message-ID: Hello, I am working on a homework assignment that has me creating a password saver using a ceasar cipher code. I was provided the key to the cipher and two passwords. I need to look up and decrypt the passwords and create a program to add a password and delete a password (options 2, 3 and 7). I had no problems adding a password. I am also having no problems looking up a password but am havving problems decrypting the password. I can only get it to provide me the give, encrypted password and not the unencrypted one which is the one I need to provide. I am not getting any errors, it is just not doing anything that I can see. I am getting the following error with the deleting a password. Traceback (most recent call last): File "C:/Users/lrgli/Desktop/Python Programs/Password test file.py", line 187, in passwords.remove (passwordToDelete) ValueError: list.remove(x): x not in list Any assistance, guidance, pointers would be appreciated. Is my indentation wrong for the decryption, am I missing something connecting the two, etc.? I feel like I am close. It is python version 3. Here is my code: import csv import sys #The password list - We start with it populated for testing purposes passwords = [["yahoo","XqffoZeo"],["google","CoIushujSetu"]] #The password file name to store the passwords to passwordFileName = "samplePasswordFile" #The encryption key for the caesar cypher encryptionKey=16 #Caesar Cypher Encryption def passwordEncrypt (unencryptedMessage, key): #We will start with an empty string as our encryptedMessage encryptedMessage = '' #For each symbol in the unencryptedMessage we will add an encrypted symbol into the encryptedMessage for symbol in unencryptedMessage: if symbol.isalpha(): num = ord(symbol) num += key if symbol.isupper(): if num > ord('Z'): num -= 26 elif num < ord('A'): num += 26 elif symbol.islower(): if num > ord('z'): num -= 26 elif num < ord('a'): num += 26 encryptedMessage += chr(num) else: encryptedMessage += symbol return encryptedMessage def loadPasswordFile(fileName): with open(fileName, newline='') as csvfile: passwordreader = csv.reader(csvfile) passwordList = list(passwordreader) return passwordList def savePasswordFile(passwordList, fileName): with open(fileName, 'w+', newline='') as csvfile: passwordwriter = csv.writer(csvfile) passwordwriter.writerows(passwordList) while True: print("What would you like to do:") print(" 1. Open password file") print(" 2. Lookup a password") print(" 3. Add a password") print(" 4. Save password file") print(" 5. Print the encrypted password list (for testing)") print(" 6. Quit program") print(" 7. Delete a password") print("Please enter a number (1-4 or 7)") choice = input() if(choice == '1'): #Load the password list from a file passwords = loadPasswordFile(passwordFileName) if(choice == '2'): #Lookup at password print("Which website do you want to lookup the password for?") for keyvalue in passwords: print(keyvalue[0]) passwordToLookup = input() for i in range(len(passwords)): # This loops through my list of passwords if passwordToLookup in passwords [i][0]: #this says what matches up the website you input with the website in the lists of passwords # print (passwords[i][1]) #this prints the encrypted password #The encryption key for the caesar cypher deencryptionKey=16 #Caesar Cypher Encryption def passwordunEncrypt (encryptedMessage, key): #We will start with an empty string as our encryptedMessage unencryptedMessage = '' #For each symbol in the unencryptedMessage we will add an encrypted symbol into the encryptedMessage for symbol in encryptedMessage: if symbol.isalpha(): num = ord(symbol) num -= key if symbol.isupper(): if num > ord('Z'): num -= 26 elif num < ord('A'): num += 26 elif symbol.islower(): if num > ord('z'): num -= 26 elif num < ord('a'): num += 26 unencryptedMessage += chr(num) else: unencryptedMessage += symbol return unencryptedMessage print(passwordunEncrypt(passwords[i][1], 16)) if(choice == '3'): print("What website is this password for?") website = input() print("What is the password?") unencryptedPassword = input() encryptedPassword = passwordEncrypt (unencryptedPassword,encryptionKey) # This encrypts the password you just entered newwebsitepassword = [website, encryptedPassword] # This creates my list of 2 items, website and password passwords.append(newwebsitepassword) #This adds this to the password list if(choice == '4'): #Save the passwords to a file savePasswordFile(passwords,passwordFileName) if(choice == '5'): #print out the password list for keyvalue in passwords: print(', '.join(keyvalue)) if(choice == '6'): #quit our program sys.exit() if (choice == '7'): #delete a password print ("What website password would you like to delete?") for keyvalue in passwords: print(keyvalue[0]) passwordToDelete = input() for i in range(len(passwords)): # This loops through my list of passwords if passwordToDelete in passwords [i][0]: #this says what matches up the website you input withthe website in the lists of passwords passwords.remove (passwordToDelete) print() print() From alan.gauld at yahoo.co.uk Sun Oct 9 04:08:42 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 9 Oct 2016 09:08:42 +0100 Subject: [Tutor] Python Shell In-Reply-To: References: Message-ID: On 08/10/16 20:43, Alan Clarke wrote: > I created a program called HW.py that runs under a command prompt, > but Python Shell gives the following error: How are you running it in the Python shell? > Traceback (most recent call last): > File "", line 1, in > HW.py > NameError: name 'HW' is not defined > > Can someone please tell me what I'm doing wrong? Since you don't tell us what you are doing, we cant tell you what about it is wrong. If you are are trying to execute HW.py from the >>> prompt by just typing its name then that's wrong. You need to import it as HW import HW # note not HW.py, just HW And if it has a sentinel section that runs a main() function then you need to replicate that code manually. But it's not normal to run programs from the Python shell like that. Most IDEs such as IDLE have a menu option to run the program and the output then appears in the shell window. But, even then, it should just be for testing, the best way to run the program is, as you apparently did, using the python interpreter directly from the OS. -- 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 From alan.gauld at yahoo.co.uk Sun Oct 9 04:29:07 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 9 Oct 2016 09:29:07 +0100 Subject: [Tutor] Decrypting a Password In-Reply-To: References: Message-ID: On 09/10/16 01:50, Linda Gray wrote: > I am working on a homework assignment that has me creating a password saver > using a ceasar cipher code. I was provided the key to the cipher and two > passwords. I need to look up and decrypt the passwords Are you sure? That's very bad practice and never needed in the real world. The normal way to handle passwords is to encrypt them and store the encryopted cersion. Then when the user enters a password you encrypt that and compare it to the stored encryption. If the two encrypted versions are the same then the original passwords were the same. So you should never need to see the plaintext version of a password, that would be a bad security hole. So are you sure you need to decrypt the password? Is that an explicit part of your assignment? > just not doing anything that I can see. I am getting the following error > with the deleting a password. > > Traceback (most recent call last): > File "C:/Users/lrgli/Desktop/Python Programs/Password test file.py", line > 187, in > passwords.remove (passwordToDelete) > ValueError: list.remove(x): x not in list > Here is my code: > > import csv > import sys > > #The password list - We start with it populated for testing purposes > passwords = [["yahoo","XqffoZeo"],["google","CoIushujSetu"]] > > > #The password file name to store the passwords to > passwordFileName = "samplePasswordFile" > > #The encryption key for the caesar cypher > encryptionKey=16 > > #Caesar Cypher Encryption > def passwordEncrypt (unencryptedMessage, key): > > #We will start with an empty string as our encryptedMessage > encryptedMessage = '' > > #For each symbol in the unencryptedMessage we will add an > encrypted symbol into the encryptedMessage > for symbol in unencryptedMessage: > if symbol.isalpha(): > num = ord(symbol) > num += key > > if symbol.isupper(): > if num > ord('Z'): > num -= 26 > elif num < ord('A'): > num += 26 > elif symbol.islower(): > if num > ord('z'): > num -= 26 > elif num < ord('a'): > num += 26 > > encryptedMessage += chr(num) > else: > encryptedMessage += symbol > > return encryptedMessage > > def loadPasswordFile(fileName): > > with open(fileName, newline='') as csvfile: > passwordreader = csv.reader(csvfile) > passwordList = list(passwordreader) > > return passwordList > > def savePasswordFile(passwordList, fileName): > > with open(fileName, 'w+', newline='') as csvfile: > passwordwriter = csv.writer(csvfile) > passwordwriter.writerows(passwordList) > > > > while True: > print("What would you like to do:") > print(" 1. Open password file") > print(" 2. Lookup a password") > print(" 3. Add a password") > print(" 4. Save password file") > print(" 5. Print the encrypted password list (for testing)") > print(" 6. Quit program") > print(" 7. Delete a password") > print("Please enter a number (1-4 or 7)") > choice = input() > > if(choice == '1'): #Load the password list from a file > passwords = loadPasswordFile(passwordFileName) > You dopn;t need parens areound the test in Python. if choice == '1': works just fine. > if(choice == '2'): #Lookup at password > print("Which website do you want to lookup the password for?") > for keyvalue in passwords: > print(keyvalue[0]) > passwordToLookup = input() > > for i in range(len(passwords)): # This loops through my list > of passwords Its usually better to loop over the list directly: for website,password in passwords: > if passwordToLookup in passwords [i][0]: #this says what > matches up the website you input with the website in the lists of > passwords > # print (passwords[i][1]) #this prints the encrypted password And this becomes if passwordToLookup == website: print password > > #The encryption key for the caesar cypher > deencryptionKey=16 > > #Caesar Cypher Encryption > def passwordunEncrypt (encryptedMessage, key): > > #We will start with an empty string as our > encryptedMessage > unencryptedMessage = '' > > #For each symbol in the unencryptedMessage we > will add an encrypted symbol into the encryptedMessage > for symbol in encryptedMessage: > if symbol.isalpha(): > num = ord(symbol) > num -= key > > if symbol.isupper(): > if num > ord('Z'): > num -= 26 > elif num < ord('A'): > num += 26 > elif symbol.islower(): > if num > ord('z'): > num -= 26 > elif num < ord('a'): > num += 26 > Put the algorithgm into a function for easier testing and readability. > unencryptedMessage += chr(num) > else: > unencryptedMessage += symbol > > return unencryptedMessage return should throw an error since its not inside a function? Looks like a cut n [aste error maybe? > print(passwordunEncrypt(passwords[i][1], 16)) > > > > > if(choice == '3'): > print("What website is this password for?") > website = input() > print("What is the password?") > unencryptedPassword = input() > > encryptedPassword = passwordEncrypt > (unencryptedPassword,encryptionKey) # This encrypts the password you > just entered > > newwebsitepassword = [website, encryptedPassword] # This > creates my list of 2 items, website and password > > passwords.append(newwebsitepassword) #This adds this to the > password list > > > if(choice == '4'): #Save the passwords to a file > savePasswordFile(passwords,passwordFileName) > > > if(choice == '5'): #print out the password list > for keyvalue in passwords: > print(', '.join(keyvalue)) > > if(choice == '6'): #quit our program > sys.exit() > > > if (choice == '7'): #delete a password > print ("What website password would you like to delete?") > > for keyvalue in passwords: > print(keyvalue[0]) > passwordToDelete = input() > > for i in range(len(passwords)): # This loops through my list > of passwords > if passwordToDelete in passwords [i][0]: #this says what > matches up the website you input withthe website in the lists of > passwords > passwords.remove (passwordToDelete) This doesn't work because passwordtodelete is the website entry, not the whole entry in passwords. You need to delete passwords[i] or, if you want to keep the web site and just delete the password element, then delete passwords[i][1] 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 From __peter__ at web.de Sun Oct 9 05:47:19 2016 From: __peter__ at web.de (Peter Otten) Date: Sun, 09 Oct 2016 11:47:19 +0200 Subject: [Tutor] Decrypting a Password References: Message-ID: Linda Gray wrote: > Hello, > > I am working on a homework assignment that has me creating a password > saver > using a ceasar cipher code. I was provided the key to the cipher and two > passwords. I need to look up and decrypt the passwords and create a > program to add a password and delete a password (options 2, 3 and 7). I > had no problems adding a password. I am also having no problems looking > up a password but am havving problems decrypting the password. The good news is that when you have a function that correctly encrypts a string using caesar's cipher you also have one that decrypts it -- because its the same function. Let's try: >>> def passwordEncrypt (unencryptedMessage, key): ... #We will start with an empty string as our encryptedMessage ... encryptedMessage = '' ... #For each symbol in the unencryptedMessage we will add an encrypted symbol into the encryptedMessage ... for symbol in unencryptedMessage: ... if symbol.isalpha(): ... num = ord(symbol) ... num += key ... if symbol.isupper(): ... if num > ord('Z'): ... num -= 26 ... elif num < ord('A'): ... num += 26 ... elif symbol.islower(): ... if num > ord('z'): ... num -= 26 ... elif num < ord('a'): ... num += 26 ... encryptedMessage += chr(num) ... else: ... encryptedMessage += symbol ... return encryptedMessage ... >>> encrypted = passwordEncrypt("Hello world!", 16) >>> encrypted 'Xubbe mehbt!' >>> passwordEncrypt(encrypted, -16) 'Hello world!' That's your function (without the empty lines to allow pasting into the interactive interpreter without syntax errors), and it seems to work. > I can only > get it to provide me the give, encrypted password and not the unencrypted > one The line > print(passwordunEncrypt(passwords[i][1], 16)) is incorrectly indented making it part of the passwordunEncrypt() function. Therefore it is never executed. It's generally a good idea to put functions at the beginning of a script and to define them on the module level rather than at some arbitrary point in a control structure (even experts hardly ever do that). > which is the one I need to provide. I am not getting any errors, it is > just not doing anything that I can see. I am getting the following error > with the deleting a password. > > Traceback (most recent call last): > File "C:/Users/lrgli/Desktop/Python Programs/Password test file.py", > line > 187, in > passwords.remove (passwordToDelete) > ValueError: list.remove(x): x not in list > > Any assistance, guidance, pointers would be appreciated. Is my > indentation wrong for the decryption, am I missing something connecting > the two, etc.? The list contains lists (the site/password pairs) and remove looks for the password alone. A small example: >>> items = [["foo", "bar"], ["ham", "spam"]] >>> items.remove("foo") Traceback (most recent call last): File "", line 1, in ValueError: list.remove(x): x not in list For the removal to succeed you need to provide the exact entry: >>> items.remove(["foo", "bar"]) >>> items [['ham', 'spam']] A workaround would be to loop over the items >>> items = [["foo", "bar"], ["ham", "spam"]] >>> for i, item in enumerate(items): ... if item[0] == "foo": ... del items[i] ... break # required! ... >>> items [['ham', 'spam']] but Python has an alternative that is better suited for the problem: the dictionary: >>> lookup = {"foo": "bar", "ham": "spam"} >>> del lookup["foo"] >>> lookup {'ham': 'spam'} > I feel like I am close. It is python version 3. > > Here is my code: From steve at pearwood.info Sun Oct 9 05:42:49 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 9 Oct 2016 20:42:49 +1100 Subject: [Tutor] Decrypting a Password In-Reply-To: References: Message-ID: <20161009094248.GO22471@ando.pearwood.info> On Sun, Oct 09, 2016 at 09:29:07AM +0100, Alan Gauld via Tutor wrote: > On 09/10/16 01:50, Linda Gray wrote: > > > I am working on a homework assignment that has me creating a password saver > > using a ceasar cipher code. I was provided the key to the cipher and two > > passwords. I need to look up and decrypt the passwords > > Are you sure? That's very bad practice and never needed > in the real world. You've never used a password vault then? The idea of a password vault is that you have one master password which controls access to a record of sites and their passwords. You need to record the *actual* password, since you have to enter the password itself (not a hash) into the site's password field. Rather than try to remember 50 passwords, or re-use passwords (a dangerous practice) you remember one good, memorable password, protect your password vault like it is the keys to your house, and then the password manager can choose very large, unique, impossible to memorise, random passwords for each site. > The normal way to handle passwords is to encrypt them > and store the encryopted cersion. For authentication, it *should* be an irreversible one-way hash. (Unfortunately, far too many places don't do that. They record the passwords in plain text, or using a hash without salting, so that the password is recoverable.) The exception being password managers or vaults, as I said, as they need access to the actual password. > Then when the user > enters a password you encrypt that and compare it to > the stored encryption. If the two encrypted versions > are the same then the original passwords were the same. That's for authentication. > So you should never need to see the plaintext > version of a password, that would be a bad > security hole. If you don't know the plaintext version of the password, how do you type it into the password field? :-) -- Steve From alan.gauld at yahoo.co.uk Sun Oct 9 07:26:44 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 9 Oct 2016 12:26:44 +0100 Subject: [Tutor] Decrypting a Password In-Reply-To: <20161009094248.GO22471@ando.pearwood.info> References: <20161009094248.GO22471@ando.pearwood.info> Message-ID: On 09/10/16 10:42, Steven D'Aprano wrote: >> Are you sure? That's very bad practice and never needed >> in the real world. > > You've never used a password vault then? That's true, I've never seen a secure one, so I never use them. Same with browsers doing auto-authentication, a terrible idea! But you are also correct that they are a scenario where unencryption becomes necessary - exactly why they are a bad idea! Actually I don't mind them so much if they are kept on a single personal device that is itself secured (and the passwords are encrypted, of course), but anywhere that the passwords are on a server and that server provides an API to unencrypt is inherently unsafe, even when using access keys. >> So you should never need to see the plaintext >> version of a password, that would be a bad >> security hole. > > If you don't know the plaintext version of the password, how do you type > it into the password field? :-) Smiley noted, but for clarity I meant "you" as in the recipient of the password not the originator. -- 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 From dyoo at hashcollision.org Sun Oct 9 15:23:42 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Sun, 9 Oct 2016 12:23:42 -0700 Subject: [Tutor] Accessing Yahoo with Python? In-Reply-To: References: Message-ID: On Sat, Oct 8, 2016 at 3:29 PM, Jim Byrnes wrote: > I realize that my question is not about the standard library. The only > reason I am asking here is, if I remember correctly, a regular contributor, > Danny Yoo, works at Yahoo. I am hoping he, or someone else here can help me > understand what is happening. Hi Jim, Thanks for remembering me! Unfortunately, I do not work at Yahoo. > I am writing a program using the yahoo_finance module. Over the past week I > have been testing and refining it. At first the only errors I was seeing > were mine. Lately I have been a lot of these errors. > > Traceback (most recent call last): > File "/usr/local/lib/python3.4/dist-packages/yahoo_finance/__init__.py", > line 120, in _request > _, results = response['query']['results'].popitem() > KeyError: 'query' Let me check... ah, it looks like this issue is known as a bug in the library: https://github.com/lukaszbanasiak/yahoo-finance/issues/48 https://github.com/lukaszbanasiak/yahoo-finance/issues/44 It looks like the developer of that third-party module knows there is a problem and trying to resolve it. You'll probably want to watch that bug for progress. Best of wishes to you! From dkwolfe at gmail.com Mon Oct 10 11:54:09 2016 From: dkwolfe at gmail.com (David Wolfe) Date: Mon, 10 Oct 2016 11:54:09 -0400 Subject: [Tutor] Python dependencies in Anaconda Message-ID: Good Morning; I'm working with a Python program that requires several dependencies (Numpy, Matplotlib, and so on). Normally I do all my programing through Anaconda (using Spyder or a Juypter notebook), so the dependencies are included, so it's not an issue. So, what I'm wondering is, are the dependencies that are included in Anaconda just contained in Anaconda, and not actually accessible in Python, unless you go through the Anaconda prompt to get to Python? Thanks, David From drtraceyjones at hotmail.com Tue Oct 11 05:16:21 2016 From: drtraceyjones at hotmail.com (tracey jones-Francis) Date: Tue, 11 Oct 2016 09:16:21 +0000 Subject: [Tutor] Advise with coding Message-ID: Hi I have just started Com Sci in Uni and I am new to coding. I feel pretty inadequate as I am really struggling with the latest tasks. Most of the work is self-directed learning so we need to figure it out ourselves but I am running out of time. Is it possible someone on here can advise me where I am going wrong. Many thanks in anticipation T From jeremygainey14 at gmail.com Sun Oct 9 16:39:42 2016 From: jeremygainey14 at gmail.com (jeremygainey14 at gmail.com) Date: Sun, 9 Oct 2016 16:39:42 -0400 Subject: [Tutor] Python Code Not Working Message-ID: <57faab0d.5d25ed0a.70628.6550@mx.google.com> Everytime I run this it says test is not defined . I don?t understand. Can someone please help correct? #Question 10 def reverse(mystr): reversed = '' for char in mystr: reversed = char + reversed return reversed def is_palindrome(myStr): if myStr in reverse(myStr): return True else: return False test(is_palindrome("abba")) test(not is_palindrome("abab")) test(is_palindrome("tenet")) test(not is_palindrome("banana")) test(is_palindrome("straw warts")) test(is_palindrome("a")) test(is_palindrome("")) -Jeremy Gainey From alan.gauld at yahoo.co.uk Tue Oct 11 16:11:35 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 11 Oct 2016 21:11:35 +0100 Subject: [Tutor] Python dependencies in Anaconda In-Reply-To: References: Message-ID: On 10/10/16 16:54, David Wolfe wrote: > Anaconda (using Spyder or a Juypter notebook), so the dependencies are > included, so it's not an issue. So, what I'm wondering is, are the > dependencies that are included in Anaconda just contained in Anaconda, and > not actually accessible in Python, Anaconda is one of several specialist distributions of Python that includes many modules not in the standard library, notably the math/science related ones. It is perfectly possible (although not entirely trivial) to install all of the required dependencies manually into a standard Python installation, but its tiresome and therefore most folks working in that area will use a distribution like Anaconda or Entropy. The individual packages are mostly available on PyPI or on the SciPy web site. They are also usually available on Linux via the standard package management tools (apt-get, yum etc) -- 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 From alan.gauld at yahoo.co.uk Tue Oct 11 16:32:38 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 11 Oct 2016 21:32:38 +0100 Subject: [Tutor] Advise with coding In-Reply-To: References: Message-ID: On 11/10/16 10:16, tracey jones-Francis wrote: > Is it possible someone on here can advise me where I am going wrong. Yesm, thats what this list is for but... We need to see code - we can't guess what you did. We need to know what input you used, what output you got and why its not what you expected. Also provide the full text of any error messages you get. Finally it ioften helpsa to know which OS and Python version you are using and, if applicable, what IDE you are using to write/run the code. If that seems a lot, it all helps to provide specific answers. The more specific your information is, the more specific our response can be,. -- 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 From alan.gauld at yahoo.co.uk Tue Oct 11 16:35:31 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 11 Oct 2016 21:35:31 +0100 Subject: [Tutor] Python Code Not Working In-Reply-To: <57faab0d.5d25ed0a.70628.6550@mx.google.com> References: <57faab0d.5d25ed0a.70628.6550@mx.google.com> Message-ID: On 09/10/16 21:39, jeremygainey14 at gmail.com wrote: > Everytime I run this it says test is not defined . I don?t understand. It means test is not defined - that is, Python doesn't know about it. You call a function test() but there is no such function built into Python, so it complains. Presumably the test function is defined in a module somewhere, in which case you need to import that function to make it visible to python. Can someone please help correct? > def is_palindrome(myStr): > if myStr in reverse(myStr): > return True > else: > return False > > test(is_palindrome("abba")) > test(not is_palindrome("abab")) > test(is_palindrome("tenet")) -- 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 From michael.armson at gmail.com Tue Oct 11 17:13:20 2016 From: michael.armson at gmail.com (Mike Armson) Date: Tue, 11 Oct 2016 17:13:20 -0400 Subject: [Tutor] Cluster analysis script error Message-ID: Hi there, I am trying to run a script (attached) which determines the number of clusters of fixations within a set of eye movement data. The script says to enter the following command on python: "python fixationClusters.py outputPrefix input clusterDistance" I am getting a syntax error with the output command after entering the following: "python /fixationClusters.py ETv2_cluster_output ETv2_cluster_input 50" The syntax error is indicated with an arrow under the last "t" in "output". I realize that "/fixationClusters.py" looks different from the "fixationClusters.py" in the instructions of the script but this part actually works. At least, it was giving me a syntax error for "fixationClusters.py" but not for "/fixationClusters.py". Also, the "ETv2_cluster" portion of the output command seems to be working, as there were originally errors here, but I fixed them. Thanks very much for your help! Mike -- *Mike Armson, PhD Candidate* University of Toronto, Department of Psychology Levine Lab, Rotman Research Institute, Baycrest *p:* (416) 785-2500 x.2826 *e: marmson at research.baycrest.org * -------------- next part -------------- #!/usr/bin/env python # # Script to find and report clusters of fixations # # Clusters are defined automatically using a simple Euclidean distance metric # All fixations that are within D pixel units of each other are considered to # be in the same cluster. # # Script Usage: ./fixationClusters.py outputPrefix input clusterDistance # or python fixationClusters.py outputPrefix input clusterDistance # # input must be a csv file with 4 columns: Trial#, x-loc, y-loc and duration. # a csv file with 5 columns: Subject#, Trial#, x-loc, y-loc and duration. # # The script returns a text file named outputPrefix.txt # # The output is similar to the input, but with an additional column labeling # clusters instead of fixation duratoins. Each cluster is given a unique label # # clusterDistance is the value (in pixel units) for which fixations are deemed # to be in the same cluster # # Mark Chiew # Aug 2012 # ################################################################################ # Imports (don't touch this stuff) ################################################################################ import numpy as np import sys ################################################################################ # Module Variables ################################################################################ # List of subject numbers subjects = [] # Screen boundaries xBound = 1024 yBound = 768 # Sort fixations (1), or keep original temporal ordering (0) sortFix = 1 # Use alphabetic (1), instead of numeric (0) cluster labels alphaLabels = 1 alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # Verbose controls whether extra output is printed to screen or not verbose = 1 ################################################################################ # Functions ################################################################################ def __detectColumns(inputFile): """Detects and returns the number of columns in the input file""" data = np.loadtxt(inputFile, skiprows=0, delimiter=',') return len(data[0]) def __readData(inputFile, cols): """Assumes the input file is 4 or 5-column numeric. If 5, first column is subject number, second column is trial number, third column is x-coord, fourth column is y-coord, and fifth column is fixation duration. If 4, omit subject number.""" data = np.loadtxt(inputFile, skiprows=0, delimiter=',') if cols == 5: subjects= tuple(set(map(int,data[:,0]))) data = [np.array(filter(lambda z:z[0]==i, data)) for i in subjects] data = [map(lambda z:z[1:], x) for x in data] elif cols == 4: subjects= (1,) data = [data] data = [[np.array(filter(lambda z:z[0]==i, x)) for i in np.arange(1,x[-1][0]+1)] for x in data] for i in range(len(data)): if len(data[i]) == 0: data[i] = np.array(['No Subject']) for j in range(len(data[i])): if len(data[i][j]) == 0: data[i][j] = np.array([[j+1,'NoTrial']]) for i in range(len(data)): data[i] = map(lambda z: z[:,1:], data[i]) return data def __checkOutofBoundsFixations(data): """Ignore fixations that occur outside of screen boundaries""" data = filter(lambda z: z[0] > 0, data) data = filter(lambda z: z[0] < xBound, data) data = filter(lambda z: z[1] > 0, data) data = filter(lambda z: z[1] < yBound, data) return np.array(data) def prepData(inputFile): """Reads data from file""" cols = __detectColumns(inputFile) printVerbose('Reading data from '+inputFile) return __readData(inputFile, cols) def calcDist(a, b): """Calculates the Euclidean distance between points a and b. Assumes a, b are 2D ordered pairs""" return np.sqrt((b[0]-a[0])**2 + (b[1]-a[1])**2) def updateClusters(clusters, pivot, indices): """Updates cluster list""" if len(indices) == 0: return clusters else: matches = [clusters[i] for i in indices] index = np.min([np.min(matches), clusters[pivot]]) clusters[pivot] = index for i, value in enumerate(clusters): if value in matches: clusters[i] = index return clusters def prettyClusterNames(clusters): """Minimizes cluster labels, so that labels go from 1 - N for N clusters""" N = sorted(set(clusters)) return map(lambda z: N.index(z), clusters) def label(cluster): """Turns cluster labels into alphabetic characters, if necessary""" if alphaLabels: over = cluster/26 idx = cluster%26 if over: return alpha[over]+alpha[idx] else: return alpha[idx] else: return str(cluster+1) def printVerbose(text): if verbose: print text if __name__ == "__main__": """Execute main functions directly, without importing""" if len(sys.argv) < 3: print "Wrong number of arguments.\n\nUsage:python fixationClusters.py outputPrefix input clusterDistance\n\nPlease try again." sys.exit() outPrefix = sys.argv[1] inFile = sys.argv[2] cDistance = float(sys.argv[3]) try: f = open(inFile) f.close() except: print "Error importing fixation file. Check file name and try again." sys.exit() data = prepData(inFile) clusters= [] for subject, datum in enumerate(data): clusters.append([]) printVerbose('\nSubject %i'%(subject)) output = [] for trial, fixs in enumerate(datum): cTemp = range(len(fixs)) for index, coords in enumerate(fixs): temp = [i for i in range(index+1, len(fixs)) if calcDist(fixs[i],coords) < cDistance] cTemp = updateClusters(cTemp, index, temp) clusters[-1].append(prettyClusterNames(cTemp)) printVerbose('Writing data...\n') out = open(outPrefix+'.txt', 'w') out.write('%-7s, %-7s, %-7s, %-7s, %-7s\n'%('Subject', ' Trial', ' x-pos', ' y-pos', 'Cluster')) for i, subject in enumerate(clusters): for j, trial in enumerate(subject): if data[i][j][0] != 'NoTrial': if sortFix: N = np.argsort(trial) for k in N: out.write('%7d, %7d, %7.1f, %7.1f, %7s\n'%(i+1, j+1, data[i][j][k][0], data[i][j][k][1], label(trial[k]))) else: for k, cluster in enumerate(trial): out.write('%7d, %7d, %7.1f, %7.1f, %7s\n'%(i+1, j+1, data[i][j][k][0], data[i][j][k][1], label(cluster))) out.close() printVerbose('Output file %s written successfully\n'%(outPrefix+'.txt')) From schmitgreg at gmail.com Tue Oct 11 16:54:43 2016 From: schmitgreg at gmail.com (Greg Schmit) Date: Tue, 11 Oct 2016 15:54:43 -0500 Subject: [Tutor] Python 3.x and Sqlite3 Message-ID: On FreeBSD I built lang/python34 from source and when I run python 3.4 I cannot import sqlite3. I thought it was being packaged with python 3.4. Am I incorrect in this assumption? -gns From kentaro0919 at gmail.com Tue Oct 11 19:14:30 2016 From: kentaro0919 at gmail.com (Kentaro Hori) Date: Wed, 12 Oct 2016 08:14:30 +0900 Subject: [Tutor] Python 3.x and Sqlite3 In-Reply-To: References: Message-ID: You have to add to .configure iPhone???? 2016/10/12 5:54?Greg Schmit ??????: > On FreeBSD I built lang/python34 from source and when I run python 3.4 I cannot import sqlite3. I thought it was being packaged with python 3.4. Am I incorrect in this assumption? > > -gns > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From alan.gauld at yahoo.co.uk Tue Oct 11 19:23:20 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 12 Oct 2016 00:23:20 +0100 Subject: [Tutor] Cluster analysis script error In-Reply-To: References: Message-ID: On 11/10/16 22:13, Mike Armson wrote: > I am trying to run a script (attached) which determines the number of > clusters of fixations within a set of eye movement data. The script says to > enter the following command on python: > > "python fixationClusters.py outputPrefix input clusterDistance" > > I am getting a syntax error with the output command I'm guessing that you are trying to run this from the Python interactive prompt (>>>)? In fact, you should run it from an OS shell prompt (you don't say which OS but in Windoze thats a CMD prompt, in MacOS the Terminal App and in Linux whichever of the many Terminal apps you use...) The clue is that you are getting a syntax error - which is usually from Python, but the command begins with 'python' which is how you call the interpreter from the OS. I suspect the phrase "...enter the following command on python:" is a little misleading, it should say something like "enter the following command at an OS shell prompt" 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 From zachary.ware+pytut at gmail.com Wed Oct 12 00:05:27 2016 From: zachary.ware+pytut at gmail.com (Zachary Ware) Date: Tue, 11 Oct 2016 23:05:27 -0500 Subject: [Tutor] Python 3.x and Sqlite3 In-Reply-To: References: Message-ID: Hi Greg, On Tue, Oct 11, 2016 at 3:54 PM, Greg Schmit wrote: > On FreeBSD I built lang/python34 from source and when I run python 3.4 I cannot import sqlite3. I thought it was being packaged with python 3.4. Am I incorrect in this assumption? This is more the kind of fare that python-list is good for; this list is more for learning how to use Python. In any case, you'll need to make sure you have sqlite3 and its headers installed before building Python. At the end of the 'make' step, you probably got a message saying "The necessary bits to build these optional modules were not found:" with _sqlite3 listed underneath it. There may also be other useful modules listed there that you may want to install the dependencies for, such as readline or _ssl. Hope this helps, -- Zach From dvnsarma at gmail.com Wed Oct 12 00:25:14 2016 From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=) Date: Wed, 12 Oct 2016 09:55:14 +0530 Subject: [Tutor] Python Code Not Working In-Reply-To: <57faab0d.5d25ed0a.70628.6550@mx.google.com> References: <57faab0d.5d25ed0a.70628.6550@mx.google.com> Message-ID: An easier solution is simply to type 'print' in place of 'test' in the program. It will work. regards, Sarma. On Mon, Oct 10, 2016 at 2:09 AM, wrote: > Everytime I run this it says test is not defined . I don?t understand. Can someone please help correct? > > #Question 10 > > def reverse(mystr): > reversed = '' > for char in mystr: > reversed = char + reversed > return reversed > > def is_palindrome(myStr): > if myStr in reverse(myStr): > return True > else: > return False > > test(is_palindrome("abba")) > test(not is_palindrome("abab")) > test(is_palindrome("tenet")) > test(not is_palindrome("banana")) > test(is_palindrome("straw warts")) > test(is_palindrome("a")) > test(is_palindrome("")) > > -Jeremy Gainey > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From nirajkumarpandey at gmail.com Wed Oct 12 04:03:15 2016 From: nirajkumarpandey at gmail.com (niraj pandey) Date: Wed, 12 Oct 2016 13:33:15 +0530 Subject: [Tutor] Need help In-Reply-To: References: Message-ID: Hi , I need one more help related to printer. Can you pls guide how to print this screen (Attached here) content in printer ? Thanks Niraj On Tue, Oct 4, 2016 at 12:21 PM, niraj pandey wrote: > Ok I got it from the solution you provided on your previous mail. > > Thanks again > > Thanks > Niraj > > On Tue, Oct 4, 2016 at 12:05 PM, niraj pandey > wrote: > >> Attaching two snapshots here. >> >> In first snapshot (1.png) I have the label windows without the values and >> in second window (2.png) every label have some value. >> I want to put these values in front of every label. I have already stored >> these values in a variable. >> >> Thanks >> Niraj >> >> On Mon, Oct 3, 2016 at 10:02 PM, niraj pandey > > wrote: >> >>> Hello Alan , >>> >>> I am using python 2.7.10 and using RHEL6 >>> >>> Thanks >>> >>> >>> On Mon, Oct 3, 2016 at 8:53 PM, Alan Gauld via Tutor >>> wrote: >>> >>>> On 03/10/16 10:54, niraj pandey wrote: >>>> >>>> > I want to add every lebels value here (ie fetch from DB and display in >>>> > front of every lebel or I had store every lable value in variable and >>>> > display here). >>>> >>>> You need to tell us which OS, Python version and GUI >>>> toolkit you are using. >>>> >>>> > [image: Inline image 1] >>>> >>>> This is a text list so images usually get stripped off. >>>> If absolutely necessary to send an image use a link to an >>>> image gallery somewhere. >>>> >>>> But at least try to explain what you are trying to show us. >>>> >>>> > Is there any function which I can use for this (like we have >>>> entry.get to >>>> > get the value similar any function to put the value) >>>> >>>> Assuming you are using Tkinter there is an insert() method. >>>> To put text at the end of the entry use >>>> >>>> import tkinter as tk >>>> myText = "Hello world" >>>> top = tk.Tk() >>>> >>>> myEntry = tk.Entry(top) >>>> myEntry.pack() >>>> myEntry.insert(tk.END,mytext) >>>> >>>> top.mainloop() >>>> >>>> >>>> However a common alternative is to use a StringVar and associate it with >>>> the Entry so that changes in the StringVar are automatically >>>> shown in the Entry and changes in the Entrey are reflected to the >>>> StringVar. Most Tkinter tutorials will show that under StringVar. >>>> >>>> Of course if you are not using Tkinter most of that will be useless! >>>> >>>> >>>> -- >>>> 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 at python.org >>>> To unsubscribe or change subscription options: >>>> https://mail.python.org/mailman/listinfo/tutor >>>> >>> >>> >>> >>> -- >>> Success occurs when opportunity and preparation meet >>> >> >> >> >> -- >> Success occurs when opportunity and preparation meet >> > > > > -- > Success occurs when opportunity and preparation meet > -- Success occurs when opportunity and preparation meet From sohlq710 at gmail.com Tue Oct 11 20:37:26 2016 From: sohlq710 at gmail.com (LQ Soh) Date: Tue, 11 Oct 2016 20:37:26 -0400 Subject: [Tutor] Adding numbers within a string Message-ID: To whom it may concern, Can someone enlighten me as to how you can create a function such that sum_numbers('10 5 8'), when run, will give an answer of 23, without using str.split() and using a for loop From alan.gauld at yahoo.co.uk Wed Oct 12 04:17:04 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 12 Oct 2016 09:17:04 +0100 Subject: [Tutor] Need help In-Reply-To: References: Message-ID: On 12/10/16 09:03, niraj pandey wrote: > Can you pls guide how to print this screen (Attached here) content in > printer ? As we already pointed out this is a text list so attachments are usually stripped off... However, printing from Tkinter is not easy. The simplest way is usually to create an HTML file and use the OS to print that via a browser (many browsers have a print command line option). It is possible to convert your screen into a graphics file and print that, but the results can be a bit unpredictable. Alan G. From alan.gauld at yahoo.co.uk Wed Oct 12 04:25:09 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 12 Oct 2016 09:25:09 +0100 Subject: [Tutor] Adding numbers within a string In-Reply-To: References: Message-ID: On 12/10/16 01:37, LQ Soh wrote: > To whom it may concern, > Can someone enlighten me as to how you can create a function such > that sum_numbers('10 5 8'), when run, will give an answer of 23, without > using str.split() and using a for loop I'm assuming this is some kind of classroom exercise? Otherwise the advice is just use string split()! If it is a class exercise then the easiest option is to write your own string split(). That is a function that takes in a string and spits out substrings. To do that you need to traverse the string and look for separators. Store the characters between separators in a list. return the list. Another way to do it is to use a regular expression to detect the groups of characters - do you know about regex? Once you have done the splitting you need to convert the substrings into numbers and add them. -- 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 From bgailer at gmail.com Wed Oct 12 10:26:12 2016 From: bgailer at gmail.com (Bob Gailer) Date: Wed, 12 Oct 2016 10:26:12 -0400 Subject: [Tutor] Adding numbers within a string In-Reply-To: References: Message-ID: On Oct 12, 2016 4:09 AM, "LQ Soh" wrote: > > To whom it may concern, > Can someone enlighten me as to how you can create a function such > that sum_numbers('10 5 8'), when run, will give an answer of 23, without > using str.split() and using a for loop def sum_numbers(x): for x in [1]: print(23) Your instructor will probably be displeased with that answer, but it meets the requirements. It would be nice if our teachers could models writing good requirements. What do you think a good requirement statement would be? _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From itetteh34 at hotmail.com Wed Oct 12 11:31:48 2016 From: itetteh34 at hotmail.com (isaac tetteh) Date: Wed, 12 Oct 2016 15:31:48 +0000 Subject: [Tutor] Adding numbers within a string In-Reply-To: References: , Message-ID: def foo(x): a,b = (0,"") for i in x: if i != " ": b+=i else: print ("this is b",b) a = a + int(b) print ("this is a",a) b = "" print ("final a ",a) this should help you solve it. figure a way to add the last number. if any troubles ask again. Thanks [?] ________________________________ From: Tutor on behalf of Bob Gailer Sent: Wednesday, October 12, 2016 2:26 PM To: LQ Soh Cc: tutor at python.org Subject: Re: [Tutor] Adding numbers within a string On Oct 12, 2016 4:09 AM, "LQ Soh" wrote: > > To whom it may concern, > Can someone enlighten me as to how you can create a function such > that sum_numbers('10 5 8'), when run, will give an answer of 23, without > using str.split() and using a for loop def sum_numbers(x): for x in [1]: print(23) Your instructor will probably be displeased with that answer, but it meets the requirements. It would be nice if our teachers could models writing good requirements. What do you think a good requirement statement would be? _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor Tutor Info Page - mail.python.org Mailing Lists mail.python.org This list is for folks who want to ask questions regarding how to learn computer programming with the Python language and its standard library. _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor Tutor Info Page - mail.python.org Mailing Lists mail.python.org This list is for folks who want to ask questions regarding how to learn computer programming with the Python language and its standard library. From hellgatez1 at yandex.com Wed Oct 12 05:52:16 2016 From: hellgatez1 at yandex.com (hell gates) Date: Wed, 12 Oct 2016 16:52:16 +0700 Subject: [Tutor] Adding numbers within a string In-Reply-To: References: Message-ID: <2983391476265936@web25h.yandex.ru> You can write your own str.split or just use while loop. 12.10.2016, 15:12, "LQ Soh" : To whom it may concern, Can someone enlighten me as to how you can create a function such that sum_numbers('10 5 8'), when run, will give an answer of 23, without using str.split() and using a for loop _______________________________________________ Tutor maillist - [1]Tutor at python.org To unsubscribe or change subscription options: [2]https://mail.python.org/mailman/listinfo/tutor References Visible links 1. mailto:Tutor at python.org 2. https://mail.python.org/mailman/listinfo/tutor From dvnsarma at gmail.com Wed Oct 12 12:50:59 2016 From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=) Date: Wed, 12 Oct 2016 22:20:59 +0530 Subject: [Tutor] Adding numbers within a string In-Reply-To: <2983391476265936@web25h.yandex.ru> References: <2983391476265936@web25h.yandex.ru> Message-ID: def string_sum(s): total = 0 items = s.split(" ") for item in items: total += int(item) print(total) You can call the function as string_sum("10 4 5 ") Output will be 19. regards, Sarma. On Wed, Oct 12, 2016 at 3:22 PM, hell gates wrote: > You can write your own str.split or just use while loop. > 12.10.2016, 15:12, "LQ Soh" : > > To whom it may concern, > Can someone enlighten me as to how you can create a function such > that sum_numbers('10 5 8'), when run, will give an answer of 23, without > using str.split() and using a for loop > _______________________________________________ > Tutor maillist - [1]Tutor at python.org > To unsubscribe or change subscription options: > [2]https://mail.python.org/mailman/listinfo/tutor > > References > > Visible links > 1. mailto:Tutor at python.org > 2. https://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From dvnsarma at gmail.com Wed Oct 12 12:58:39 2016 From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=) Date: Wed, 12 Oct 2016 22:28:39 +0530 Subject: [Tutor] Adding numbers within a string In-Reply-To: References: <2983391476265936@web25h.yandex.ru> Message-ID: Sorry, I did not read the conditions that split and for should not be used. regards, Sarma. On Wed, Oct 12, 2016 at 10:20 PM, D.V.N.Sarma ??.??.???.???? wrote: > def string_sum(s): > total = 0 > items = s.split(" ") > for item in items: > total += int(item) > print(total) > > You can call the function as > > string_sum("10 4 5 ") > > Output will be 19. > regards, > Sarma. > > > On Wed, Oct 12, 2016 at 3:22 PM, hell gates wrote: >> You can write your own str.split or just use while loop. >> 12.10.2016, 15:12, "LQ Soh" : >> >> To whom it may concern, >> Can someone enlighten me as to how you can create a function such >> that sum_numbers('10 5 8'), when run, will give an answer of 23, without >> using str.split() and using a for loop >> _______________________________________________ >> Tutor maillist - [1]Tutor at python.org >> To unsubscribe or change subscription options: >> [2]https://mail.python.org/mailman/listinfo/tutor >> >> References >> >> Visible links >> 1. mailto:Tutor at python.org >> 2. https://mail.python.org/mailman/listinfo/tutor >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor From drtraceyjones at hotmail.com Wed Oct 12 13:40:10 2016 From: drtraceyjones at hotmail.com (tracey jones-Francis) Date: Wed, 12 Oct 2016 17:40:10 +0000 Subject: [Tutor] Code for python game Message-ID: Im in the middle of designing a game in python, im quite new to using it and am struggling with a certain bit of code. I want to have a function that will ignore certain words that i have specified in a dictionary. I have tried so many different types of code but can't seem to return just the keywords i want. the dictionary is called skip_words and has about 20 different strings in. so far i came up with: def filter_words(words, skip_words): word = words.strip(skip_words) return word The function should read an input such as help me please and filter out the words "please" and "me" as they are in the dictionary and just return the word help as the input. >>>filter_words(["help", "me", "please"], ["me", "please"]) ['help'] That doesn't work but i just assume it is a very simple bit of code. any suggestions of a way that works? Thanks:) T From alan.gauld at yahoo.co.uk Wed Oct 12 14:05:40 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 12 Oct 2016 19:05:40 +0100 Subject: [Tutor] Adding numbers within a string In-Reply-To: References: <2983391476265936@web25h.yandex.ru> Message-ID: On 12/10/16 17:58, D.V.N.Sarma ??.??.???.???? wrote: > Sorry, I did not read the conditions that split and for should not be used. It is even more confusing - split() may NOT be used but 'for' MUST be used... -- 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 From alan.gauld at yahoo.co.uk Wed Oct 12 14:17:01 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 12 Oct 2016 19:17:01 +0100 Subject: [Tutor] Code for python game In-Reply-To: References: Message-ID: On 12/10/16 18:40, tracey jones-Francis wrote: > I want to have a function that will ignore certain words that > i have specified in a dictionary. > the dictionary is called skip_words and has about 20 different strings in. We shouldn't care inside the function what the external data is called, we just write it to accept a list of words (its not a dictionary, it is a list). > def filter_words(words, skip_words): > word = words.strip(skip_words) > return word > >>>> filter_words(["help", "me", "please"], ["me", "please"]) > ['help'] Your code above cannot work because it tries to strip() a list of words. You can only strip one string at a time, so the first thing you need is a loop that tests each word. Secondly strip() removes characters from your string but that's not necessarily needed here (it depends how you build the input list...) Let's assume the words are already stripped and in lowercase. Now, for each word in your input you want to see if it is in the skip list. If not add it to your output list - you haven't got one of those yet so you'll need to create one. Once you have tested all the input words you can return the result list. I It should look something like (untested): def filter_words(words, skips): result = [] for word in words: if word not in skips: results.append(word) return result If you know about list comprehensions you can do that all in one line! -- 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 From jderry at austin.utexas.edu Wed Oct 12 14:20:05 2016 From: jderry at austin.utexas.edu (Derry, James R) Date: Wed, 12 Oct 2016 18:20:05 +0000 Subject: [Tutor] Code for python game In-Reply-To: References: Message-ID: hi, tracey, are you allowed to use python sets? if so, you should take a look at them and their methods: https://docs.python.org/3.5/tutorial/datastructures.html?highlight=data%20structures#sets best, james ________________________________________ From: Tutor [tutor-bounces+jderry=mail.utexas.edu at python.org] on behalf of tracey jones-Francis [drtraceyjones at hotmail.com] Sent: Wednesday, October 12, 2016 12:40 PM To: tutor at python.org Subject: [Tutor] Code for python game Im in the middle of designing a game in python, im quite new to using it and am struggling with a certain bit of code. I want to have a function that will ignore certain words that i have specified in a dictionary. I have tried so many different types of code but can't seem to return just the keywords i want. the dictionary is called skip_words and has about 20 different strings in. so far i came up with: def filter_words(words, skip_words): word = words.strip(skip_words) return word The function should read an input such as help me please and filter out the words "please" and "me" as they are in the dictionary and just return the word help as the input. >>>filter_words(["help", "me", "please"], ["me", "please"]) ['help'] That doesn't work but i just assume it is a very simple bit of code. any suggestions of a way that works? Thanks:) T _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From dvnsarma at gmail.com Thu Oct 13 01:59:53 2016 From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=) Date: Thu, 13 Oct 2016 11:29:53 +0530 Subject: [Tutor] Adding numbers within a string In-Reply-To: References: <2983391476265936@web25h.yandex.ru> Message-ID: Then Isaac's function does that(but you have to leave a space after last number in the string). def foo(x): a, b = 0, "" for i in x: if i != " ": b += i else: print ("this is b", b) a += int(b) print ("this is a",a) b = "" print ("final a ",a) foo("10 5 8 ") regards, Sarma. On Wed, Oct 12, 2016 at 11:35 PM, Alan Gauld via Tutor wrote: > On 12/10/16 17:58, D.V.N.Sarma ??.??.???.???? wrote: >> Sorry, I did not read the conditions that split and for should not be used. > > It is even more confusing - split() may NOT be used > but 'for' MUST be used... > > -- > 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 at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From danny.yoo at gmail.com Thu Oct 13 02:31:10 2016 From: danny.yoo at gmail.com (Danny Yoo) Date: Wed, 12 Oct 2016 23:31:10 -0700 Subject: [Tutor] Adding numbers within a string In-Reply-To: References: <2983391476265936@web25h.yandex.ru> Message-ID: Please do not give homework solutions. Thanks. From anish198519851985 at gmail.com Thu Oct 13 02:52:11 2016 From: anish198519851985 at gmail.com (anish singh) Date: Wed, 12 Oct 2016 23:52:11 -0700 Subject: [Tutor] python grep implementation Message-ID: I am trying to implement grep functionality in python. import os, sys, getopt import multiprocessing as mp import re import itertools def get_files(path, pattern): for (dirpath, dirnames, filenames) in os.walk(path): for filename in filenames: if filename.endswith(pattern): yield os.path.join(dirpath, filename) def worker_search_fn(arg): fname, regex = arg with open(fname, 'rt') as f: match = regex.search(f.read()) if match: print(fname + " " +":"+ match.group()) return def main(argv): path, f_pattern, s_pattern = '', '', '' try: opts, args = getopt.getopt(argv,"hi:p:f:s:S:",["ifile=","file_pattern=","string_pattern=","string_flags="]) except getopt.GetoptError: print 'test.py -i -p -f -S ' print 'example usage python a.py -i . -s \'.*_i2c_register.*\' -f .c,.h,.cpp -S "S"' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'test.py -i -p , -f ' sys.exit() elif opt in ("-i", "--ifile"): path = arg elif opt in ("-f", "--file_pattern"): f_pattern = arg.split(",") elif opt in ("-s", "--string_pattern"): s_pattern = arg elif opt in ("-S", "--string_flags"): s_pattern_flags = arg regex = re.compile(s_pattern, getattr(re, s_pattern_flags)) files = get_files(path, tuple(f_pattern)) mp.Pool().map(worker_search_fn, itertools.izip(files, itertools.repeat(regex))) if __name__ == "__main__": main(sys.argv[1:]) I want to see if I can further speedup in any way possible and also some code review. From ryan at allwegot.net Wed Oct 12 20:00:18 2016 From: ryan at allwegot.net (Ryan Smith) Date: Wed, 12 Oct 2016 20:00:18 -0400 Subject: [Tutor] Need help In-Reply-To: References: Message-ID: On Wednesday, October 12, 2016, Alan Gauld via Tutor wrote: > On 12/10/16 09:03, niraj pandey wrote: > > > Can you pls guide how to print this screen (Attached here) content in > > printer ? > > As we already pointed out this is a text list so attachments > are usually stripped off... > > However, printing from Tkinter is not easy. The simplest way is usually > to create an HTML file and use the OS to print that via a browser (many > browsers have a print command line option). It is possible to convert > your screen into a graphics file and print that, but the results can be > a bit unpredictable. > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From jjhartley at gmail.com Thu Oct 13 23:37:54 2016 From: jjhartley at gmail.com (James Hartley) Date: Thu, 13 Oct 2016 22:37:54 -0500 Subject: [Tutor] enforcing specific types in Python 3.5? Message-ID: I have implemented the equivalent of "insert if unique" in Python & SQLAlchemy to help with data normalization. However to help minimize the number of preliminary SELECT statements needed, it helps to check types through calls to isinstance() before getting to the salient code. Unfortunately, the code begins to be cluttered with type-checking minutiae. While researching this problem, I have found potential solutions like the following: http://stackoverflow.com/questions/9305751/force-python-class-member-variable-to-be-specific-type ...but given that Python 3.5 has syntactically understands gradual typing, I have wondered whether addition of this feature offers anything over use of property() as described above. Toy examples have not revealed anything useful on this front: $ cat example.py #!/usr/bin/env python class Foobar(): def __init__(self, value): self.value = value def f(s: str) -> int: print(s) return 3.14 def main(): i = f('foobar') print(type(i)) print('i = "{}"'.format(i)) i = f(Foobar(3)) print(type(i)) print('i = "{}"'.format(i)) if __name__ == '__main__': main() $ python example.py foobar i = "3.14" <__main__.Foobar object at 0x85b8aaac> i = "3.14" $ I understand that gradual typing may be useful with static analysis, but I don't see that any type enforcement occurs by default at runtime. Am I missing something here? Is there a better solution for type enforcement? Thanks! From __peter__ at web.de Fri Oct 14 03:48:37 2016 From: __peter__ at web.de (Peter Otten) Date: Fri, 14 Oct 2016 09:48:37 +0200 Subject: [Tutor] enforcing specific types in Python 3.5? References: Message-ID: James Hartley wrote: > I have implemented the equivalent of "insert if unique" in Python & > SQLAlchemy to help with data normalization. However to help minimize the > number of preliminary SELECT statements needed, it helps to check types > through calls to isinstance() before getting to the salient code. > Unfortunately, the code begins to be cluttered with type-checking > minutiae. > > While researching this problem, I have found potential solutions like the > following: > > http://stackoverflow.com/questions/9305751/force-python-class-member-variable-to-be-specific-type > > ...but given that Python 3.5 has syntactically understands gradual typing, > I have wondered whether addition of this feature offers anything over use > of property() as described above. Toy examples have not revealed anything > useful on this front: > > $ cat example.py > #!/usr/bin/env python > > class Foobar(): > def __init__(self, value): > self.value = value > > def f(s: str) -> int: > print(s) > return 3.14 > > def main(): > i = f('foobar') > print(type(i)) > print('i = "{}"'.format(i)) > i = f(Foobar(3)) > print(type(i)) > print('i = "{}"'.format(i)) > > if __name__ == '__main__': > main() > $ python example.py > foobar > > i = "3.14" > <__main__.Foobar object at 0x85b8aaac> > > i = "3.14" > $ > > I understand that gradual typing may be useful with static analysis, but I > don't see that any type enforcement occurs by default at runtime. Am I > missing something here? Is there a better solution for type enforcement? Quoting : """ no type checking happens at runtime . Instead, the proposal assumes the existence of a separate off-line type checker which users can run over their source code voluntarily. Essentially, such a type checker acts as a very powerful linter """ You need an external tool http://mypy-lang.org/ to perform a type check: (mypylang)$ mypy example.py example.py: note: In function "f": example.py:9: error: Incompatible return value type (got "float", expected "int") (mypylang)$ From mpreisig at gmail.com Fri Oct 14 05:47:06 2016 From: mpreisig at gmail.com (mpreisig .) Date: Fri, 14 Oct 2016 11:47:06 +0200 Subject: [Tutor] using python shell program on windows Message-ID: how can i use this program on windows: https://pypi.python.org/pypi/timesheet/0.9.2 - in a python shell? - in a windows cmd shell? - using cygwin or something similar? thanks, matthias From __peter__ at web.de Fri Oct 14 09:15:40 2016 From: __peter__ at web.de (Peter Otten) Date: Fri, 14 Oct 2016 15:15:40 +0200 Subject: [Tutor] using python shell program on windows References: Message-ID: mpreisig . wrote: > how can i use this program on windows: > > https://pypi.python.org/pypi/timesheet/0.9.2 > > - in a python shell? > - in a windows cmd shell? > - using cygwin or something similar? Did you follow the instructions on the page you linked to? "timesheet" is a script, so once it's installed you can either run it from the windows cmd shell or cygwin's bash. The latter has the advantage that it supports bash completion if you follow the instructions on the above page, i. e. when you type $ timesheet su and hit TAB the shell will turn that into $ timesheet subject [If you run into problems you are welcome to come back with specific questions.] From mpreisig at gmail.com Fri Oct 14 10:12:18 2016 From: mpreisig at gmail.com (mpreisig .) Date: Fri, 14 Oct 2016 16:12:18 +0200 Subject: [Tutor] using python shell program on windows In-Reply-To: References: Message-ID: Thanks Peter. So the setup script is supposed to generate the "timesheet" script? Because in the source there is no such file. Then the question I guess is how to install the package. Do I run the setup.py script from where I downloaded it to (e.g. in the Windows "Downloads" folder, open a cmd-window and do "python setup.py"), or do I have to copy the entire folder structure into the site-packages folder of my python directory first? Thanks, Matthias > mpreisig . wrote: > > > how can i use this program on windows: > > > > https://pypi.python.org/pypi/timesheet/0.9.2 > > > > - in a python shell? > > - in a windows cmd shell? > > - using cygwin or something similar? > > Did you follow the instructions on the page you linked to? > > "timesheet" is a script, so once it's installed you can either run it from > the windows cmd shell or cygwin's bash. The latter has the advantage that it > supports bash completion if you follow the instructions on the above page, > i. e. when you type > > $ timesheet su > > and hit TAB the shell will turn that into > > $ timesheet subject > > [If you run into problems you are welcome to come back with specific > questions.] > From __peter__ at web.de Fri Oct 14 12:52:31 2016 From: __peter__ at web.de (Peter Otten) Date: Fri, 14 Oct 2016 18:52:31 +0200 Subject: [Tutor] using python shell program on windows References: Message-ID: mpreisig . wrote: > Thanks Peter. > > So the setup script is supposed to generate the "timesheet" script? > Because in the source there is no such file. > > Then the question I guess is how to install the package. Do I run the > setup.py script from where I downloaded it to (e.g. in the Windows > "Downloads" folder, open a cmd-window and do "python setup.py"), or do I > have to copy the entire folder structure into the site-packages folder of > my python directory first? I don't have Windows available to actually test it, but according to the docs invoking python -m pip install timesheet on the commandline should take care of the details. On my (Linux) machine this also installed a script that I can invoke on the command line with $ timesheet start foo bar Started task: Subject foo Title bar Start 2016-10-14 18:49 End Duration 00:00 $ If that does not work on Windows there's probably a Windows user who knows what to try instead. From eryksun at gmail.com Fri Oct 14 14:08:09 2016 From: eryksun at gmail.com (eryk sun) Date: Fri, 14 Oct 2016 18:08:09 +0000 Subject: [Tutor] using python shell program on windows In-Reply-To: References: Message-ID: On Fri, Oct 14, 2016 at 4:52 PM, Peter Otten <__peter__ at web.de> wrote: > > python -m pip install timesheet > > on the commandline should take care of the details. On my (Linux) machine > this also installed a script that I can invoke on the command line with > > $ timesheet start foo bar > Started task: > Subject foo > Title bar > Start 2016-10-14 18:49 > End > Duration 00:00 > $ > > If that does not work on Windows there's probably a Windows user who knows > what to try instead. I haven't used this package before, but I can attest that the wheel and its dependencies do install without error on Windows, and it appears to be working. It says it supports Python 3, but I discovered it has a raw_input call in the implementation of its start command. So I suggest using Python 2 instead. The installation creates a timesheet.exe script wrapper in Python's "Scripts" folder. Unless you're using a virtual environment, you'll have to add this directory to the PATH environment variable to run timesheet from the command line. Running timesheet warns about a missing configuration file, "%LOCALAPPDATA%\timesheetrc" (expanded for your %LOCALAPPDATA% directory). I created this as an empty file to avoid the warning. If you need to back up or delete the timesheet database, it's located at "%LOCALAPPDATA%\timesheet\timesheet.sqlite". From nicholas_hopkins1 at hotmail.com Sat Oct 15 18:48:08 2016 From: nicholas_hopkins1 at hotmail.com (Nicholas Hopkins) Date: Sat, 15 Oct 2016 22:48:08 +0000 Subject: [Tutor] Python help Message-ID: Hello Please tell me what is wrong with my code and how I can put an if else statement inside of another if else statement This is my code: path = input('Which path number will you take?') if path == '1': print('You took the first path') elif path == '2': print('You choose to take the second path') print('You see a rock') rock == input('Do you want to pick up the rock') if rock == 'yes': print('you picked up the rock') else: print('You left the rock') elif path == '3': print('You choose to take the third path') else: print('You must choose a number between 1 and 3') it comes up with this error [cid:image001.png at 01D22792.63CCF290] Thanks Sent from Mail for Windows 10 From alan.gauld at yahoo.co.uk Sun Oct 16 20:19:42 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 17 Oct 2016 01:19:42 +0100 Subject: [Tutor] Python help In-Reply-To: References: Message-ID: On 15/10/16 23:48, Nicholas Hopkins wrote: > Please tell me what is wrong with my code and how I can put an if else statement > inside of another if else statement You are almost right but... > This is my code: > path = input('Which path number will you take?') > if path == '1': > print('You took the first path') > elif path == '2': > print('You choose to take the second path') > print('You see a rock') > rock == input('Do you want to pick up the rock') indentation is important in Python and the above line should line up with the one above it. You should have gotten an Indentation Error message. > if rock == 'yes': > print('you picked up the rock') > else: > print('You left the rock') And if this clause lined up correctly too then it would work as you expected. > elif path == '3': > print('You choose to take the third path') > else: > print('You must choose a number between 1 and 3') > > > it comes up with this error > [cid:image001.png at 01D22792.63CCF290] Please include the error in your message. This is a text only list and attachments tend to get stripped off -- 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 From akleider at sonic.net Sun Oct 16 22:52:52 2016 From: akleider at sonic.net (Alex Kleider) Date: Sun, 16 Oct 2016 19:52:52 -0700 Subject: [Tutor] Python help In-Reply-To: References: Message-ID: <67ba6cef24aa4bb33b3a5f924266123a@sonic.net> On 2016-10-15 15:48, Nicholas Hopkins wrote: > Hello > Please tell me what is wrong with my code and how I can put an if else > statement inside of another if else statement > This is my code: > path = input('Which path number will you take?') > if path == '1': > print('You took the first path') > elif path == '2': > print('You choose to take the second path') > print('You see a rock') > rock == input('Do you want to pick up the rock') > if rock == 'yes': > print('you picked up the rock') > else: > print('You left the rock') > elif path == '3': > print('You choose to take the third path') > else: > print('You must choose a number between 1 and 3') > > > it comes up with this error > [cid:image001.png at 01D22792.63CCF290] Can't see your error (text only list) but it's probably due to indentation problems. Why do you have only the first line not indented? Also check indentation of lines 7, 8 and 10. > Thanks > Sent from Mail for > Windows 10 > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From ajk225 at gmail.com Sun Oct 16 20:24:19 2016 From: ajk225 at gmail.com (Andrew Koe) Date: Sun, 16 Oct 2016 20:24:19 -0400 Subject: [Tutor] Python help In-Reply-To: References: Message-ID: Hi, Also, you have a typo in your elif path == '2' statement. It should be rock = input('Do you want to pick up the rock') with one equal sign not rock == input ('Do you want to pick up the rock'). -Andrew On Sat, Oct 15, 2016 at 6:48 PM, Nicholas Hopkins wrote: > Hello > Please tell me what is wrong with my code and how I can put an if else statement inside of another if else statement > This is my code: > path = input('Which path number will you take?') > if path == '1': > print('You took the first path') > elif path == '2': > print('You choose to take the second path') > print('You see a rock') > rock == input('Do you want to pick up the rock') > if rock == 'yes': > print('you picked up the rock') > else: > print('You left the rock') > elif path == '3': > print('You choose to take the third path') > else: > print('You must choose a number between 1 and 3') > > > it comes up with this error > [cid:image001.png at 01D22792.63CCF290] > Thanks > Sent from Mail for Windows 10 > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From mpreisig at gmail.com Mon Oct 17 04:11:29 2016 From: mpreisig at gmail.com (mpreisig .) Date: Mon, 17 Oct 2016 10:11:29 +0200 Subject: [Tutor] using python shell program on windows In-Reply-To: References: Message-ID: Thanks a lot Peter and eryk for these very clear explanations. I was able to install successfully using pip and run the program. Best, Matthias > On Fri, Oct 14, 2016 at 4:52 PM, Peter Otten <__peter__ at web.de> wrote: > > > > python -m pip install timesheet > > > > on the commandline should take care of the details. On my (Linux) machine > > this also installed a script that I can invoke on the command line with > > > > $ timesheet start foo bar > > Started task: > > Subject foo > > Title bar > > Start 2016-10-14 18:49 > > End > > Duration 00:00 > > $ > > > > If that does not work on Windows there's probably a Windows user who knows > > what to try instead. > > I haven't used this package before, but I can attest that the wheel > and its dependencies do install without error on Windows, and it > appears to be working. > > It says it supports Python 3, but I discovered it has a raw_input call > in the implementation of its start command. So I suggest using Python > 2 instead. > > The installation creates a timesheet.exe script wrapper in Python's > "Scripts" folder. Unless you're using a virtual environment, you'll > have to add this directory to the PATH environment variable to run > timesheet from the command line. > > Running timesheet warns about a missing configuration file, > "%LOCALAPPDATA%\timesheetrc" (expanded for your %LOCALAPPDATA% > directory). I created this as an empty file to avoid the warning. > > If you need to back up or delete the timesheet database, it's located > at "%LOCALAPPDATA%\timesheet\timesheet.sqlite". > From 12306 at smcdsb.on.ca Mon Oct 17 21:31:27 2016 From: 12306 at smcdsb.on.ca (Zeel Solanki) Date: Mon, 17 Oct 2016 20:31:27 -0500 Subject: [Tutor] Python Easy Word Problem (Grade 11) Message-ID: Hello, I just recently started learning python and I am having trouble figure out the following python problem. Can you please help me make the code for the the problem below: Problem: Write a version of a palindrome recogniser that accepts a file name from the user, reads each line, and prints the line to the screen if it is a palindrome. Please help me find the code to solve this problem. Please and thank you. -- This is a student email account managed by Simcoe Muskoka Catholic District School Board. The contents of this email are governed by the laws of the state and the board policies of the school district. From alan.gauld at yahoo.co.uk Tue Oct 18 03:38:52 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 18 Oct 2016 08:38:52 +0100 Subject: [Tutor] Python Easy Word Problem (Grade 11) In-Reply-To: References: Message-ID: On 18/10/16 02:31, Zeel Solanki wrote: > I just recently started learning python and I am having trouble figure out > the following python problem. Can you please help me make the code for the > the problem below: We will help, but we won;t do the lesson for you. You will need to wr4ite the code. > Problem: > Write a version of a palindrome recogniser that accepts a file name from > the user, reads each line, and prints the line to the screen if it is a > palindrome. Do you know about functions yet? If so can you write a function that recognises palindromes? def is_palindrome(aString):... That would be a good first step. Secondly, can you write a function that opens a file and prints each line? def process_file(filename):.... Thirdly can you read a filename from the user and return it? def get_filename:.... If so then your main program should be very easy to write. If you are unsure about any of those three steps let us know. But make sure you send us your code, even if it's broken. Also send us the full text of any error messages you get. Finally tell us which OS and Python version you are using. -- 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 From badouglas at gmail.com Tue Oct 18 13:00:29 2016 From: badouglas at gmail.com (bruce) Date: Tue, 18 Oct 2016 13:00:29 -0400 Subject: [Tutor] selenium bindings... Message-ID: Hi. This is prob way off topic. Looking at web examples from different sites for selenium/python bindings. Basically, trying to get an understanding of how to get the "page" content of a page, after an implicit/explicit wait. I can see how to get an element, but can't see any site that describes how to get the complete page... As an example of getting an element... ------------------------ from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Firefox() driver.get("http://somedomain/url_that_delays_loading") try: element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "myDynamicElement")) ) finally: driver.quit() ---------------------------- But, as to getting the complete page, in the "try".. no clue. Any thoughts/pointers?? thanks From alan.gauld at yahoo.co.uk Tue Oct 18 18:59:57 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 18 Oct 2016 23:59:57 +0100 Subject: [Tutor] selenium bindings... In-Reply-To: References: Message-ID: On 18/10/16 18:00, bruce wrote: > This is prob way off topic. Yep, more appropriate for a selenium group/list. There is one on gmane at gmane.comp.web.selenium.user Try asking there. -- 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 From sahil4u2u at gmail.com Tue Oct 18 20:33:21 2016 From: sahil4u2u at gmail.com (Sahil Chauhan) Date: Tue, 18 Oct 2016 20:33:21 -0400 Subject: [Tutor] selenium bindings... In-Reply-To: References: Message-ID: You can get the page source with if that's what you are looking for driver.page_source Regards, Sahil On Tue, Oct 18, 2016 at 1:00 PM, bruce wrote: > Hi. > > This is prob way off topic. > > Looking at web examples from different sites for selenium/python > bindings. Basically, trying to get an understanding of how to get the > "page" content of a page, after an implicit/explicit wait. > > I can see how to get an element, but can't see any site that describes > how to get the complete page... > > As an example of getting an element... > > ------------------------ > from selenium import webdriver > from selenium.webdriver.common.by import By > from selenium.webdriver.support.ui import WebDriverWait > from selenium.webdriver.support import expected_conditions as EC > > driver = webdriver.Firefox() > driver.get("http://somedomain/url_that_delays_loading") > try: > element = WebDriverWait(driver, 10).until( > EC.presence_of_element_located((By.ID, "myDynamicElement")) > ) > finally: > driver.quit() > ---------------------------- > > But, as to getting the complete page, in the "try".. no clue. > > Any thoughts/pointers?? > > thanks > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From tonifuente at yahoo.co.uk Wed Oct 19 10:06:41 2016 From: tonifuente at yahoo.co.uk (Toni Fuente) Date: Wed, 19 Oct 2016 15:06:41 +0100 Subject: [Tutor] Subdividing config file by matching line from a file Message-ID: <20161019140640.GA20541@macarra> Hello everybody, I am trying to divide a configuration file (configs) in the form of: ServerAdmin webmaster at foo.com ServerName www.foo.com DocumentRoot /home/public/web/htdocs/foo.com ScriptAlias /cgi-bin/ /home/public/web/htdocs/foo.com/cgi-bin/ [...] ServerAdmin webmaster at bar.com ServerName www.bar.com DocumentRoot /home/public/web/htdocs/bar.com/ [...] into different individual config files for the different domains. In a different file (sites), I've got a list of domains. foo.com example.com blabla.com [...] I've approached this problem by creating first a list of all the config "chunks" with this piece of code: #!/usr/bin/python token = '\n' chunks = [] current_chunk = [] for line in open('configs'): if line.startswith(token) and current_chunk: # if line starts with token and the current chunk is not empty chunks.append(current_chunk[:]) # add not empty chunk to chunks current_chunk = [] # make current chunk blank # just append a line to the current chunk on each iteration current_chunk.append(line) chunks.append(current_chunk) # append the last chunk outside the loop Dividing the chunks of confg by blank line: token='\n' into a list of lists. And now I am stuck trying to iterate through the chunks list, and iterate through the sites file trying to find the "site" string and if found, print the entire "chunk", which will be send to a personal site configuration file. Like so: for item in chunks: #print item for line in open('sites'): #print line for i in item: if line not in i: continue else: print item break I don't get the results that I am expecting. Is is the right way to approach this problem? Any direction will be very helpful. Thank you in advance, -- Toni From __peter__ at web.de Wed Oct 19 10:52:50 2016 From: __peter__ at web.de (Peter Otten) Date: Wed, 19 Oct 2016 16:52:50 +0200 Subject: [Tutor] Subdividing config file by matching line from a file References: <20161019140640.GA20541@macarra> Message-ID: Toni Fuente via Tutor wrote: > Hello everybody, > > I am trying to divide a configuration file (configs) in the form of: > > > ServerAdmin webmaster at foo.com > ServerName www.foo.com > DocumentRoot /home/public/web/htdocs/foo.com > ScriptAlias /cgi-bin/ /home/public/web/htdocs/foo.com/cgi-bin/ > > > [...] > > > ServerAdmin webmaster at bar.com > ServerName www.bar.com > DocumentRoot /home/public/web/htdocs/bar.com/ > > > [...] > > > into different individual config files for the different domains. > > In a different file (sites), I've got a list of domains. > > foo.com > example.com > blabla.com > [...] > > I've approached this problem by creating first a list of all the config > "chunks" with this piece of code: > > > #!/usr/bin/python > > token = '\n' > chunks = [] > current_chunk = [] > > > for line in open('configs'): > if line.startswith(token) and current_chunk: > # if line starts with token and the current chunk is not empty > chunks.append(current_chunk[:]) # add not empty chunk to chunks > current_chunk = [] # make current chunk blank > # just append a line to the current chunk on each iteration > current_chunk.append(line) > > chunks.append(current_chunk) # append the last chunk outside the loop > > > Dividing the chunks of confg by blank line: token='\n' into a list of > lists. > > And now I am stuck trying to iterate through the chunks list, and iterate > through the sites file trying to find the "site" string and if found, > print the entire "chunk", which will be send to a personal site > configuration file. Like so: > > for item in chunks: > #print item > for line in open('sites'): > #print line > for i in item: > if line not in i: > continue > else: > print item > break > > I don't get the results that I am expecting. Is is the right way to > approach this problem? Any direction will be very helpful. > > Thank you in advance, > You have to search all chunks for a specific site, i. e. you need the outer loop to iterate over the sites and the inner loops (repeatedly) over the chunks. It is easier to see the structure when you factor the site-search into its own function: def find_chunk(site, chunks): for chunk in chunks: if any(site in line for line in chunk): return chunk return None # no appropriate chunk found # (you might instead raise an Exception) for line in open("sites"): site = line.strip() chunk = find_chunk(site, chunks) if chunk is not None: print "Site:", site print "Config:" print "".join(chunk) else: print >> sys.stderr, "no configuration for site", site print "---" (If the number of chunks were huge you'd build some kind of lookup table mapping site to chunk, but in your case this is hardly worthwile) From tonifuente at yahoo.co.uk Wed Oct 19 12:05:15 2016 From: tonifuente at yahoo.co.uk (Toni Fuente) Date: Wed, 19 Oct 2016 17:05:15 +0100 Subject: [Tutor] Subdividing config file by matching line from a file In-Reply-To: References: <20161019140640.GA20541@macarra> Message-ID: <20161019160515.GB20541@macarra> * Peter Otten <__peter__ at web.de> [2016-10-19 16:52:50 +0200]: > Date: Wed, 19 Oct 2016 16:52:50 +0200 > From: Peter Otten <__peter__ at web.de> > To: tutor at python.org > Subject: Re: [Tutor] Subdividing config file by matching line from a file > Organization: None > User-Agent: KNode/4.13.3 > Message-ID: > > Toni Fuente via Tutor wrote: > > > Hello everybody, > > > > I am trying to divide a configuration file (configs) in the form of: > > > > > > ServerAdmin webmaster at foo.com > > ServerName www.foo.com > > DocumentRoot /home/public/web/htdocs/foo.com > > ScriptAlias /cgi-bin/ /home/public/web/htdocs/foo.com/cgi-bin/ > > > > > > [...] > > > > > > ServerAdmin webmaster at bar.com > > ServerName www.bar.com > > DocumentRoot /home/public/web/htdocs/bar.com/ > > > > > > [...] > > > > > > into different individual config files for the different domains. > > > > In a different file (sites), I've got a list of domains. > > > > foo.com > > example.com > > blabla.com > > [...] > > > > I've approached this problem by creating first a list of all the config > > "chunks" with this piece of code: > > > > > > #!/usr/bin/python > > > > token = '\n' > > chunks = [] > > current_chunk = [] > > > > > > for line in open('configs'): > > if line.startswith(token) and current_chunk: > > # if line starts with token and the current chunk is not empty > > chunks.append(current_chunk[:]) # add not empty chunk to chunks > > current_chunk = [] # make current chunk blank > > # just append a line to the current chunk on each iteration > > current_chunk.append(line) > > > > chunks.append(current_chunk) # append the last chunk outside the loop > > > > > > Dividing the chunks of confg by blank line: token='\n' into a list of > > lists. > > > > And now I am stuck trying to iterate through the chunks list, and iterate > > through the sites file trying to find the "site" string and if found, > > print the entire "chunk", which will be send to a personal site > > configuration file. Like so: > > > > for item in chunks: > > #print item > > for line in open('sites'): > > #print line > > for i in item: > > if line not in i: > > continue > > else: > > print item > > break > > > > I don't get the results that I am expecting. Is is the right way to > > approach this problem? Any direction will be very helpful. > > > > Thank you in advance, > > > > You have to search all chunks for a specific site, i. e. you need the outer > loop to iterate over the sites and the inner loops (repeatedly) over the > chunks. It is easier to see the structure when you factor the site-search > into its own function: > > def find_chunk(site, chunks): > for chunk in chunks: > if any(site in line for line in chunk): > return chunk > return None # no appropriate chunk found > # (you might instead raise an Exception) > > > for line in open("sites"): > site = line.strip() > chunk = find_chunk(site, chunks) > if chunk is not None: > print "Site:", site > print "Config:" > print "".join(chunk) > else: > print >> sys.stderr, "no configuration for site", site > print "---" > > (If the number of chunks were huge you'd build some kind of lookup table > mapping site to chunk, but in your case this is hardly worthwile) > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor Thank you Peter, that help me a lot, I can see now better what I am doing. -- Toni S?lo la verdad os har? libres. -- San Juan. (Siglo I) Ap?stol cristiano. From elvclr at gmail.com Thu Oct 20 00:31:11 2016 From: elvclr at gmail.com (Betty Cruz) Date: Wed, 19 Oct 2016 23:31:11 -0500 Subject: [Tutor] Created map after opening file Message-ID: Hello, I'm new to python. I'm trying to create a map after reading a file. I have downloaded python 3, anaconda, and pycharm. I have written some code, but I'm having trouble reading the file...How do I read the file so that it reads the data and makes the map? My data is only in rows...the first row are the x's and the second row are the y's. Any help would be appreciated. I have tried to run the program. but I just get an error, saying that the directory for the file is not found. code: import numpy as np import matplotlib.pyplot as plt data= np.loadtxt('mat.dat') #data = np.genfromtxt('map.dat') # plot the first column as x, and second column as y #pl.plot(data[:,0], data[:,1], ?ro?) #pl.xlabel(?x?) #pl.ylabel(?y?) #pl.xlim(0.0, 90.0) #pl.ylim(10.0, 80.0) #pl.show() From alan.gauld at yahoo.co.uk Thu Oct 20 05:54:20 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 20 Oct 2016 10:54:20 +0100 Subject: [Tutor] Created map after opening file In-Reply-To: References: Message-ID: On 20/10/16 05:31, Betty Cruz wrote: > Hello, I'm new to python. Hello, welcome. > ...I'm trying to create a map after reading a file. What kind of "map" - that's a very generic term. Do you mean a geographic map using GIS data? If so is it some kind of image output that you want? Or is it a map as in Java? In other words a dictionary using Python-speak? Or is it a more general mapping of one value to another? > I have downloaded python 3, anaconda, and pycharm. For completeness which OS are you running? These imply you are into math/science so maybe its a more specific kind of map? But we really can't guess, you will need to tell us. You should not assume that everyone on the list will understand your questions if you use technical terms. You may get lucky and find a kindred soul but there's no guarantee so you really need to explain your problem in terms that most list readers can understand. (That, in turn, may even help you to understand it better yourself! :-) > I have written some code, but I'm having trouble reading the file...How do > I read the file so that it reads the data and makes the map? Unless this a ScyPy/NumPy specific kind of map you are probably going to have to split those activities into two. > My data is only in rows...the first row are the x's > and the second row are the y's. Can you send a sample, say 4-6 rows? > Any help would be appreciated. I have tried to run the program. but I just > get an error, saying that the directory for the file is not found. Always send the complete error text. The error messages are full of useful data but that doesn't help us if we can't see it. If it's complaining about the directory though that does suggest that it's a path issue - did you try specifying the full path to the file? > import numpy as np > import matplotlib.pyplot as plt > > data= np.loadtxt('mat.dat') What does 'data' look like at this point? Have you tried printing it? print(data) That's often the first step in debugging a problem. Most Python types will have some kind of readable representation from a print (although not all...) Check that what you got is what you expected. > #data = np.genfromtxt('map.dat') > # plot the first column as x, and second column as y > #pl.plot(data[:,0], data[:,1], ?ro?) > #pl.xlabel(?x?) > #pl.ylabel(?y?) > #pl.xlim(0.0, 90.0) > #pl.ylim(10.0, 80.0) > #pl.show() This looks like a straight plot of the data, is that what you meant by a "map"? If so then there is a good tutorial on using matplotlib on the SciPy site which should show you what you need. http://matplotlib.org/users/beginner.html The only difficulty may be in reading the data, but we can't help with that until we can see what it looks like. -- 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 From alan.gauld at yahoo.co.uk Thu Oct 20 13:13:34 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 20 Oct 2016 18:13:34 +0100 Subject: [Tutor] Created map after opening file In-Reply-To: References: Message-ID: <5808FB3E.5020307@yahoo.co.uk> Always use Reply All (Or Reply List) to reply to the tutor list... On 20/10/16 14:45, Betty Cruz wrote: > I had actually attached the map and how the data looked. I guess the > pictures didn't go through? I have added links. > The server often strips attachments, it's always better to include as text or provide a link if it's big. > > The data looks like this: > 10000 10000 10000 7367 7367 7367 > 10000 29410 29410 29410 29410 36101 So the points you want to plot are: (10000,10000), (10000,294210),(10000,29410)(again?), (7367,29410)... correct? > https://i.stack.imgur.com/tUvBj.png > > I have tried printing it out, but I just get this error: No such file > or directory: 'map.dat' Have you tried using the full path? eg: data = np.loadtxt(r'C:/myfolder/map.dat') Python is looking in the current working directory for the file and not finding it. > I added print (data) after data = np.loadtxt('map.dat'), but that > didn't work. Yes, that will only work once you get the file path sorted out. -- 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 From alan.gauld at alan-g.me.uk Thu Oct 20 13:45:38 2016 From: alan.gauld at alan-g.me.uk (Alan Gauld) Date: Thu, 20 Oct 2016 18:45:38 +0100 Subject: [Tutor] Fwd: Re: Created map after opening file Message-ID: <580902C2.2070805@alan-g.me.uk> Resending after mail error, apologies if you get two! ------------------------------------------- Always use Reply All (Or Reply List) to reply to the tutor list... On 20/10/16 14:45, Betty Cruz wrote: > I had actually attached the map and how the data looked. I guess the > pictures didn't go through? I have added links. > The server often strips attachments, it's always better to include as text or provide a link if it's big. > > The data looks like this: > 10000 10000 10000 7367 7367 7367 > 10000 29410 29410 29410 29410 36101 So the points you want to plot are: (10000,10000), (10000,294210),(10000,29410)(again?), (7367,29410)... correct? > https://i.stack.imgur.com/tUvBj.png > > I have tried printing it out, but I just get this error: No such file > or directory: 'map.dat' Have you tried using the full path? eg: data = np.loadtxt(r'C:/myfolder/map.dat') Python is looking in the current working directory for the file and not finding it. > I added print (data) after data = np.loadtxt('map.dat'), but that > didn't work. Yes, that will only work once you get the file path sorted out. -- 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 From kpalladino at e-windham.com Thu Oct 20 16:25:03 2016 From: kpalladino at e-windham.com (Karen Palladino) Date: Thu, 20 Oct 2016 16:25:03 -0400 Subject: [Tutor] Help please Message-ID: <007201d22b10$0ad4e040$207ea0c0$@e-windham.com> HI, I am new to python and programming for that matter. Basically, I don't know much at all. I have python on my p/c which was put there by a former co-worker who wrote a program that extracts bites of information to generate a report. The format of the text file used to extract the information has changed and therefore, the information is not be extracted and distributed properly. We are looking for someone to help fine tune the program, can anyone help us? Thank you, Karen Palladino The Windham Group, Inc. 363 West 22 Street New York, NY 10011 212-624-1132 From alan.gauld at yahoo.co.uk Thu Oct 20 20:15:53 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 21 Oct 2016 01:15:53 +0100 Subject: [Tutor] Help please In-Reply-To: <007201d22b10$0ad4e040$207ea0c0$@e-windham.com> References: <007201d22b10$0ad4e040$207ea0c0$@e-windham.com> Message-ID: On 20/10/16 21:25, Karen Palladino wrote: > I am new to python and programming for that matter. Basically, I don't know > much at all. I have python on my p/c which was put there by a former > co-worker who wrote a program that extracts bites of information to generate > a report. The format of the text file used to extract the information has > changed and therefore, the information is not be extracted and distributed > properly. > > > > We are looking for someone to help fine tune the program, can anyone help > us? This list can help you learn how to modify the program yourself, but it is not a job board. So if you are trying to find a programmer who can modify the program for you, you need to look somewhere else. (There are several; sites that specialize in Python jobs) If you do want to learn how to program in Python then there are many tutorials available for complete beginners (including mine, see below) There is a list here: https://wiki.python.org/moin/BeginnersGuide/NonProgrammers If you go down that route feel free to post any questions you may have here and we will try to answer them. -- 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 From ben+python at benfinney.id.au Thu Oct 20 20:50:12 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 21 Oct 2016 11:50:12 +1100 Subject: [Tutor] How to employ a Python programmer to help (was: Help please) References: <007201d22b10$0ad4e040$207ea0c0$@e-windham.com> Message-ID: <85bmyeh6ez.fsf@benfinney.id.au> "Karen Palladino" writes: > We are looking for someone to help fine tune the program, can anyone help > us? If you are looking to employ someone to work on the program, you can advertise a job position on the Python community's Job Board . -- \ ?I was trying to daydream, but my mind kept wandering.? ?Steven | `\ Wright | _o__) | Ben Finney From vkhatu at uwo.ca Thu Oct 20 22:08:36 2016 From: vkhatu at uwo.ca (Viraja Chandrashekhar Khatu) Date: Fri, 21 Oct 2016 02:08:36 +0000 Subject: [Tutor] Python 3.5.2 Installaton Question Message-ID: Hello, I have a quick question about installing Python 3.5.2 on my Windows 7 laptop. I already have Python 2.7.1 installed on my laptop. However, I now wish to switch to Python 3.5.2, which is the latest release. My question is: Do I have to completely uninstall Python 2.7.1 and then install Python 3.5.2? Or can I still install Python 3.5.2 keeping Python 2.7.1 untouched on my laptop? Even if the second option would work, what is recommended to be done so that both versions do not show any kind of interference while programming in Python? Kindly confirm at your earliest. Thanks and Regards Viraja Khatu From bharathks123 at yahoo.com Fri Oct 21 05:43:32 2016 From: bharathks123 at yahoo.com (bharath ks) Date: Fri, 21 Oct 2016 09:43:32 +0000 (UTC) Subject: [Tutor] Python 3.5.2 Installaton Question In-Reply-To: References: Message-ID: <2118366173.478577.1477043012578@mail.yahoo.com> Hello, You could you have multiple version of python on your system. It's not necessary to uninstall the older version. you can look at this link for more infoHow to run different python versions in cmd | | | | | | | | | | | How to run different python versions in cmd How can I configure windows command dialog to run different python versions in it? For example when I type pytho... | | | | ? Thanks & BR, Bharath Shetty On Friday, 21 October 2016 11:38 AM, Viraja Chandrashekhar Khatu wrote: Hello, I have a quick question about installing Python 3.5.2 on my Windows 7 laptop. I already have Python 2.7.1 installed on my laptop. However, I now wish to switch to Python 3.5.2, which is the latest release. My question is: Do I have to completely uninstall Python 2.7.1 and then install Python 3.5.2? Or can I still install Python 3.5.2 keeping Python 2.7.1 untouched on my laptop? Even if the second option would work, what is recommended to be done so that both versions do not show any kind of interference while programming in Python? Kindly confirm at your earliest. Thanks and Regards Viraja Khatu _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From badouglas at gmail.com Fri Oct 21 08:50:05 2016 From: badouglas at gmail.com (bruce) Date: Fri, 21 Oct 2016 08:50:05 -0400 Subject: [Tutor] a bit off topic.. - more of a high level arch question! Message-ID: Hi. Thinking of a situation where I have two "processes" running. They each want to operate on a list of files in the dir on a first come first operate basis. Once a process finishes with the file, it deletes it. Only one process operates on a file. I'm curious for ideas/thoughts. As far as I can tell, using some sort of PID/Lock file is "the" way of handling this. ProcessA looks to see if the PIDFile is in use, If it is, I wait a "bit" if the PIDFile is "empty", I set it an proceed --when I finish my work, i reset the PIDFile As long as both/all processes follow this logic, things should work, unless you get a "race" condition on the PIDFile.. Any thoughts on how you might handle this kind of situation, short of having a master process, that forks/spawns of children, with the master iterating through the list of files.. Thanks.. From nirajkumarpandey at gmail.com Fri Oct 21 05:44:47 2016 From: nirajkumarpandey at gmail.com (niraj pandey) Date: Fri, 21 Oct 2016 15:14:47 +0530 Subject: [Tutor] Python 3.5.2 Installaton Question In-Reply-To: References: Message-ID: Hi , In Linux I have multiple version of python on separate location and so far I do not see any issue . So I think you can also install multiple version of python on your window system as well. You may just need to provide separate installation directory path to install it on another location without overwrite the previous version. Thanks Niraj On Fri, Oct 21, 2016 at 7:38 AM, Viraja Chandrashekhar Khatu wrote: > Hello, > > > I have a quick question about installing Python 3.5.2 on my Windows 7 > laptop. > > > I already have Python 2.7.1 installed on my laptop. However, I now wish to > switch to Python 3.5.2, which is the latest release. My question is: > > > Do I have to completely uninstall Python 2.7.1 and then install Python > 3.5.2? Or can I still install Python 3.5.2 keeping Python 2.7.1 untouched > on my laptop? Even if the second option would work, what is recommended to > be done so that both versions do not show any kind of interference while > programming in Python? > > > Kindly confirm at your earliest. > > > Thanks and Regards > > > Viraja Khatu > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Success occurs when opportunity and preparation meet From dyoo at hashcollision.org Fri Oct 21 14:23:57 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 21 Oct 2016 11:23:57 -0700 Subject: [Tutor] a bit off topic.. - more of a high level arch question! In-Reply-To: References: Message-ID: > Thinking of a situation where I have two "processes" running. They > each want to operate on a list of files in the dir on a first come > first operate basis. Once a process finishes with the file, it deletes > it. > > Only one process operates on a file. > > I'm curious for ideas/thoughts. Hi Bruce, An inter-process locking approach seems straightforward: it allows us to make sure that only one process is running a particular section of code at once. In your case, this allows us to make sure the worker processes don't get mixed up when deciding what to work on next. I know that there's some built-in support for file locks in the standard library, but on brief glance, it looks a bit low-level. https://docs.python.org/3.6/library/fcntl.html#fcntl.lockf ... I wonder if there is a nicer API for this. I've been out of the loop in terms of what third-party Python libraries are in vogue these days, but let me do a few searches... Ok, the following library might be helpful: http://fasteners.readthedocs.io/en/latest/ http://fasteners.readthedocs.io/en/latest/examples.html#interprocess-locks Does anyone have experience with this "fasteners" library? It looks promising! It appears to provide a nice library for using lock files for inter-process synchronization; their example of interprocess locks seems straightforward. Good luck to you! From alan.gauld at alan-g.me.uk Fri Oct 21 13:05:58 2016 From: alan.gauld at alan-g.me.uk (Alan Gauld) Date: Fri, 21 Oct 2016 18:05:58 +0100 Subject: [Tutor] Fwd: Re: Fwd: Re: Created map after opening file In-Reply-To: References: Message-ID: <580A4AF6.9010702@alan-g.me.uk> Forwarding to list -------- Forwarded Message -------- I can now see my data. Current view: https://s15.postimg.org/ni570gxl7/pyscreenshot2.png Yes, you are correct on how the points are going to be plotted. My question is, how do you plot only rows on python? I found an example online, but the data is in columns. (http://www.ast.uct.ac.za/~sarblyth/pythonGuide/PythonPlottingBeginnersGuide.pdf, pg. 14). How do I change this particular part on the example so it reads the rows: pl.plot(data[:,0], data[:,1], ?ro?):: Or will this not work in this case? I was thinking of making two arrays like this: x=np.array [] and y=np.array[] and the inserting the data between the brackets, but then though wouldn't that defeat the purpose of the file? On Thu, Oct 20, 2016 at 12:45 PM, Alan Gauld > wrote: Resending after mail error, apologies if you get two! ------------------------------------------- Always use Reply All (Or Reply List) to reply to the tutor list... On 20/10/16 14:45, Betty Cruz wrote: > I had actually attached the map and how the data looked. I guess the > pictures didn't go through? I have added links. > The server often strips attachments, it's always better to include as text or provide a link if it's big. > > The data looks like this: > 10000 10000 10000 7367 7367 7367 > 10000 29410 29410 29410 29410 36101 So the points you want to plot are: (10000,10000), (10000,294210),(10000,29410)(again?), (7367,29410)... correct? > https://i.stack.imgur.com/tUvBj.png > > I have tried printing it out, but I just get this error: No such file > or directory: 'map.dat' Have you tried using the full path? eg: data = np.loadtxt(r'C:/myfolder/map.dat') Python is looking in the current working directory for the file and not finding it. > I added print (data) after data = np.loadtxt('map.dat'), but that > didn't work. Yes, that will only work once you get the file path sorted out. -- 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 at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From raghunadhprasad at gmail.com Fri Oct 21 15:37:06 2016 From: raghunadhprasad at gmail.com (Raghunadh) Date: Fri, 21 Oct 2016 14:37:06 -0500 Subject: [Tutor] Python 3.5.2 Installaton Question Message-ID: Hi Niraj, Try virtual environments in python. More helpful to deal with multiple versions. Regards Raghunadh On October 21, 2016, at 12:10 PM, niraj pandey wrote: Hi , In Linux I have multiple version of python on separate location and so far I do not see any issue . So I think you can also install multiple version of python on your window system as well. You may just need to provide separate installation directory path to install it on another location without overwrite the previous version. Thanks Niraj On Fri, Oct 21, 2016 at 7:38 AM, Viraja Chandrashekhar Khatu wrote: > Hello, > > > I have a quick question about installing Python 3.5.2 on my Windows 7 > laptop. > > > I already have Python 2.7.1 installed on my laptop. However, I now wish to > switch to Python 3.5.2, which is the latest release. My question is: > > > Do I have to completely uninstall Python 2.7.1 and then install Python > 3.5.2? Or can I still install Python 3.5.2 keeping Python 2.7.1 untouched > on my laptop? Even if the second option would work, what is recommended to > be done so that both versions do not show any kind of interference while > programming in Python? > > > Kindly confirm at your earliest. > > > Thanks and Regards > > > Viraja Khatu > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Success occurs when opportunity and preparation meet _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From pierre at averseng.re Sat Oct 22 21:39:21 2016 From: pierre at averseng.re (Pierre-Michel Averseng) Date: Sun, 23 Oct 2016 05:39:21 +0400 Subject: [Tutor] Python 3.5 installation beside Python 2.3 on Windows 7 In-Reply-To: References: Message-ID: Le 22/10/2016 ? 20:00, tutor-request at python.org a ?crit : > Python 3.5.2 Installaton Question (niraj pandey) > I already have Python 2.7.1 installed on my laptop. However, I now wish to > switch to Python 3.5.2, which is the latest release. My question is: > > > Do I have to completely uninstall Python 2.7.1 and then install Python > 3.5.2? Or can I still install Python 3.5.2 keeping Python 2.7.1 untouched > on my laptop? For Windows (including XP, Vista, 7, and 8), Python comes as a self-installer MSI program file?simply double-click on its file icon, and answer Yes or Next at every prompt to perform a default install. The default install includes Python?s docu- mentation set and support for tkinter (Tkinter in Python 2.X) GUIs, shelve data- bases, and the IDLE development GUI. Python 3.3 and 2.7 are normally installed in the directories C:\Python33 and C:\Python27 though this can be changed at install time. Best Regards Pierre Averseng in South-Western Indian Ocean From eryksun at gmail.com Sat Oct 22 23:09:12 2016 From: eryksun at gmail.com (eryk sun) Date: Sun, 23 Oct 2016 03:09:12 +0000 Subject: [Tutor] Python 3.5 installation beside Python 2.3 on Windows 7 In-Reply-To: References: Message-ID: On Sun, Oct 23, 2016 at 1:39 AM, Pierre-Michel Averseng wrote: > Le 22/10/2016 ? 20:00, tutor-request at python.org a ?crit : > >> Do I have to completely uninstall Python 2.7.1 and then install Python >> 3.5.2? Or can I still install Python 3.5.2 keeping Python 2.7.1 untouched >> on my laptop? > > For Windows (including XP, Vista, 7, and 8), Python comes as a > self-installer MSI program file?simply double-click on its file icon, and answer > Yes or Next at every prompt to perform a default install. The default install > includes Python?s documentation set and support for tkinter (Tkinter in Python > 2.X) GUIs, shelve databases, and the IDLE development GUI. Python 3.3 and > 2.7 are normally installed in the directories C:\Python33 and C:\Python27 > though this can be changed at install time. 3.5 doesn't support Windows XP. It also switched to using executable installers that are built using the WiX toolset. The web installer downloads up to 22 MSI packages on demand. Even the 'offline' installer has to download the MSIs for the debug binaries, since they're not commonly installed and including them would make the offline installer substantially larger. Also, the default installation targets have changed to "%ProgramFiles[(x86)]%\Python35[-32]" for all-users installs and "%LocalAppData%\Programs\Python\Python35[-32]" for per-user installs. From kadir.sertcanli at gmail.com Mon Oct 24 10:40:08 2016 From: kadir.sertcanli at gmail.com (Kadir Sertcanli) Date: Mon, 24 Oct 2016 16:40:08 +0200 Subject: [Tutor] Python Message-ID: Hi! I have a function that I want to plot depending on a parameter (?a?), I looked in the beginners guide but couldn?t fint what I wanted. I know how to put the axis etc. but I don?t know how to involve my function which is V=-(ba^-1 + ca^2) where I have different values for b and c, so the function I want to plot is depending on a. Kind regards Kadir Sertcanli From alan.gauld at yahoo.co.uk Mon Oct 24 12:55:43 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 24 Oct 2016 17:55:43 +0100 Subject: [Tutor] Python In-Reply-To: References: Message-ID: On 24/10/16 15:40, Kadir Sertcanli wrote: > Hi! I have a function that I want to plot depending on a parameter (?a?), OK, But you will need to give us some more details. > I looked in the beginners guide Which beginner's guide are you using? Plotting is not something normally covered in a Python beginner's guide - it's not part of standard Python, you usually need some extra modules to do that. > I know how to put the axis etc. Which plotting module are you using? Or are you trying to do it using a GUI toolkit (if so which one?)? > but I don?t know how to involve my function which is > V=-(ba^-1 + ca^2) where I have different values for b and c > so the function I want to plot is depending on a. Normally you would generate a set of data pairs and then plot those. Do you know how to create a list of values based on your input 'a' values? for example if I wanted to plot the first 10 integer squares I'd generate a list of values something like: data = [(n,n**n) for n in range(10)] That would give me a data list that looked like: [(0,0),(1,1),(2,4),(3,9),...(9,81)] I could then plot each pair on a graph or chart of some sort. -- 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 From steve at pearwood.info Mon Oct 24 13:07:50 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 25 Oct 2016 04:07:50 +1100 Subject: [Tutor] Python In-Reply-To: References: Message-ID: <20161024170749.GC15983@ando.pearwood.info> On Mon, Oct 24, 2016 at 04:40:08PM +0200, Kadir Sertcanli wrote: > Hi! I have a function that I want to plot depending on a parameter > (?a?), I looked in the beginners guide but couldn?t fint what I > wanted. I know how to put the axis etc. but I don?t know how to > involve my function which is V=-(ba^-1 + ca^2) where I have different > values for b and c, so the function I want to plot is depending on a. How are you plotting the function? What software are you using? How do you put the axis on? What part do you not understand? Show us the code that you have. Don't expect us to guess what you are doing. -- Steve From Joaquin.Alzola at lebara.com Mon Oct 24 12:16:12 2016 From: Joaquin.Alzola at lebara.com (Joaquin Alzola) Date: Mon, 24 Oct 2016 16:16:12 +0000 Subject: [Tutor] Python In-Reply-To: References: Message-ID: >Hi! I have a function that I want to plot depending on a parameter (?a?), I looked in the beginners guide but couldn?t fint what I wanted. I know how to put the axis etc. but I don?t know how to involve my function which is V=-(ba^-1 + ca^2) where I have >different values for b and c, so the function I want to plot is depending on a. You need to put your code. This email is confidential and may be subject to privilege. If you are not the intended recipient, please do not copy or disclose its content but contact the sender immediately upon receipt. From elliott.andrews1998 at gmail.com Mon Oct 24 17:36:55 2016 From: elliott.andrews1998 at gmail.com (Elliott Andrews) Date: Tue, 25 Oct 2016 10:36:55 +1300 Subject: [Tutor] Python v3 Tkinter GUI program Message-ID: Hi there, I am making a program in python based on a Subway operation. All descriptions and comments codes are provided in the attached program. I've been using IDLE to run the program and it seems to work the way I want it too. However I have heard from many, that global variables are bad practise in any programming language, and so I want to basically replace all my global variables with another variable that does the same thing. The problem is, some data is entered and then when the data is submitted, the GUI window terminates and automatically re-opens for another data entry. I need some sort of variable to store some data while the program resetts itself. Sorry is this sounds really broad, and I am happy to clarify and points. -------------- next part -------------- ''' Author: Elliott Andrews, Date: 22/09/16, Programmed with: IDLE 3.5.1 via Python 3.5.1 and Tk 8.6.4 Program Title: "Phone Ordering System for SUBS R US." Program Description: This program is designed for a company (e.g Subway) to enter in an order for a sub as a phone operator. The phone operater will ask for customer infomation, ingedients to be put in the sub and then order it. The phone operator will then ask the customer if they wish to cancel the order and if they want to order another sub. After all subs have been ordered, the phone operator will tell the customer the total cost of all the subs orders and then exit the prgoram''' from tkinter import * #Importing GUI from tkinter library to display in window. import time #Importing time controls for diagnostic messages (readability). #Global variables (major) have to be used to pass 'cancelled' and 'total_cost' through whole application. #This will ensure when window is told to destory, variables will be kept for a maximum of 5 future orders and will avoid any 'Traceback' errors. #Not using global variables or other means such as (.get) will not work because when window is told to destory, a new window instance is created, defaulting and resetting orig variables. global cancelled global total_cost total_cost = 0 #Setting total cost (for all orders - max 5) to 0. class Startup: #First class 'Startup' which will run diagnostic checks to make sure program will run. print("Current python version: 3.5.1 \nTk version: 8.6.4") #Recommended version to run python and tkinter in. if total_cost != 0: #If total_cost is not equal to 0, then... This variable has to be set to 0, as it will be added too, each time a order is added. print("Sorry, the application failed to start. Please make sure you have the latest python version and try again. \n Error: Failed to reset top variabe (Total_Cost)") else: #Otherwise, continue as normal. print("Application starting...") time.sleep (2) #Giving time for operator/user to see the status for application startup. class GUI(Frame, Startup): #Second class 'GUI' which will run the main display (visual elements and will continue from first class). def __init__(self, master): #Initalising the GUI application. super(GUI, self).__init__(master) #For use with lots of mutiple instances of __init__. Future use for parenting within 'master'. self.grid() #Defining layout for GUI (grid method), could also use pack. self.clear_variables() #Stating all functions with 'def'... self.cancel() self.create_widgets() self.check_address() self.show_order() self.close_window() def close_window(self): #Defining the process to close the window, reset cancelled variable equal to 0, then quit. global cancelled cancelled = 0 root.quit() #Will prepare a quit function if needed. def clear_variables(self): #Defining the process to set all other minor variables to proper type and to set them to None or 0 where appropriate. self.ordertype = StringVar() #StringVar is ideal for letters... self.cusName = StringVar() self.cusAddress = StringVar() self.cusPhone = StringVar() #Can use IntVar for phone number, but for textbox display only, StringVar is ok. self.breads_var = StringVar() self.cheeses_var = StringVar() self.sauces_var = StringVar() self.ordertype.set (None) #Has a 'None' value, similar to 'Null'. self.cusName.set (None) self.cusAddress.set (None) self.cusPhone.set (None) self.breads_var.set (None) self.cheeses_var.set (None) self.sauces_var.set (None) self.cost = 0 #Since self.cost is to be a integer, integer operations must be used root.quit() #Will prepare a quit function if needed. def cancel(self): #Defining the process for cancelling the order, to set all other minor variables to proper type and to set them to None or 0 where appropriate. #This process allows orders that have been cancelled to continue the program. self.ordertype = StringVar() self.cusName = StringVar() self.cusAddress = StringVar() self.cusPhone = StringVar() self.breads_var = StringVar() self.cheeses_var = StringVar() self.sauces_var = StringVar() self.ordertype.set (None) self.cusName.set (None) self.cusAddress.set (None) self.cusPhone.set (None) self.breads_var.set (None) self.cheeses_var.set (None) self.sauces_var.set (None) global total_cost total_cost-=self.cost #Following on from when order is cancelled, subtract the cost of that order (since cancelled). self.cost = 0 global cancelled #If cancel is true (when equal to 1) then do cancel cancelled = 1 root.quit() #A quit function if needed def create_widgets(self): #Define the function for 'create_widgets'. Widgets are all the objects/clickables that appear on the GUI. #Stored lists. These store the ingredients for the subs and will be listed on the GUI for the user to choose from. breads = ["White", "Wheat"] #"Multigrain" - Can be added to list, to see GUI respond to new ingredients. cheeses = ["Swiss", "Cheddar"] #Edam - Can be added... sauces = ["Mayo"] #Honey Mustard - Can be added... #Create a simple label (text format) which will display 'text=...' in a certain table position. Text will align to the left (W = West). Label(self, text = "Welcome! Please enter customer's infomation and sub-sandwich ingredients/choices. Note: All fields and required below..." ).grid(row = 0, column = 0, columnspan = 3, sticky = W) Label(self, text = "How will the customer receive the order?", ).grid(row = 1, column = 0, sticky = W) #Using the radiobutton operation to create a radio button. Only two options needed so list display is not really needed. Radiobutton(self, text = "Delivery ($3)", #Text for radio button to display. variable = self.ordertype, #Variable to assign value to. value = "Delivery", #Value to be used as variable. command = self.check_address, #When radio button is presses, go to module 'check_address'. ).grid(row = 2, column = 0, sticky = W) Radiobutton(self, text = "Pickup", variable = self.ordertype, value = "Pickup", command = self.check_address, ).grid(row = 3, column = 0, sticky = W) Label(self, text = "Customer's Name:", ).grid(row = 4, column = 0, sticky = W) self.cusName = Entry(self) self.cusName.grid(row = 5,column = 0, sticky = W) Label(self, text = "Customer's Address:", ).grid(row = 6, column = 0, sticky = W) self.cusAddress = Entry(self) self.cusAddress.grid(row = 7,column = 0, sticky = W) Label(self, text = "Customer's Phone Number:", ).grid(row = 8, column = 0, sticky = W) self.cusPhone = Entry(self) self.cusPhone.grid(row = 9, column = 0, sticky = W) Label(self, text = "Bread Type ($2):", ).grid(row = 10, column = 0, sticky = W) self.breads_btns = [] #Stating a empty list to be filled with ingredients from lists above (i.e bread = ...) for i in range(len(breads)): #Let 'i' be the variable to find the range within the length of the list 'breads'. Essentialy will gather all bread options. rb = Radiobutton(self, variable = self.breads_var, value = breads[i] , anchor = W, text = breads[i]) #List all breads as radiobuttons with their assigned names in terms of 'i'. self.breads_btns.append(rb) #Attach these radiobuttons to 'rb'. rb.grid(row =(i + 11), column = 0, sticky = W) #State 'rb' to use grid. Start from row 11 and list breads downwards and align to left. Label(self, text = "Cheeses ($1):", #Copy and pasted from above as cheese's will use same code as bread's. ).grid(row = 10, column = 1, sticky = W) self.cheeses_btns = [] for i in range(len(cheeses)): rb = Radiobutton(self, variable = self.cheeses_var, value = cheeses[i], anchor = W, text = cheeses[i]) self.cheeses_btns.append(rb) rb.grid(row =(i + 11), column = 1, sticky = W) Label(self, text = "Salads ($2):", ).grid(row = 33, column = 0, sticky = W) self.salads_lettuce = BooleanVar() #Defining salads as a BooleanVar (True or False) since checkbuttons are needed to be setup differetly to radiobuttons. #Checkbuttons can store many values opposed to radiobuttons which only store one, hence why my checkbuttons are listed seperatly. Checkbutton(self, text = "Lettuce", #Text to display next to checkbutton. variable = self.salads_lettuce, #Variable to be true when checkbutton is clicked. ).grid(row = 34, column = 0, sticky = W) #To be placed on grid at row 34, aligned left. self.salads_tomato = BooleanVar() Checkbutton(self, text = "Tomato", variable = self.salads_tomato, ).grid(row = 35, column = 0, sticky = W) self.salads_capsicum = BooleanVar() Checkbutton(self, text = "Capsicum", variable = self.salads_capsicum, ).grid(row = 36, column = 0, sticky = W) Label(self, text = "Meats ($4):", ).grid(row = 33, column = 1, sticky = W) self.meats_bacon = BooleanVar() #Same method for meats so copy and pasted, as meats are checkboxes as well. Checkbutton(self, text = "Bacon", variable = self.meats_bacon, ).grid(row = 34, column = 1, sticky = W) self.meats_salami = BooleanVar() Checkbutton(self, text = "Salami", variable = self.meats_salami, ).grid(row = 35, column = 1, sticky = W) self.meats_ham = BooleanVar() Checkbutton(self, text = "Ham", variable = self.meats_ham, ).grid(row = 36, column = 1, sticky = W) Label(self, text = "Sauces ($1):", ).grid(row = 55, column = 0, sticky = W) self.sauces_btns = [] for i in range(len(sauces)): #Copy and pasted from above as sauces's will use same code as cheese's. rb = Radiobutton(self, variable = self.sauces_var, value = sauces[i], anchor = W, text = sauces[i]) self.sauces_btns.append(rb) rb.grid(row =(i + 56), column = 0, sticky = W) Button(self, #Create a button by defing a button function. text = "Show Order", #Text to display on the button command = self.show_order, #When button is pressed, go to show_order module (to display summary message by refresh). ).grid(row = 60, column = 0, sticky = W) #To be placed on grid at row 60, aligned to left. Button(self, text = "Cancel Order", command = self.cancel, #When button is pressed, go to cancel module (to close current window and start again for another order). ).grid(row = 60, column = 1, sticky = W) Button(self, text = "Save and order another sub! (Max 5)", command = self.close_window, #When button is pressed, go to close_window module (to close window, save cost of sub and to order another sub). ).grid(row = 60, column = 2, sticky = W) Button(self, text = "Finished? Exit program", command = exit, #When button is pressed, simply exit program (prompt will appear asking user to confirm to kill program). ).grid(row = 60, column = 3, sticky = W) def check_address(self): #Defining the process to grey out option for filling in address, when 'pickup' is selected. orderselection[item_ct] = self.ordertype.get() #Get the value for variable self.ordertype to determine if pickup or delivery is selected. #Then put that value in another variable 'orderselection', to be appended to the orderselction list (item count). if orderselection[item_ct] == "Pickup": #If statement, if orderselction has been choosen as 'pickup' then... self.cusAddress['state'] = DISABLED #Set self.cusAddress (entry box for address) to be disabled (grey out). Label(self, state = DISABLED, #Also set the label for Customer's Address to be disabled (grey out). text = "Customer's Address:", ).grid(row = 6, column = 0, sticky = W) #Overwrite exisitng label at grid location row 6, column 0 to grey out. elif orderselection[item_ct] == "Delivery": #Else-if statement, elif orderselction has been choosen as 'delivery' then... self.cusAddress['state'] = NORMAL #Set self.cusAddress (entry box for address) to be back to normal (un-grey). Label(self, state = NORMAL, #Also set the label for Customer's Address to be back to normal (un-grey). text = "Customer's Address:", ).grid(row = 6, column = 0, sticky = W) #Overwrite exisitng label at grid location row 6, column 0 to un-grey. else: #Else statement, if none of these if statments are true, then display the message in IDLE... print("A orderselection has not been choosen") def show_order(self): #Defining the process to display all order infomation in text box and to calculate prices of all items selected. saladschoice[item_ct] = "" #Setting items, if they have selected a ceratin ingredient/item then assign to saladschoice list with relation to item count [item_ct]. if self.salads_lettuce.get(): #If self.salads_lettuce has the value lettuce selected, then add lettuce to the list to be displayed. saladschoice[item_ct] += "Lettuce, " #Text to be added on, with a comma and space for other salads (tidy formating). if self.salads_tomato.get(): saladschoice[item_ct] += "Tomato, " #Copy and paste above if self.salads_capsicum.get(): saladschoice[item_ct] += "Capsicum, " #Copy and paste above meatschoice[item_ct] = "" #Setting items, if they have selected a ceratin ingredient/item then assign to meatschoice list with relation to item count [item_ct]. if self.meats_bacon.get(): #If self.meats_bacon has the value bacon selected, then add bacon to the list to be displayed. meatschoice[item_ct] += "Bacon, " if self.meats_salami.get(): meatschoice[item_ct] += "Salami, " #Copy and paste above if self.meats_ham.get(): meatschoice[item_ct] += "Ham, " #Copy and paste above orderselection[item_ct] = self.ordertype.get() #Process of actual assignment from ingredients selected to their defined list with relation to item count (item_ct). cname[item_ct] = self.cusName.get() caddress[item_ct] = self.cusAddress.get() cphone[item_ct] = self.cusPhone.get() breadchoice[item_ct] = self.breads_var.get() cheesechoice[item_ct] = self.cheeses_var.get() #Note that salads and meats do not need a get operation as they have already been performed above. Salads and meats once again need to get each value #individually, to display mutiple values selected, meaning several checks are needed for each. saucechoice[item_ct] = self.sauces_var.get() orderselection.append('') #Append functions for storing ingredients in lists. Currently program only displays total cost of all orders who have ordered many subs (max of 5). #However extra code below will make it easy if this program was to be extended in the future to show ingredients of all subs ordered for one summary page. #For this particuar program, this functionality is not needed, but the code here would be able to add extra functionality if desired. cname.append('') #These append function are telling all values using that are using the 'get' operation to assign to the variable with relation to [item_ct] #Therefor enabling these statments here to attach/add all value into the list. caddress.append('') cphone.append('') breadchoice.append('') cheesechoice.append('') saladschoice.append('') meatschoice.append('') saucechoice.append('') self.results_txt = Text(self, width = 60, height = 15, wrap = WORD) #Creating the textbox as self.results_txt. #Setting height and width and wraping text so text will appear on next line instead of going off the page. self.results_txt.grid (row = 61, column = 0) #Placment of text box will be on grid, on row 61, column 0. message = "Transportation of sub-sandwich to customer: " #Display first statment of message text... message += orderselection[item_ct] #Add onto previous statement, the ordertype to display. message += "\nCustomer's Name: " #And so on... message += cname[item_ct] message += "\nCustomer's Address: " message += caddress[item_ct] message += "\nCustomer's Phone: " message += cphone[item_ct] message += "\nBread Type: " message += breadchoice[item_ct] message += "\nCheese Type: " message += cheesechoice[item_ct] message += "\nSalads Selected: " message += saladschoice[item_ct] message += "\nMeats Selected: " message += meatschoice[item_ct] message += "\nSauces Selected: " message += saucechoice[item_ct] #Messages above will only display if... #This long if statment has been created for purposes of validation, meaning the customer must at least enter a certain amount of infomation (seen below) #TO be able to actually order (e.g It is no good someone ordering a sub if no ingredients are selected!) #!= stament mean if something is not equal to something then... (i.e meaning the customer has to select something) and 'and' is to add another condition #instead of having mutiple if staments. if orderselection[item_ct] != "None" and cname[item_ct] != "None" and breadchoice[item_ct] != "None" and cheesechoice[item_ct] != "None" and saucechoice[item_ct] != "None": if orderselection[item_ct] == "Delivery": #Add a delivery cost of 3 to self.cost variable if delivery is selected. #self.cost is the cost of each sub ordered, it will be used later on to add all costs together. self.cost += 3 else: print("Delivery/Pickup has not been selected, add a cost of $3 if Delivery") # In theory it is not possible for the program to run this statment because of the validation statment, but is good practise to have a secondary #validation statment, if somehow the first one shall fail. if breadchoice[item_ct] != "None": self.cost += 2 #If breadchoice does not equal none (i.e a bread has been selected) then add a cost of 2. else: print("A bread is not selected and costs $2") if cheesechoice[item_ct] != "None": self.cost += 1 #And so on... else: print("A cheese is not selected and costs $1") if saladschoice[item_ct] != "": self.cost += 2 #Any type of salads will cost $2, meaning the salad cost is one of the few options which will have (each cost charge) #(e.g If I order just lettuce, the cost is $2, if order lettuce, tomato and capsicum the cost is still $2) else: print("A salad/s is not selected, all selected cost $2") if meatschoice[item_ct] != "": self.cost += 4 else: print("A meat/s is selected, all selected cost $4") if saucechoice[item_ct] != "None": self.cost += 1 message += "\n\nCost of this sub: $" #Since if all staments have added all costs sucessfully then we can display the total below: message += str(self.cost) #Converting integer into stringvar to display in text box. message += "\n\nTotal overall cost: $" global total_cost #Stating the total_cost variable total_cost=total_cost+self.cost #Adding the single cost to the total cost(which will keep value as next sub is ordered). message += str(total_cost) #Converting integer into stringvar to display in text box. else: print("A sauce has not been selected, and costs $1") else: print("Program is running through validation checks... Complete!") self.results_txt.delete(0.0, END) #Stating the end of the textbox message self.results_txt.insert(0.0, message) #Will insert all variables stated as 'message' into text box. choice = 0 #This is the number of subs ordered (will start as 0, since this is the deafult order for counting (e.g 0,1,2,3)) item_ct=0 #This is also the number of subs ordered but will be used for counting till a maximum of 5. orderselection = [] #Again these statments need to be listed as all items and ingredients need to be saved before another sub is to be ordered. orderselection.append('') #Confirming that the above items have been ordered, they are put in the list once more. cname = [] cname.append('') caddress = [] caddress.append('') cphone = [] cphone.append('') breadchoice = [] breadchoice.append('') cheesechoice = [] cheesechoice.append('') saladschoice = [] saladschoice.append('') meatschoice = [] meatschoice.append('') saucechoice = [] saucechoice.append('') while item_ct < 5: #To run program one again, the ending and restarting functions have all been put in a while item_ct (subs order count is less than 5) #(i.e 4,3,2,1 and 0) global cancelled #Stating the cancelled variable, to reset itself, so when the program restarts, it won't keep cancelling in on itself, repeating. cancelled=0 root = Tk() #The actual statment which opens the window, providing there is an import statment for 'tkinter'. toplevel = root.winfo_toplevel()#Setting window header to attach to top of screen (first half of making window maximised) toplevel.wm_state('zoomed')#Setting inner window to stretch window to all sides of screen (second half of making window maximised) #Two above statments automatically will maximise window when program starts. root.title("Phone Ordering System - SUBS R US") #Text title for the window to display. app = GUI(root) #Main application is defined in class, GUI with respect to 'root'. root.mainloop() #Enables program to repeat in a loop. root.destroy() #Will close the window. print("You have finished order number",str(item_ct)) if cancelled==0: item_ct+=1 #Adding 1 to item_ct (sub order number) if item_ct > 4: #When tem_ct is more than 4, then a maximum of 5 subs has been ordered, the program should have been closed and a summary statement #Will appear in IDLE. print("The program has ended automatically as the maximum of 5 subs has been ordered") print("Please wait, we are calculating your order total...") time.sleep (5) #Giving a time of 5 seconds or the user to read. print("You have ordered a maximum of 5 subs.") print("The total cost of all subs ordered is $",str(total_cost)) else: #If item_cut is not > 4 the 'continue' the program (begin program again). print("Ready for a new order!") continue From jay.talbot at gmail.com Mon Oct 24 18:36:44 2016 From: jay.talbot at gmail.com (Jay Talbot) Date: Mon, 24 Oct 2016 18:36:44 -0400 Subject: [Tutor] PyctvhccTV TtV v.:vgvon v3 Tkinter GgUI program Message-ID: Qk. vv"::.: On Oct 24, 2016 6:08 PM, "Elliott Andrews" wrote: Hi there, I am making a program in python based on a Subway operation. All descriptions and comments codes are provided in the attached program. I've been using IDLE to run the program and it seems to work the way I want it too. However I have heard from many, that global variables are bad practise in any programming language, and so I want to basically replace all my global variables with another variable that does the same thing. The problem is, some data is entered and then when the data is submitted, the GUI window terminates and automatically re-opens for another data entry. I need some sort of variable to store some data while the program resetts itself. Sorry is this sounds really broad, and I am happy to clarify and points. _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From alan.gauld at yahoo.co.uk Mon Oct 24 18:41:41 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 24 Oct 2016 23:41:41 +0100 Subject: [Tutor] Python v3 Tkinter GUI program In-Reply-To: References: Message-ID: On 24/10/16 22:36, Elliott Andrews wrote: > Hi there, I am making a program in python based on a Subway operation. All > descriptions and comments codes are provided in the attached program. Normally attachments are deleted by the server although yours seems to have gotten through (to me at least). Its best to post code in the body of the mail although in your case that's a lot of code so maybe a pastebin would be better. Anyways.... > been using IDLE to run the program and it seems to work the way I want it > too. OK, But you should always test GUIs outside of an IDE, after all thats how they will likely be run in the real world and while IDEs are great development tools they often distort the environment in subtle ways that can change how things behave. > However I have heard from many, that global variables are bad practise in > any programming language, and so I want to basically replace all my global > variables with another variable that does the same thing. You need to understand why they are bad practice. In the real world most non-trivial programs will have a few global variables (even if its just an instance of a top level class). The main problems with globals is that it is very hard to keep track of what is changing them and when. Also they make your code almost unusable in any other context since you need to replicate all the variables. One trivial way to do it in your case is to put them inside the GUI class. That's still got a lot of the same problems as globals but at least you can reuse the class without issues. [incidentally you don't need to label your global variables as global outside of the functions where they are used. The global keyword is a way of indicating which globals are used by a given function, it is not an indication to the rest of the program that a variable is global.] > The problem is, some data is entered and then when the data is submitted, > the GUI window terminates and automatically re-opens for another data > entry. I need some sort of variable to store some data while the program > resetts itself. The usual solution in GUI programs is not to kill the window but merely to hide it. You can then change the display values and reshow it again as needed. That way the "global" variables are still available. In Tkinter the hide method is called withdraw(). To redisplay it use the deiconify() method, and if necessary the lift() method to raise it to the top of the window stack. I can't help but mention the way you build your message strings. You should look at string formatting, it is usually a cleaner and more efficient solution that using the += operator on strings. The latter involves an awful lot of copying of strings and while you only do it about 20 times it would be better practice to insert the data elements using formatting. There are a lot of other comments I could make about the code but for now those pointers should move you forward. -- 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 From ben+python at benfinney.id.au Mon Oct 24 19:01:12 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 25 Oct 2016 10:01:12 +1100 Subject: [Tutor] Attaching program text to messages (was: Python v3 Tkinter GUI program) References: Message-ID: <85h981e4hz.fsf_-_@benfinney.id.au> Alan Gauld via Tutor writes: > On 24/10/16 22:36, Elliott Andrews wrote: > > All descriptions and comments codes are provided in the attached > > program. > > Normally attachments are deleted by the server although yours > seems to have gotten through (to me at least). I think because it is (declared by Elliott's mail user-agent to be) a text attachment, it survives to the mailing list. > Its best to post code in the body of the mail although in your case > that's a lot of code so maybe a pastebin would be better. A text attachment (provided you ensure it is declared that way, as Elliott's message did) seems a better way. If it fails, we all know immediately, and it can be retried. A pastebin's failure mode (some reader can't access for whatever reason) is more likely to appear later, when someone wants to refer back to the message. So I'd say that is inferior to attaching the program text. -- \ ?Now Maggie, I?ll be watching you too, in case God is busy | `\ creating tornadoes or not existing.? ?Homer, _The Simpsons_ | _o__) | Ben Finney From alan.gauld at yahoo.co.uk Mon Oct 24 19:27:25 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 25 Oct 2016 00:27:25 +0100 Subject: [Tutor] Python v3 Tkinter GUI program In-Reply-To: References: Message-ID: On 24/10/16 22:36, Elliott Andrews wrote: > Sorry is this sounds really broad, and I am happy to clarify and points. Sorry I just noticed another point that I can't overlook. You have code/comment: root = Tk() #The actual statment which opens the window, toplevel = root.winfo_toplevel() #Setting window header # to attach to top of screen (first half of # making window maximised) This is not how best to maximise a window. First you should find that toplevel is the same as root. ie toplevel == root is True. So instead of: toplevel.wm_state('zoomed') #Setting inner window to stretch You should be able to do root.wm_state('zoomed') instead. Although you don't strictly need the wm_ prefix since Tkinter provides the state() shortcut: root.state('zoomed') Except that doesn't work for me and I get an error about 'zoomed' being an invalid choice. The more usual way is to set the geometry to the screen size: top = Tk() top.withdraw() # hide the window sh = top.winfo_screenheight() sw = top.winfo_screenwidth() top.geometry("%sx%s" % (sw,sh)) # resize it to full screen top.deiconify() # show the resized window [The hide/show sequence is because if the window layout is complex it will be redrawn much more quickly and without any flickering if you hide/show.] Finally, be aware that maximising a window is considered bad practice in modern GUI design for two reasons: 1) Modern OS allow users to multi-task and grabbing the whole screen to yourself is a bit greedy and makes it very annoying to the user. I have a 32 inch monitor precisely because I want to see (say) my browser, email and spreadsheet all at the same time! 2) Given that screens can range widely in size it is almost impossible to guarantee that your widget layouts and fonts will be usable on every screen. (compare a 1024x768 netbook display with a 4096x2160 4K video monitor) 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 From alan.gauld at yahoo.co.uk Mon Oct 24 19:34:05 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 25 Oct 2016 00:34:05 +0100 Subject: [Tutor] Attaching program text to messages In-Reply-To: <85h981e4hz.fsf_-_@benfinney.id.au> References: <85h981e4hz.fsf_-_@benfinney.id.au> Message-ID: On 25/10/16 00:01, Ben Finney wrote: > I think because it is (declared by Elliott's mail user-agent to be) a > text attachment, it survives to the mailing list. That might be the reason. > A text attachment (provided you ensure it is declared that way, as > Elliott's message did) seems a better way. If it fails, we all know > immediately, and it can be retried. That's true if it always survives. It will be interesting to see if the attachment is accessible from the archives... OK, It shows the text appended to the message so that does indeed seem the best option. Now, how do we educate everyone on how to specify and use a text attachment? (This is a serious question BTW since we can add it to the tutor welcome/usage message.) -- 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 From ben+python at benfinney.id.au Mon Oct 24 19:50:44 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 25 Oct 2016 10:50:44 +1100 Subject: [Tutor] Attaching program text to messages References: <85h981e4hz.fsf_-_@benfinney.id.au> Message-ID: <858ttde27f.fsf@benfinney.id.au> Alan Gauld via Tutor writes: > Now, how do we educate everyone on how to specify and use a text > attachment? (This is a serious question BTW since we can add it > to the tutor welcome/usage message.) That depends on who's included in ?everyone? :-) If it includes people who don't wish to change their email client, I think that may be impossible. Some email clients (e.g. Microsoft Outlook) are notoriously bad at handling attachments, so if you're not willing to tell such people ?switch to a better client? then you may not be able to include them. As well as telling people to avoid some terrible email clients, you're talking about educating people on how to use their email client's specific features. Does ?everyone? include people who are just trying to post a message here for the first time and aren't ready to gat a lecture on what an email client even is? (The proportion of people using email without any awareness of what program they're even using is surprisingly high, so a document saying ?Follow the instructions from the section that applies to your specific email client? will not be of use to those people.) It's a difficult problem: email should be simple to use correctly by default, but people's email clients ? that many of them didn't actively select ? are in varying states of brokenness, before they even get any information from us about what to do. -- \ ?Intellectual property is to the 21st century what the slave | `\ trade was to the 16th.? ?David Mertz | _o__) | Ben Finney From bryonadams at openmailbox.org Mon Oct 24 21:38:10 2016 From: bryonadams at openmailbox.org (Bryon Adams) Date: Mon, 24 Oct 2016 21:38:10 -0400 Subject: [Tutor] Alternative to for/while loop Message-ID: Hello, I'm very new to python so please forgive what may be a beginner question. The book I'm working through hasn't covered using flow control yet so I'm thinking there should be a way to do this without the for loop I used, but I'm at a loss here. So far the book has covered: lists, strings, numerical types (float, integer, etc), methods, tuples, importing modules, boolean logic, and mathematical operators. The problem asks to receive an arbitrary list of numbers separated by commas and then find the average. If someone could point me in the right direction I'd appreciate it. I'm using Python3.5.1 on Fedora 24 Linux, though the book uses Python2.x. My code: nums = input('Enter some numbers separated by commas: ') nums = [float(i) for i in nums.split(', ')] print((sum(nums)) / len(nums)) Regards, Bryon From ben+python at benfinney.id.au Tue Oct 25 04:10:00 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 25 Oct 2016 19:10:00 +1100 Subject: [Tutor] Alternative to for/while loop References: Message-ID: <85vawgdf3b.fsf@benfinney.id.au> Bryon Adams writes: > I'm very new to python so please forgive what may be a beginner > question. Welcome! You are in the right place for asking beginner Python questions :-) > I'm thinking there should be a way to do this without the for loop I > used, but I'm at a loss here. Thank you for posting your code, and a specific question about it. Why do you think there ?should be a way to do this without the for loop?? If you want to do something with a collection of items, a ?for? loop is quite a normal way to do that. (In fact you have not used a for loop, you have used a different syntax called a ?list comprehension?. But the main question remains unchanged: Why would you expect to not need some kind of iteration like a ?for??) -- \ ?Probably the earliest flyswatters were nothing more than some | `\ sort of striking surface attached to the end of a long stick.? | _o__) ?Jack Handey | Ben Finney From alan.gauld at yahoo.co.uk Tue Oct 25 04:19:53 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 25 Oct 2016 09:19:53 +0100 Subject: [Tutor] Alternative to for/while loop In-Reply-To: References: Message-ID: On 25/10/16 02:38, Bryon Adams wrote: > question. The book I'm working through hasn't covered using flow control > yet so I'm thinking there should be a way to do this without the for > loop I used, but I'm at a loss here. Thee are ways to do it without using a for loop but they are all more advanced rather than simpler. (And they are less "good" than the simple program you have written in that they are unnecessarily complicated) > So far the book has covered: lists, > strings, numerical types (float, integer, etc), methods, tuples, > importing modules, boolean logic, and mathematical operators. You used a list comprehension in your solution, was that covered as part of lists? If not how did you find it? > nums = input('Enter some numbers separated by commas: ') > nums = [float(i) for i in nums.split(', ')] > print((sum(nums)) / len(nums)) That's about as simple as it gets except for the surplus of parens in the last line: print(sum(nums) / len(nums)) is sufficient. -- 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 From wolfgang.maier at biologie.uni-freiburg.de Tue Oct 25 04:31:19 2016 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Tue, 25 Oct 2016 10:31:19 +0200 Subject: [Tutor] Alternative to for/while loop In-Reply-To: <85vawgdf3b.fsf@benfinney.id.au> References: <85vawgdf3b.fsf@benfinney.id.au> Message-ID: On 25.10.2016 10:10, Ben Finney wrote: > Bryon Adams writes: > >> I'm very new to python so please forgive what may be a beginner >> question. > > Welcome! You are in the right place for asking beginner Python questions > :-) > >> I'm thinking there should be a way to do this without the for loop I >> used, but I'm at a loss here. > > Thank you for posting your code, and a specific question about it. > > Why do you think there ?should be a way to do this without the for > loop?? If you want to do something with a collection of items, a ?for? > loop is quite a normal way to do that. > > (In fact you have not used a for loop, you have used a different syntax > called a ?list comprehension?. But the main question remains unchanged: > Why would you expect to not need some kind of iteration like a ?for??) > You cut off a relevant part of the orignal question: > The book I'm working through hasn't covered using flow control yet ... and I agree that it would be a strange book that requires you to use for loops or comprehensions before they got introduced. A possible explanation is that, as you are saying, the book uses python2. In python2, input does not return a string, but evaluates the input from the user to produce different types of objects. So in Python2: >>> nums = input('Enter some numbers separated by commas: ') Enter some numbers separated by commas: 1,2,3,4 >>> nums (1,2,3,4) >>> type(nums) So the task is actually easier in Python2, BUT: there is a good reason (safety) why that behavior of input got removed in Python3. In general, it is a really bad idea to evaluate arbitrary input as python code. Your solution using a comprehension (or a for loop) to convert string parts to float explicitly is far better and the recommended approach nowadays. Best, Wolfgang From nirajkumarpandey at gmail.com Tue Oct 25 04:09:17 2016 From: nirajkumarpandey at gmail.com (niraj pandey) Date: Tue, 25 Oct 2016 13:39:17 +0530 Subject: [Tutor] Alternative to for/while loop In-Reply-To: References: Message-ID: Try this. my_string = '0,1,2,3' my_lst=my_string.split(",") leng = len(my_lst) b=sum(my_lst) avg=float(b/leng) print avg On Tue, Oct 25, 2016 at 7:08 AM, Bryon Adams wrote: > Hello, > I'm very new to python so please forgive what may be a beginner > question. The book I'm working through hasn't covered using flow control > yet so I'm thinking there should be a way to do this without the for loop I > used, but I'm at a loss here. So far the book has covered: lists, strings, > numerical types (float, integer, etc), methods, tuples, importing modules, > boolean logic, and mathematical operators. > The problem asks to receive an arbitrary list of numbers separated by > commas and then find the average. If someone could point me in the right > direction I'd appreciate it. I'm using Python3.5.1 on Fedora 24 Linux, > though the book uses Python2.x. > > My code: > nums = input('Enter some numbers separated by commas: ') > nums = [float(i) for i in nums.split(', ')] > print((sum(nums)) / len(nums)) > > Regards, > Bryon > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Success occurs when opportunity and preparation meet From wolfgang.maier at biologie.uni-freiburg.de Tue Oct 25 05:14:26 2016 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Tue, 25 Oct 2016 11:14:26 +0200 Subject: [Tutor] Alternative to for/while loop In-Reply-To: References: Message-ID: On 25.10.2016 10:09, niraj pandey wrote: > Try this. > > my_string = '0,1,2,3' > my_lst=my_string.split(",") > leng = len(my_lst) > b=sum(my_lst) > avg=float(b/leng) > print avg > better try things yourself before suggesting them to others: >>> my_string = '0,1,2,3' >>> my_lst=my_string.split(",") >>> leng = len(my_lst) >>> b=sum(my_lst) Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for +: 'int' and 'str' This is exactly why the OP had to come up with his comprehension solution. From alan.gauld at yahoo.co.uk Tue Oct 25 05:33:35 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 25 Oct 2016 10:33:35 +0100 Subject: [Tutor] Alternative to for/while loop In-Reply-To: References: Message-ID: On 25/10/16 09:09, niraj pandey wrote: > Try this. > > my_string = '0,1,2,3' > my_lst=my_string.split(",") > leng = len(my_lst) > b=sum(my_lst) > avg=float(b/leng) > print avg It doesn't work because my_list is a list of strings and you can't sum() strings. The loop is needed to convert the strings to numbers. -- 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 From alan.gauld at yahoo.co.uk Tue Oct 25 05:36:38 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 25 Oct 2016 10:36:38 +0100 Subject: [Tutor] Alternative to for/while loop In-Reply-To: References: <85vawgdf3b.fsf@benfinney.id.au> Message-ID: On 25/10/16 09:31, Wolfgang Maier wrote: > A possible explanation is that, as you are saying, the book uses > python2. In python2, input does not return a string, but evaluates the > input from the user to produce different types of objects. So in Python2: Good catch Wolfgang, that's probably what the author had in mind. I'd actually forgotten about v2 input(), it is so long since I used it! :-) -- 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 From bryonadams at openmailbox.org Tue Oct 25 15:43:21 2016 From: bryonadams at openmailbox.org (Bryon Adams) Date: Tue, 25 Oct 2016 15:43:21 -0400 Subject: [Tutor] Alternative to for/while loop In-Reply-To: References: Message-ID: <56c865e7-aa46-928c-0916-0e351ea78b57@openmailbox.org> On 10/25/2016 4:19 AM, Alan Gauld via Tutor wrote: > On 25/10/16 02:38, Bryon Adams wrote: > >> question. The book I'm working through hasn't covered using flow control >> yet so I'm thinking there should be a way to do this without the for >> loop I used, but I'm at a loss here. > > Thee are ways to do it without using a for loop but they are > all more advanced rather than simpler. (And they are less > "good" than the simple program you have written in that they > are unnecessarily complicated) > >> So far the book has covered: lists, >> strings, numerical types (float, integer, etc), methods, tuples, >> importing modules, boolean logic, and mathematical operators. > > You used a list comprehension in your solution, was that > covered as part of lists? If not how did you find it? > >> nums = input('Enter some numbers separated by commas: ') >> nums = [float(i) for i in nums.split(', ')] >> print((sum(nums)) / len(nums)) > > That's about as simple as it gets except for the surplus > of parens in the last line: > > print(sum(nums) / len(nums)) > > is sufficient. > I had done a little bash, C, and Visual Basic so I figured a for loop would be a good way to do this (that's how I came to the idea of using 'for' anyway). This is my first effort since college to try and really learn some programming, was a hodge podge networking program and I didn't realise how useful or in demand some programming would be. If I remember correctly I was looking for how to do a for loop in python3 but I don't remember the terms I threw into DuckDuckGo (it definitely wasn't list comprehension). I believe I bookmarked it though. I ended up at a Stack Overflow page with instructions on how to do this. I'll have to skim through the chapter and see if I can find list comprehension, if not I'll check the back of the book for where it's mentioned. Wolfgang was on the money when suggesting the book was python2. Regards, Bryon From bryonadams at openmailbox.org Tue Oct 25 15:29:54 2016 From: bryonadams at openmailbox.org (Bryon Adams) Date: Tue, 25 Oct 2016 15:29:54 -0400 Subject: [Tutor] Alternative to for/while loop In-Reply-To: References: <85vawgdf3b.fsf@benfinney.id.au> Message-ID: On 10/25/2016 4:31 AM, Wolfgang Maier wrote: > On 25.10.2016 10:10, Ben Finney wrote: >> Bryon Adams writes: >> >>> I'm very new to python so please forgive what may be a beginner >>> question. >> >> Welcome! You are in the right place for asking beginner Python questions >> :-) >> >>> I'm thinking there should be a way to do this without the for loop I >>> used, but I'm at a loss here. >> >> Thank you for posting your code, and a specific question about it. >> >> Why do you think there ?should be a way to do this without the for >> loop?? If you want to do something with a collection of items, a ?for? >> loop is quite a normal way to do that. >> >> (In fact you have not used a for loop, you have used a different syntax >> called a ?list comprehension?. But the main question remains unchanged: >> Why would you expect to not need some kind of iteration like a ?for??) >> > > You cut off a relevant part of the orignal question: > >> The book I'm working through hasn't covered using flow control yet ... > > and I agree that it would be a strange book that requires you to use for > loops or comprehensions before they got introduced. > > A possible explanation is that, as you are saying, the book uses > python2. In python2, input does not return a string, but evaluates the > input from the user to produce different types of objects. So in Python2: > >>>> nums = input('Enter some numbers separated by commas: ') > Enter some numbers separated by commas: 1,2,3,4 >>>> nums > (1,2,3,4) >>>> type(nums) > > > So the task is actually easier in Python2, BUT: > there is a good reason (safety) why that behavior of input got removed > in Python3. In general, it is a really bad idea to evaluate arbitrary > input as python code. Your solution using a comprehension (or a for > loop) to convert string parts to float explicitly is far better and the > recommended approach nowadays. > > Best, > Wolfgang > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor I should have mentioned, yes the book does use python2. I've been using python3 however when I do the exercises, range() was another function that changed but I was able to figure that one out =). Thanks for the detailed explanation everyone, I appreciate it. I'll have to look up list comprehension, I'm not sure it was actually covered in the chapter to be honest and it sounds like the difference in python versions is why the author may not have covered it. I've got a bit of extra reading to do tonight! Regards, Bryon From etroy at aeroconsult.com Tue Oct 25 15:24:47 2016 From: etroy at aeroconsult.com (Ed Troy) Date: Tue, 25 Oct 2016 15:24:47 -0400 Subject: [Tutor] What is wrong with my Python program that causes it to run but not give results? Message-ID: <580FB17F.9030202@aeroconsult.com> I found a very useful Python program for calculating the Spice parameters for a LED. I have Python3 and the various modules loaded onto my Ubuntu machine. I created the diode IV curve data as per the article, but I can't seem to get it to run. My python filename is LED_model_utf8.py The text file with the LED IV data is LED_IV.txt. When I type python LED_model_utf8.py LED_IV.txt, I get an error message: edward at ubuntu:~$ python LED_model_utf8.py LED_IV.txt Traceback (most recent call last): File "LED_model_utf8.py", line 4, in import matplotlib.pyplot as plt ImportError: No module named matplotlib.pyplot If I type python3 LED_model_utf8.py LED_IV.txt, there is a pause and then I am back to the $ prompt. So, it seems like the program is running, but I am not getting any results like graphs and Spice parameters. Clearly, something is wrong, although the program "seems" to run correctly without errors. It just does not "do" anything. The page that contains the file and a description of how it works is: https://leicesterraspberrypi.wordpress.com/projects/modelling-a-diode-for-use-in-spice-simulations/ I can attach or list out my python file and the data file if needed. Ed From ben+python at benfinney.id.au Tue Oct 25 19:19:21 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 26 Oct 2016 10:19:21 +1100 Subject: [Tutor] What is wrong with my Python program that causes it to run but not give results? References: <580FB17F.9030202@aeroconsult.com> Message-ID: <85mvhsc8zq.fsf@benfinney.id.au> Ed Troy writes: > I found a very useful Python program for calculating the Spice > parameters for a LED. I have Python3 and the various modules loaded > onto my Ubuntu machine. Which libraries, specifically, have you installed? > When I type python LED_model_utf8.py LED_IV.txt, I get an error message: > edward at ubuntu:~$ python LED_model_utf8.py LED_IV.txt > Traceback (most recent call last): > File "LED_model_utf8.py", line 4, in > import matplotlib.pyplot as plt > ImportError: No module named matplotlib.pyplot This error implies that there's no library available providing ?matplotlib?. Have you installed the third-party Matplotlib library, into the same environment? -- \ ?What if the Hokey Pokey IS what it's all about?? ?anonymous | `\ | _o__) | Ben Finney From marc.tompkins at gmail.com Tue Oct 25 19:20:39 2016 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 25 Oct 2016 16:20:39 -0700 Subject: [Tutor] What is wrong with my Python program that causes it to run but not give results? In-Reply-To: <580FB17F.9030202@aeroconsult.com> References: <580FB17F.9030202@aeroconsult.com> Message-ID: On Oct 25, 2016 3:07 PM, "Ed Troy" wrote: >I get an error message: > edward at ubuntu:~$ python LED_model_utf8.py LED_IV.txt > Traceback (most recent call last): > File "LED_model_utf8.py", line 4, in > import matplotlib.pyplot as plt > ImportError: No module named matplotlib.pyplot > That last line tells you what you need to know: Python can't find the pyplot module, which is part of matplotlib. In other words, you're missing at least one of the required dependencies; there may be others once you've resolved this one. The tutorial you're following should tell you how to install the dependencies; either you've missed a step, or the author has. If it's not in the tutorial, Google "matplotlib" for instructions on installing it. From alan.gauld at yahoo.co.uk Tue Oct 25 19:50:26 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 26 Oct 2016 00:50:26 +0100 Subject: [Tutor] What is wrong with my Python program that causes it to run but not give results? In-Reply-To: <580FB17F.9030202@aeroconsult.com> References: <580FB17F.9030202@aeroconsult.com> Message-ID: On 25/10/16 20:24, Ed Troy wrote: > my Ubuntu machine. I created the diode IV curve data as per the article, > but I can't seem to get it to run. > edward at ubuntu:~$ python LED_model_utf8.py LED_IV.txt > Traceback (most recent call last): > File "LED_model_utf8.py", line 4, in > import matplotlib.pyplot as plt > ImportError: No module named matplotlib.pyplot Plain 'python' on Ubuntu usually runs Python v2. It looks like you don;t have Matplotlib inastalled for Python 2. Matplotlib is part of the 3rd party SciPy libraries and not part of the standard python install. Having looked at the web page it seems you need to use python3 and have scipy, numpy and matplotlib packages installed. You should have them in your software centre as python3-scipy, python3-numpy and python3-matplotlib > If I type python3 LED_model_utf8.py LED_IV.txt, there is a pause and > then I am back to the $ prompt. So, it seems like the program is > running, but I am not getting any results That's correct. But without seeing the code and data it's hard to guess but you could at least verify that it runs by editing the python file to include print lines. Go to the end of the file and modify the last segment to look like: if __name__ == "__main__": print("Starting....") main() print("Stopping...") > The page that contains the file and a description of how it works is: > https://leicesterraspberrypi.wordpress.com/projects/modelling-a-diode-for-use-in-spice-simulations/ I see the code but I don't see a path that doesn't print anything... You should see some kind of output. -- 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 From crk at godblessthe.us Tue Oct 25 19:52:08 2016 From: crk at godblessthe.us (Clayton Kirkwood) Date: Tue, 25 Oct 2016 16:52:08 -0700 Subject: [Tutor] regarding checksum Message-ID: <000001d22f1a$cc181070$64483150$@godblessthe.us> Small problem: Import zlib For file in files: checksum = zlib.adler32(file) traceback checksum = zlib.adler32(file) TypeError: a bytes-like object is required, not 'str' Obvious question, how do I make a bytes-like object. I've read through the documentation and didn't find a way to do this. Thanks, Clayton From __peter__ at web.de Wed Oct 26 04:34:41 2016 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 Oct 2016 10:34:41 +0200 Subject: [Tutor] regarding checksum References: <000001d22f1a$cc181070$64483150$@godblessthe.us> Message-ID: Clayton Kirkwood wrote: > Small problem: > Import zlib > For file in files: > checksum = zlib.adler32(file) > > traceback > checksum = zlib.adler32(file) > TypeError: a bytes-like object is required, not 'str' > > Obvious question, how do I make a bytes-like object. I've read through the > documentation and didn't find a way to do this. A checksum is calculated for a sequence of bytes (numbers in the range 0...255), but there are many ways to translate a string into such a byte sequence. As an example let's convert "ma?ana" first using utf-8, >>> list("ma?ana".encode("utf-8")) [109, 97, 195, 177, 97, 110, 97] then latin1: >>> list("ma?ana".encode("latin-1")) [109, 97, 241, 97, 110, 97] So which sequence should the checksum algorithm choose? Instead of picking one at random it insists on getting bytes and requires the user to decide: >>> zlib.adler32("ma?ana".encode("utf-8")) 238748531 >>> zlib.adler32("ma?ana".encode("latin1")) 178062064 However, your for loop > For file in files: > checksum = zlib.adler32(file) suggests that you are interested in the checksum of the files' contents. To get the bytes in the file you have to read the file in binary mode: >>> files = "one", "two" >>> for file in files: ... with open(file, "rb") as f: ... print(zlib.adler32(f.read())) ... 238748531 178062064 From etroy at aeroconsult.com Tue Oct 25 23:19:40 2016 From: etroy at aeroconsult.com (Ed Troy) Date: Tue, 25 Oct 2016 23:19:40 -0400 Subject: [Tutor] What is wrong with my Python program that causes it to run but not give results? In-Reply-To: References: <580FB17F.9030202@aeroconsult.com> Message-ID: <581020CC.2000109@aeroconsult.com> I am pretty sure I installed python3. And, also, matplotlib, scipy, and numpy. If I enter either python or python3, I get the >>> prompt, so I may have both installed. How do I verify which versions of python and numpy, matplotlib and scipy I have installed? I am pretty sure I have matplotlib, scipy, and numpy installed under python3, especially since I don't get an error message when I run the program using python3, but, I don't get any output, either, so something is wrong. Would it be a help if I actually list the python program that I am trying to run? On 10/25/2016 7:50 PM, Alan Gauld via Tutor wrote: > On 25/10/16 20:24, Ed Troy wrote: > >> my Ubuntu machine. I created the diode IV curve data as per the article, >> but I can't seem to get it to run. >> edward at ubuntu:~$ python LED_model_utf8.py LED_IV.txt >> Traceback (most recent call last): >> File "LED_model_utf8.py", line 4, in >> import matplotlib.pyplot as plt >> ImportError: No module named matplotlib.pyplot > Plain 'python' on Ubuntu usually runs Python v2. > It looks like you don;t have Matplotlib inastalled for Python 2. > Matplotlib is part of the 3rd party SciPy libraries and not > part of the standard python install. > > Having looked at the web page it seems you need to use python3 > and have scipy, numpy and matplotlib packages installed. > You should have them in your software centre as > python3-scipy, python3-numpy and python3-matplotlib > >> If I type python3 LED_model_utf8.py LED_IV.txt, there is a pause and >> then I am back to the $ prompt. So, it seems like the program is >> running, but I am not getting any results > That's correct. But without seeing the code and data it's > hard to guess but you could at least verify that it runs > by editing the python file to include print lines. > Go to the end of the file and modify the last segment > to look like: > > > if __name__ == "__main__": > print("Starting....") > main() > print("Stopping...") > > >> The page that contains the file and a description of how it works is: >> https://leicesterraspberrypi.wordpress.com/projects/modelling-a-diode-for-use-in-spice-simulations/ > I see the code but I don't see a path that > doesn't print anything... You should see some > kind of output. > > -- RF, Microwave, Antenna, and Analog Design, Development,Simulation, and Research Consulting http://aeroconsult.com Aerospace Consulting LLC P.O. Box 536 Buckingham, Pa. 18912 (215) 345-7184 (215) 345-1309 FAX From alan.gauld at yahoo.co.uk Wed Oct 26 05:27:34 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 26 Oct 2016 10:27:34 +0100 Subject: [Tutor] What is wrong with my Python program that causes it to run but not give results? In-Reply-To: <581020CC.2000109@aeroconsult.com> References: <580FB17F.9030202@aeroconsult.com> <581020CC.2000109@aeroconsult.com> Message-ID: On 26/10/16 04:19, Ed Troy wrote: > I am pretty sure I installed python3. And, also, matplotlib, scipy, and > numpy. If I enter either python or python3, I get the >>> prompt, so I > may have both installed. Yes, that's normal. Ubuntu uses python 2 for some of its utilities. > How do I verify which versions of python and > numpy, matplotlib and scipy I have installed? It looks like you have the libraries for v3 but not for v2. Thats OK because the script you want to run is only suitable for v3. > Would it be a help if I actually list the python program that I am > trying to run? Yes. I'm assuming you just cut n paste the code from the web site but something could have gone wrong with the fpormatting and Python is sensitive to that, so seeing your actual code would be a good idea. Meanwhile... >> Go to the end of the file and modify the last segment >> to look like: >> >> if __name__ == "__main__": >> print("Starting....") >> main() >> print("Stopping...") Did you try that? And if so did you see either/both messages when you ran the program under python3? -- 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 From felix.dietrich at sperrhaken.name Wed Oct 26 10:12:47 2016 From: felix.dietrich at sperrhaken.name (Felix Dietrich) Date: Wed, 26 Oct 2016 16:12:47 +0200 Subject: [Tutor] What is wrong with my Python program that causes it to run but not give results? In-Reply-To: <581020CC.2000109@aeroconsult.com> (Ed Troy's message of "Tue, 25 Oct 2016 23:19:40 -0400") References: <580FB17F.9030202@aeroconsult.com> <581020CC.2000109@aeroconsult.com> Message-ID: <87bmy72o80.fsf@sperrhaken.name> Ed Troy writes: > I am pretty sure I installed python3. And, also, matplotlib, scipy, > and numpy. > How do I verify which versions of python and numpy, matplotlib and > scipy I have installed? The following commandline should list the version of installed python packages required by the script ? assuming you have used Ubuntu's deb based package manager to install the scripts dependencies: $ dpkg-query --showformat='${db:Status-Abbrev} ${binary:Package} ${Version}\n' \ --show 'python*' \ | awk '$1 ~ /.i.?/ && $2 ~ /^python3?(-((scipy)|(numpy)|(matplotlib)))?$/' \ | column -t Short explanation: dpkg-query lists packages matching a glob-pattern; awk filters for packages actually installed and limits the by the glob-pattern matched package names further; column prettifies the output. > I am pretty sure I have matplotlib, scipy, and numpy installed under > python3, especially since I don't get an error message when I run the > program using python [?] As you have noted yourself the absence of ImportErrors strongly implies that you have the required modules installed ? even so: double checking won't hurt. As an aside: because the script starts with a shebang line ("#!") you do not, after you have made it executable, need to specify the interpreter to use, which safes you the trouble of choosing Version 2 or 3 of python (or mistyping the interpreter name) and would also allow the script to be easily called from a directory in your PATH environment variable: $ chmod u+x LED_model_utf8.py $ ./LED_model_utf8.py LED_model_utf8.py LED_IV.txt -- Felix Dietrich From felix.dietrich at sperrhaken.name Wed Oct 26 10:18:40 2016 From: felix.dietrich at sperrhaken.name (Felix Dietrich) Date: Wed, 26 Oct 2016 16:18:40 +0200 Subject: [Tutor] What is wrong with my Python program that causes it to run but not give results? In-Reply-To: (Alan Gauld via Tutor's message of "Wed, 26 Oct 2016 10:27:34 +0100") References: <580FB17F.9030202@aeroconsult.com> <581020CC.2000109@aeroconsult.com> Message-ID: <877f8v2ny7.fsf@sperrhaken.name> > Alan Gauld via Tutor writes: >> On 26/10/16 04:19, Ed Troy wrote: >> Would it be a help if I actually list the python program that I am >> trying to run? > > Yes. I'm assuming you just cut n paste the code from the web site but > something could have gone wrong with the formatting and Python is > sensitive to that, so seeing your actual code would be a good idea. Could you also provide a small set of sample data that fails, maybe $ head LED_IV.txt > sample.txt will be enough. -- Felix Dietrich From etroy at aeroconsult.com Wed Oct 26 11:45:32 2016 From: etroy at aeroconsult.com (Ed Troy) Date: Wed, 26 Oct 2016 11:45:32 -0400 Subject: [Tutor] What is wrong with my Python program that causes it to run but not give results? In-Reply-To: <877f8v2ny7.fsf@sperrhaken.name> References: <580FB17F.9030202@aeroconsult.com> <581020CC.2000109@aeroconsult.com> <877f8v2ny7.fsf@sperrhaken.name> Message-ID: <5810CF9C.7010805@aeroconsult.com> I found the problem. Originally, I was getting errors that were related to formatting, apparently. It looked fine to me, but because I had copied it from the web, there were, apparently, hidden characters. In an effort to get rid of errors, I was eliminating some lines. I finally added a line, # -#- coding: utf-8 -*- near the beginning of the file. This is when I got to where I was with it seeming to run if I started the command line with python3 but getting errors if I started with python. I was pretty sure I had all of the required modules installed. But then, when instructed to add some lines at the end for debugging, I found that I had accidentally removed two lines at the end and forgot to add them back in. They were: if __name__=="__main__": main() Once I added them, it runs fine whether I say python LED_model_utf8.py LED_IV.txt or python3 LED_model_utf8.py LED_IV.txt Thanks to everyone. Sorry for the mistake on my part. I think that if I had added the # -#- coding: utf-8 -*- right from the start, the problem never would have happened. Ed On 10/26/2016 10:18 AM, Felix Dietrich wrote: >> Alan Gauld via Tutor writes: >>> On 26/10/16 04:19, Ed Troy wrote: >>> Would it be a help if I actually list the python program that I am >>> trying to run? >> Yes. I'm assuming you just cut n paste the code from the web site but >> something could have gone wrong with the formatting and Python is >> sensitive to that, so seeing your actual code would be a good idea. > Could you also provide a small set of sample data that fails, maybe > > $ head LED_IV.txt > sample.txt > > will be enough. > > -- > Felix Dietrich > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > From akleider at sonic.net Wed Oct 26 13:44:58 2016 From: akleider at sonic.net (Alex Kleider) Date: Wed, 26 Oct 2016 10:44:58 -0700 Subject: [Tutor] run local script on a remote machine Message-ID: <131d9be99cad9352d351837849e96b3d@sonic.net> I've got three files as follows: 1: #!/usr/bin/env python3 # # file: experiment.py # # A simple python program that takes parameters. import sys info = sys.argv[1:] print(info) with open("/home/alex/junk.txt", 'w') as file_object: for item in info: file_object.write(''.join((item,'\n'))) 2: #!/bin/bash # # file: call.sh # Demonstrates running a local python script on another host # with command line arguments specified locally. ssh -p22 alex at 10.10.10.10 python3 -u - one two three < /home/alex/Py/BackUp/Sandbox/Scripted/experiment.py 3: #!/usr/bin/env python3 # # file: call.py import os import shlex import subprocess script = "/home/alex/Py/BackUp/Sandbox/Scripted/experiment.py" if os.path.isfile(script): print("File exists on local machine.") else: print("No such file.") command = ( "ssh -p22 alex at 10.10.10.10 python3 -u - one two three < {}" .format(script)) ret = subprocess.call(shlex.split(command)) if ret: print("Command failed!!") else: print("All's well.") Running the shell script (2) executes a single shell command and leaves the junk.txt file at 10.10.10.10 as desired. Calling the same shell command using the subprocess module from with in a python script (3) does not work: alex at X301n3:~/Py/BackUp/Sandbox/Scripted$ ./call.py File exists on local machine. bash: /home/alex/Py/BackUp/Sandbox/Scripted/experiment.py: No such file or directory Command failed!! I'm doing this using Ubuntu14.04LTS. Thanks in advance for any suggestions as to how to proceed. Alex From glenuk at gmail.com Wed Oct 26 14:06:10 2016 From: glenuk at gmail.com (Wish Dokta) Date: Wed, 26 Oct 2016 19:06:10 +0100 Subject: [Tutor] String within a string solution (newbie question) Message-ID: Hello, I am currently writing a basic program to calculate and display the size of folders with a drive/directory. To do this I am storing each directory in a dict as the key, with the value being the sum of the size of all files in that directories (but not directories). For example: { "C:\\docs" : 10, "C:\\docs123" : 200, "C:\\docs\\code\\snippets" : 5, "C:\\docs\\code" : 20, "C:\\docs\\pics" : 200, "C:\\docs\\code\\python" : 10 } Then to return the total size of a directory I am searching for a string in the key: For example: for "C:\\docs\\code" in key: Which works fine and will return "C:\\docs\\code" : 20, "C:\\docs\\code\\snippets" : 5, "C:\\docs\\code\\python" : 10 = (35) However it fails when I try to calculate the size of a directory such as "C:\\docs", as it also returns "C:\\docs123". I'd be very grateful if anyone could offer any advice on how to correct this. From alan.gauld at yahoo.co.uk Wed Oct 26 14:34:58 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 26 Oct 2016 19:34:58 +0100 Subject: [Tutor] String within a string solution (newbie question) In-Reply-To: References: Message-ID: On 26/10/16 19:06, Wish Dokta wrote: > folders with a drive/directory. To do this I am storing each directory in a > dict as the key, with the value being the sum of the size of all files in > that directories (but not directories). > > For example: > > for "C:\\docs\\code" in key: > > Which works fine and will return "C:\\docs\\code" : 20, > "C:\\docs\\code\\snippets" : 5, "C:\\docs\\code\\python" : 10 = (35) > > However it fails when I try to calculate the size of a directory such as > "C:\\docs", as it also returns "C:\\docs123". > > I'd be very grateful if anyone could offer any advice on how to correct > this. We can't guess what your code looks like, you need to show us. Post the code and we can maybe help. -- 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 From bgailer at gmail.com Wed Oct 26 14:43:54 2016 From: bgailer at gmail.com (Bob Gailer) Date: Wed, 26 Oct 2016 14:43:54 -0400 Subject: [Tutor] String within a string solution (newbie question) In-Reply-To: References: Message-ID: On Oct 26, 2016 2:07 PM, "Wish Dokta" wrote: > > Hello, > > I am currently writing a basic program to calculate and display the size of > folders with a drive/directory. To do this I am storing each directory in a > dict as the key, with the value being the sum of the size of all files in > that directories (but not directories). > > For example: > > { "C:\\docs" : 10, "C:\\docs123" : 200, "C:\\docs\\code\\snippets" : 5, > "C:\\docs\\code" : 20, "C:\\docs\\pics" : 200, "C:\\docs\\code\\python" : > 10 } > > Then to return the total size of a directory I am searching for a string in > the key: > > For example: > > for "C:\\docs\\code" in key: Put "\\" at the end of the search string. > > Which works fine and will return "C:\\docs\\code" : 20, > "C:\\docs\\code\\snippets" : 5, "C:\\docs\\code\\python" : 10 = (35) > > However it fails when I try to calculate the size of a directory such as > "C:\\docs", as it also returns "C:\\docs123". > > I'd be very grateful if anyone could offer any advice on how to correct > this. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From cs at zip.com.au Thu Oct 27 03:22:21 2016 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 27 Oct 2016 18:22:21 +1100 Subject: [Tutor] run local script on a remote machine In-Reply-To: <131d9be99cad9352d351837849e96b3d@sonic.net> References: <131d9be99cad9352d351837849e96b3d@sonic.net> Message-ID: <20161027072221.GA84878@cskk.homeip.net> On 26Oct2016 10:44, Alex Kleider wrote: [... snipped experiment.py and the demo call.sh script ...] >3: >#!/usr/bin/env python3 ># ># file: call.py > >import os >import shlex >import subprocess > >script = "/home/alex/Py/BackUp/Sandbox/Scripted/experiment.py" This is fine. >if os.path.isfile(script): > print("File exists on local machine.") >else: > print("No such file.") This is fine. >command = ( >"ssh -p22 alex at 10.10.10.10 python3 -u - one two three < {}" > .format(script)) >ret = subprocess.call(shlex.split(command)) This is not fine. There are a few things wrong here. First, as a maytter of practice you should _never_ construct command strings as you are doing here: embedding an arbitrary filename directly in a string that will be evaluated by a command parser. This applies equally to shell commands such as yours or to SQL or anything else where you're preparing text to be parsed. Supposing your filename has shell punctuation in it, even the lowly space character? The outcome would not be what you intended. You can see where I'm going here I'm sure. Read more here (SQL specific, though the principle is general): http://bobby-tables.com/ The second problem, and the one causing your immediate issue, is the use of shlex.split. This is _not_ a full shell parser. It is a convenience function that recognises common shell quoting syntax to be used when writing little minilanguages of your own - it gets you a preimplemented quoting parser you can then let your users access to mark off strings. Your command looks like this, roughly: ssh -p22 ..blah blah blah... < /path/to/script.py All shlex.split is going to do with this is to break it into separate strings: ssh -p22 ..blah blah blah... < /path/to/script.py They're just strings. No redirection recognition or implementation is happening here. Then when you call subprocess.call: ret = subprocess.call(shlex.split(command)) you're passing a list of those strings as the first argument. subprocess.call and its partner Popen have two modes for their first argument: if it is a string then it will be passed to the system shell, otherwise it is executed directly without being handled by a shell. Effectively the first form takes: subprocess.call(some_string) and runs is as: subprocess.call(['/bin/sh', '-c', some_string]) You're using the second form, and that is by far the better thing to do, so good there. _However_, you're effectively invoking ssh with no redirections; instead your passing the strings '<' and '/path/to/script.py' as arguments to ssh. What you really want to do is this (untested): with open(script) as scfp: ret = subprocess.call(['ssh', '-p22', 'alex at 10.10.10.10', 'python3', '-u', '-', 'one', 'two', 'three'], stdin=scfp) which arranges to attach an open file reading from your script to the ssh subprocess you are invoking. Note that it does _not_ pass the script pathname itself as an argument to ssh. Neither does your shell script. Now for the confusing bit: what _was_ your program really doing? Well, ssh concatenates its command arguments: python3 -u - one two three together and passes them to the far end, which hands them to the shell! So effectively, like the string form of subprocess.call, ssh itself effectively invokes: sh -c 'python3 -u - one two three' at the far end. So you're going to need shell quotes in that string if you ever pass something slightly tricky, or something arbitrary. But you're not yet. _However_, the original form of you program was passing _these_ strings as command arguments to ssh: python3 -u - one two three < /home/alex/Py/BackUp/Sandbox/Scripted/experiment.py so ssh is invoking this: /bin/sh -c 'python3 -u - one two three < /home/alex/Py/BackUp/Sandbox/Scripted/experiment.py' at the far end. (Those are all on one line, BTW, in case your email reader folds things up.) So you might think: but then the shell _will_ see the "<" redirection! But of course that is the shell on the remote machine, and your script isn't on that machine, so the shell emits the error message you saw. Hoping this clarifies what's going on and how to go forward. Please feel free to ask any questions that occur. Cheers, Cameron Simpson Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law. - Douglas Hosfstadter, Godel, Escher, Bach: an Eternal Golden Braid From wolfgang.maier at biologie.uni-freiburg.de Thu Oct 27 03:57:55 2016 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Thu, 27 Oct 2016 09:57:55 +0200 Subject: [Tutor] run local script on a remote machine In-Reply-To: <131d9be99cad9352d351837849e96b3d@sonic.net> References: <131d9be99cad9352d351837849e96b3d@sonic.net> Message-ID: On 26.10.2016 19:44, Alex Kleider wrote: > > I've got three files as follows: > keeping just the relevant lines ... > 2: > #!/bin/bash > # > # file: call.sh > > # Demonstrates running a local python script on another host > # with command line arguments specified locally. > > ssh -p22 alex at 10.10.10.10 python3 -u - one two three < > /home/alex/Py/BackUp/Sandbox/Scripted/experiment.py > > 3: > #!/usr/bin/env python3 > # > # file: call.py > > import os > import shlex > import subprocess > > script = "/home/alex/Py/BackUp/Sandbox/Scripted/experiment.py" > if os.path.isfile(script): > print("File exists on local machine.") > else: > print("No such file.") > > command = ( > "ssh -p22 alex at 10.10.10.10 python3 -u - one two three < {}" > .format(script)) > > ret = subprocess.call(shlex.split(command)) > ... > > Running the shell script (2) executes a single shell command and leaves > the junk.txt file at 10.10.10.10 as desired. > Calling the same shell command using the subprocess module from with in > a python script (3) does not work: > alex at X301n3:~/Py/BackUp/Sandbox/Scripted$ ./call.py > File exists on local machine. > bash: /home/alex/Py/BackUp/Sandbox/Scripted/experiment.py: No such file > or directory The structure of the command you are trying to execute would require you to set the "shell" argument of subprocess.call to True. Specifically, the "<" redirection operator is shell functionality. Quoting from https://docs.python.org/3/library/subprocess.html?highlight=subprocess#subprocess.Popen: """ The shell argument (which defaults to False) specifies whether to use the shell as the program to execute. If shell is True, it is recommended to pass args as a string rather than as a sequence. On POSIX with shell=True, the shell defaults to /bin/sh. If args is a string, the string specifies the command to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself. That is to say, Popen does the equivalent of: Popen(['/bin/sh', '-c', args[0], args[1], ...]) """ This is exactly the behaviour you are expecting from your code: the shell gets called and sees a command for which the stdin should be replaced with the contents of a local file; it does that and executes the ssh command. With the default shell=False, OTOH, the first item in your shlex.split generated list, 'ssh', becomes the executable and gets called with the rest of the list as arguments. ssh, however, does not interpret the '<' sign like the shell, runs the remote shell command, the remote shell sees and interprets the '<', fails to find the file on the remote machine and errors out. The simple solution should be to not split your command string, but pass it directly to subprocess.call (untested): subprocess.call(command, shell=True) as long as you promise to NEVER use that code in production with user input. The problem with it is that it may allow users to inject shell commands as they like exactly because whatever ends up in the command string gets interpreted by the shell. Best, Wolfgang From glenuk at gmail.com Thu Oct 27 08:37:31 2016 From: glenuk at gmail.com (Wish Dokta) Date: Thu, 27 Oct 2016 13:37:31 +0100 Subject: [Tutor] String within a string solution (newbie question) In-Reply-To: References: Message-ID: Hello Alan, Thank you for the reply. I have actually fixed that bug. If you are bored or for some other reason would like to assist a newbro my code is here: main: http://pastebin.com/LgbeywiB functions: http://pastebin.com/vU7zzJKe I'd be very grateful for any feedback on improvements to the code or how I am coding in general. I'd be particularly interested in a better data structure to use to store the directories and their sizes. Many thanks, Glen On 26 October 2016 at 19:34, Alan Gauld via Tutor wrote: > On 26/10/16 19:06, Wish Dokta wrote: > > > folders with a drive/directory. To do this I am storing each directory > in a > > dict as the key, with the value being the sum of the size of all files in > > that directories (but not directories). > > > > For example: > > > > for "C:\\docs\\code" in key: > > > > Which works fine and will return "C:\\docs\\code" : 20, > > "C:\\docs\\code\\snippets" : 5, "C:\\docs\\code\\python" : 10 = (35) > > > > However it fails when I try to calculate the size of a directory such as > > "C:\\docs", as it also returns "C:\\docs123". > > > > I'd be very grateful if anyone could offer any advice on how to correct > > this. > > We can't guess what your code looks like, you need to show us. > Post the code and we can maybe help. > > -- > 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 at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From glenuk at gmail.com Thu Oct 27 08:39:00 2016 From: glenuk at gmail.com (Wish Dokta) Date: Thu, 27 Oct 2016 13:39:00 +0100 Subject: [Tutor] String within a string solution (newbie question) In-Reply-To: References: Message-ID: Thank you Bob, While you were correct adding "\\" helped, I also needed to add "\\" to the dict key so it would also pic up the root directory. Many thanks, Glen On 26 October 2016 at 19:43, Bob Gailer wrote: > On Oct 26, 2016 2:07 PM, "Wish Dokta" wrote: > > > > Hello, > > > > I am currently writing a basic program to calculate and display the size > of > > folders with a drive/directory. To do this I am storing each directory > in a > > dict as the key, with the value being the sum of the size of all files in > > that directories (but not directories). > > > > For example: > > > > { "C:\\docs" : 10, "C:\\docs123" : 200, "C:\\docs\\code\\snippets" : 5, > > "C:\\docs\\code" : 20, "C:\\docs\\pics" : 200, "C:\\docs\\code\\python" : > > 10 } > > > > Then to return the total size of a directory I am searching for a string > in > > the key: > > > > For example: > > > > for "C:\\docs\\code" in key: > > Put "\\" at the end of the search string. > > > > Which works fine and will return "C:\\docs\\code" : 20, > > "C:\\docs\\code\\snippets" : 5, "C:\\docs\\code\\python" : 10 = (35) > > > > However it fails when I try to calculate the size of a directory such as > > "C:\\docs", as it also returns "C:\\docs123". > > > > I'd be very grateful if anyone could offer any advice on how to correct > > this. > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > From bgailer at gmail.com Thu Oct 27 10:50:30 2016 From: bgailer at gmail.com (Bob Gailer) Date: Thu, 27 Oct 2016 10:50:30 -0400 Subject: [Tutor] String within a string solution (newbie question) In-Reply-To: References: Message-ID: BubOn Oct 27, 2016 8:38 AM, "Wish Dokta" wrote: > > Hello Alan, > > Thank you for the reply. > > I have actually fixed that bug. If you are bored or for some other reason > would like to assist a newbro my code is here: > > main: http://pastebin.com/LgbeywiB > functions: http://pastebin.com/vU7zzJKe Code following first while needs to be indented. Too many unnecessary blank lines. Since a drive is a letter ask user to enter a letter rather than going through the exercise of translating letters to numbers and back. Minimize the number of statements following try. To print a message surrounded by blank lines consider: print("\nMessage\n") or print(""" Message """) > > I'd be very grateful for any feedback on improvements to the code or how I > am coding in general. I'd be particularly interested in a better data > structure to use to store the directories and their sizes. > > Many thanks, > Glen > > On 26 October 2016 at 19:34, Alan Gauld via Tutor wrote: > > > On 26/10/16 19:06, Wish Dokta wrote: > > > > > folders with a drive/directory. To do this I am storing each directory > > in a > > > dict as the key, with the value being the sum of the size of all files in > > > that directories (but not directories). > > > > > > For example: > > > > > > for "C:\\docs\\code" in key: > > > > > > Which works fine and will return "C:\\docs\\code" : 20, > > > "C:\\docs\\code\\snippets" : 5, "C:\\docs\\code\\python" : 10 = (35) > > > > > > However it fails when I try to calculate the size of a directory such as > > > "C:\\docs", as it also returns "C:\\docs123". > > > > > > I'd be very grateful if anyone could offer any advice on how to correct > > > this. > > > > We can't guess what your code looks like, you need to show us. > > Post the code and we can maybe help. > > > > -- > > 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 at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From matt.ruffalo at gmail.com Thu Oct 27 12:04:14 2016 From: matt.ruffalo at gmail.com (Matt Ruffalo) Date: Thu, 27 Oct 2016 12:04:14 -0400 Subject: [Tutor] String within a string solution (newbie question) In-Reply-To: References: Message-ID: <86b310c9-9b7c-8489-f414-35eee4832a4f@gmail.com> On 10/26/2016 02:06 PM, Wish Dokta wrote: > Hello, > > I am currently writing a basic program to calculate and display the size of > folders with a drive/directory. To do this I am storing each directory in a > dict as the key, with the value being the sum of the size of all files in > that directories (but not directories). > > For example: > > { "C:\\docs" : 10, "C:\\docs123" : 200, "C:\\docs\\code\\snippets" : 5, > "C:\\docs\\code" : 20, "C:\\docs\\pics" : 200, "C:\\docs\\code\\python" : > 10 } > > Then to return the total size of a directory I am searching for a string in > the key: > > For example: > > for "C:\\docs\\code" in key: > > Which works fine and will return "C:\\docs\\code" : 20, > "C:\\docs\\code\\snippets" : 5, "C:\\docs\\code\\python" : 10 = (35) > > However it fails when I try to calculate the size of a directory such as > "C:\\docs", as it also returns "C:\\docs123". > > I'd be very grateful if anyone could offer any advice on how to correct > this. Hello- As you saw in your current approach, using strings for paths can be problematic in a lot of scenarios. I've found it really useful to use a higher-level abstraction instead, like what is provided by pathlib in the standard library. You're obviously using Windows, and you didn't mention your Python version, so I'll assume you're using something current like 3.5.2 (at least 3.4 is required for the following code). You could do something like the following: """ from pathlib import PureWindowsPath # From your example sizes_str_keys = { "C:\\docs": 10, "C:\\docs123": 200, "C:\\docs\\code\\snippets": 5, "C:\\docs\\code": 20, "C:\\docs\\pics": 200, "C:\\docs\\code\\python": 10, } # Same dict, but with Path objects as keys, and the same sizes as values. # You would almost definitely want to use Path in your code (and adjust # the 'pathlib' import appropriately), but I'm on a Linux system so I had # to use a PureWindowsPath instead. sizes_path_keys = {PureWindowsPath(p): s for (p, s) in sizes_str_keys.items()} def filter_paths(size_dict, top_level_directory): for path in size_dict: # Given some directory we're examining (e.g. c:\docs\code\snippets), # and top-level directory (e.g. c:\docs), we want to yield this # directory if it exactly matches (of course) or if the top-level # directory is a parent of what we're looking at: # >>> pprint(list(PureWindowsPath("C:\\docs\\code\\snippets").parents)) # [PureWindowsPath('C:/docs/code'), # PureWindowsPath('C:/docs'), # PureWindowsPath('C:/')] # so in that case we'll find 'c:\docs' in iterating over path.parents. # You'll definitely want to remove the 'print' calls too: if path == top_level_directory or top_level_directory in path.parents: print('Matched', path) yield path else: print('No match for', path) def compute_subdir_size(size_dict, top_level_directory): total_size = 0 for dir_key in filter_paths(size_dict, top_level_directory): total_size += size_dict[dir_key] return total_size """ Then you could call 'compute_subdir_size' like so: """ >>> compute_subdir_size(sizes_path_keys, PureWindowsPath(r'c:\docs')) Matched C:\docs\code\snippets No match for C:\docs123 Matched C:\docs\code\python Matched C:\docs\pics Matched C:\docs\code Matched C:\docs 245 >>> compute_subdir_size(sizes_path_keys, PureWindowsPath(r'c:\docs\code')) Matched C:\docs\code\snippets No match for C:\docs123 Matched C:\docs\code\python No match for C:\docs\pics Matched C:\docs\code No match for C:\docs 35 """ MMR... From akleider at sonic.net Thu Oct 27 12:37:23 2016 From: akleider at sonic.net (Alex Kleider) Date: Thu, 27 Oct 2016 09:37:23 -0700 Subject: [Tutor] run local script on a remote machine In-Reply-To: References: <131d9be99cad9352d351837849e96b3d@sonic.net> Message-ID: On 2016-10-27 00:57, Wolfgang Maier wrote: > > The structure of the command you are trying to execute would require > you to set the "shell" argument of subprocess.call to True. > Specifically, the "<" redirection operator is shell functionality. Thank you Wolfgang. Simply eliminating the call to shlex.split() made everything work as desired. ......... > > as long as you promise to NEVER use that code in production with user > input. The problem with it is that it may allow users to inject shell > commands as they like exactly because whatever ends up in the command > string gets interpreted by the shell. I promise! Thanks again. Alex _____________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From akleider at sonic.net Thu Oct 27 12:46:55 2016 From: akleider at sonic.net (Alex Kleider) Date: Thu, 27 Oct 2016 09:46:55 -0700 Subject: [Tutor] run local script on a remote machine In-Reply-To: <20161027072221.GA84878@cskk.homeip.net> References: <131d9be99cad9352d351837849e96b3d@sonic.net> <20161027072221.GA84878@cskk.homeip.net> Message-ID: <9ef5f903f09a9706990d0643141f1e13@sonic.net> On 2016-10-27 00:22, Cameron Simpson wrote: > On 26Oct2016 10:44, Alex Kleider wrote: >> command = ( >> "ssh -p22 alex at 10.10.10.10 python3 -u - one two three < {}" >> .format(script)) >> ret = subprocess.call(shlex.split(command)) > > This is not fine. .......... > http://bobby-tables.com/ Thanks for the warning. I'm aware of the injection problem and should have mentioned that the code exposed itself to this only because I was trying to make it as short as possible to demonstrate the problem. > > The second problem, and the one causing your immediate issue, is the > use of shlex.split. Eliminating it made things work as desired. > Hoping this clarifies what's going on and how to go forward. It does that indeed. Thank you very much. > Please feel free to ask any questions that occur. Also gratitude to you and the others on this list that are so generous with your advice. Sincerely, Alex From rusty377 at gmail.com Thu Oct 27 18:41:21 2016 From: rusty377 at gmail.com (Rusty Bayles) Date: Thu, 27 Oct 2016 18:41:21 -0400 Subject: [Tutor] New to Python Message-ID: I just installed 3.5.2 interpreter and cannot figure out how to run program. I am a database developer and my first attempt at sqllite3 has beeen a disasterr! When I run a program (after importinh sqllite and doing connection setups and attempting to setup table. When I press run (F5?) the first line in the program fails at 3.5.2 on the five? Also if I setup new fille and start typing sometimes I get prompt and sometimes not? I am signed up at stackskills for a class but they don't mention how to run program-they just do it. Also noticed-when starting new file sometimes I see run at the top sometimes not? Lots of questions. Familiar with programming in C. -- Cheers,, Rusty From alan.gauld at yahoo.co.uk Thu Oct 27 19:31:07 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 28 Oct 2016 00:31:07 +0100 Subject: [Tutor] New to Python In-Reply-To: References: Message-ID: On 27/10/16 23:41, Rusty Bayles wrote: > I just installed 3.5.2 interpreter and cannot figure out how to run > program. I strongly suggest you go to Youtube and search for IDLE. There are several short (3-10min) videos there that should make it clear where you are going wrong. Watch a couple of them. > ...When I run a program (after importinh sqllite and doing > connection setups and attempting to setup table. When I press run (F5?) the > first line in the program fails at 3.5.2 on the five? It looks like you are typing (cut n pasting?) the Python prompt into your program. Its possible you are trying to save an interactive session and then run it, but that won't work (unfortunately, it would be good if you could!) > ... if I setup new file and start typing sometimes I get prompt > and sometimes not? New file should always be a blank text screen, I'm not sure how you are getting a prompt. My best suggestion is to watch a couple of the video tutorials. Danny Yoo also has an HTML tutorial but it's quicker to watch the vids - and if you have experience in coding you should get the point pretty quickly. If you are stuck Danny's tutorial is here: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html Its quite old so a few menu options/labels may have changed but the basics are the same. -- 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 From jf_byrnes at comcast.net Thu Oct 27 20:40:43 2016 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Thu, 27 Oct 2016 19:40:43 -0500 Subject: [Tutor] comp.lang.python on gmane Message-ID: Is comp.lang.python available on gmane? I've googled and found references to it being on gmane but I can't find it there. I'd like to use gmane because Comcast doesn't do usenet anymore. Thanks, Jim From alan.gauld at yahoo.co.uk Thu Oct 27 20:14:21 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 28 Oct 2016 01:14:21 +0100 Subject: [Tutor] New to Python In-Reply-To: References: Message-ID: <5812985D.6080202@yahoo.co.uk> On 28/10/16 01:05, Rusty Bayles wrote: > Thanks for the reply Alan, > Could you please tell me more detail on the videos? Like who made them. Some are just amateurs others are professional (or at least Youtube regulars) Here are a couple of links, but to be honest just about any of them would meet your immediate needs. Short (my recommendation): https://www.*youtube*.com/watch?v=bOvqYw1SZJg longer: https://www.*youtube*.com/watch?v=lBkcDFRA958 1. Very different styles but they both contain the essentials. -- 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 From dyoo at hashcollision.org Thu Oct 27 21:09:07 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 27 Oct 2016 18:09:07 -0700 Subject: [Tutor] comp.lang.python on gmane In-Reply-To: References: Message-ID: On Thu, Oct 27, 2016 at 5:40 PM, Jim Byrnes wrote: > Is comp.lang.python available on gmane? > > I've googled and found references to it being on gmane but I can't find it > there. I'd like to use gmane because Comcast doesn't do usenet anymore. Hi Jim, I think Gmane is still recovering: https://lars.ingebrigtsen.no/2016/07/28/the-end-of-gmane/ http://home.gmane.org/2016/08/29/next-steps-gmane/ It sounds like they're making good progress at recovery so far. Until then, you can still get at comp.lang.python via web interface with Google Groups: https://groups.google.com/forum/#!forum/comp.lang.python Besides those, the archive is available at: http://mail.python.org/pipermail/python-list/ If you have more questions, please feel free to ask. Best of wishes! From dyoo at hashcollision.org Thu Oct 27 21:20:39 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 27 Oct 2016 18:20:39 -0700 Subject: [Tutor] New to Python In-Reply-To: References: Message-ID: > program-they just do it. Also noticed-when starting new file sometimes I > see run at the top sometimes not? Lots of questions. Familiar with > programming in C. If you're a database and C developer, then you probably have enough experience to go through the Python tutorial, as it is aimed for the experienced programmer. https://docs.python.org/3/tutorial/interpreter.html#using-the-python-interpreter From jf_byrnes at comcast.net Thu Oct 27 22:49:23 2016 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Thu, 27 Oct 2016 21:49:23 -0500 Subject: [Tutor] comp.lang.python on gmane In-Reply-To: References: Message-ID: On 10/27/2016 08:09 PM, Danny Yoo wrote: > On Thu, Oct 27, 2016 at 5:40 PM, Jim Byrnes wrote: >> Is comp.lang.python available on gmane? >> >> I've googled and found references to it being on gmane but I can't find it >> there. I'd like to use gmane because Comcast doesn't do usenet anymore. > > Hi Jim, > > > I think Gmane is still recovering: > > https://lars.ingebrigtsen.no/2016/07/28/the-end-of-gmane/ I read that but had forgotten about it because up until now gmane seemed to be working normally for me. > http://home.gmane.org/2016/08/29/next-steps-gmane/ > > > It sounds like they're making good progress at recovery so far. Until > then, you can still get at comp.lang.python via web interface with > Google Groups: > > https://groups.google.com/forum/#!forum/comp.lang.python > > > Besides those, the archive is available at: > > http://mail.python.org/pipermail/python-list/ > I am trying to solve a problem with Selenium and googling hasn't helped. I wanted to ask a question on the list, but wanted to search back 5 or 6 months first to see it it had already been solved. I have always found the web interfaces so cumbersome to use I don't know if I can do a search like that on them. Thanks, Jim From wolfgang.maier at biologie.uni-freiburg.de Fri Oct 28 02:40:21 2016 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Fri, 28 Oct 2016 08:40:21 +0200 Subject: [Tutor] comp.lang.python on gmane In-Reply-To: References: Message-ID: <566cdfa8-c085-caf8-aa36-f5b76e1e953d@biologie.uni-freiburg.de> On 28.10.2016 04:49, Jim Byrnes wrote: > On 10/27/2016 08:09 PM, Danny Yoo wrote: >> On Thu, Oct 27, 2016 at 5:40 PM, Jim Byrnes >> wrote: >>> Is comp.lang.python available on gmane? >>> >>> I've googled and found references to it being on gmane but I can't >>> find it >>> there. I'd like to use gmane because Comcast doesn't do usenet anymore. >> >> Hi Jim, >> >> >> I think Gmane is still recovering: >> >> https://lars.ingebrigtsen.no/2016/07/28/the-end-of-gmane/ > > I read that but had forgotten about it because up until now gmane seemed > to be working normally for me. Despite the recent turbulences with gmane comp.lang.python works perfectly fine for me through thunderbird via: news://news.gmane.org:119/gmane.comp.python.general When I last checked it was only the web interface they were still having trouble with. Wolfgang From nilswagenaar at hotmail.com Thu Oct 27 21:38:29 2016 From: nilswagenaar at hotmail.com (nils wagenaar) Date: Fri, 28 Oct 2016 01:38:29 +0000 Subject: [Tutor] Assessing local variable outside function Message-ID: Hello, Could i use a variable defined in a function in another function? I have now: def DatasetToSubset(file, LatUpbound, LatLowBound, LonUpBound, LonLowBound): nc=netCDF4.Dataset(file) lats=nc.variables['lat'][:]; lons=nc.variables['lon'][:] latselect=np.logical_and(lats > LatLowBound, lats < LatUpBound) lonselect=np.logical_and(lon > LonLowBound, lon < LonUpBound) data=nc.variables['Runoff'][1000, latselect, lonselect] return data; return latselect; return lonselect So, i want to use latselect and lonselect in a different function where i interpolate for the subsetted area. Nils From random832 at fastmail.com Thu Oct 27 22:54:06 2016 From: random832 at fastmail.com (Random832) Date: Thu, 27 Oct 2016 22:54:06 -0400 Subject: [Tutor] comp.lang.python on gmane In-Reply-To: References: Message-ID: <1477623246.300016.769833241.68D1FD1A@webmail.messagingengine.com> On Thu, Oct 27, 2016, at 20:40, Jim Byrnes wrote: > Is comp.lang.python available on gmane? > > I've googled and found references to it being on gmane but I can't find > it there. I'd like to use gmane because Comcast doesn't do usenet > anymore. I don't know about the current viability of gmane in general, but it's called "gmane.comp.python.general" on gmane. From alan.gauld at yahoo.co.uk Fri Oct 28 04:20:28 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 28 Oct 2016 09:20:28 +0100 Subject: [Tutor] Assessing local variable outside function In-Reply-To: References: Message-ID: On 28/10/16 02:38, nils wagenaar wrote: > Hello, > > > Could i use a variable defined in a function in another function? By returning it to the caller. > def DatasetToSubset(file, LatUpbound, LatLowBound, LonUpBound, LonLowBound): > nc=netCDF4.Dataset(file) > lats=nc.variables['lat'][:]; lons=nc.variables['lon'][:] > latselect=np.logical_and(lats > LatLowBound, lats < LatUpBound) > lonselect=np.logical_and(lon > LonLowBound, lon < LonUpBound) > data=nc.variables['Runoff'][1000, latselect, lonselect] > return data; return latselect; return lonselect The syntax for return is return value And you can only have one return on the line. But value can be a tuple so to do what you want: return data, latselect, lonselect And your caller can use something like dat,lat,lon = DatasetToSubset(....) The other way to do it is to create a class containing all the functions that use the same data and put the shared variables as instance attributes. class LatAndLon: # think of a better name! :-) def __init__(self, file, lat=None, lon=None): self.file = file self.lat = lat self.lon = lon def datasetToSubset(self, .....): nc = ... ... self.lat = ... self.lon = ... self.data = ... def another_function(self,...): if self.lat == 42: self.process(data) elis self.lon > 66: self.format() #etc... Then create an instance and call the methods as needed vals = LatAndLon(....) vals.datasetToSubset(....) vals.another_function(....) That way the data stays outside the global namespace but the functions that use it can all see it. You will likely find that this greatly reduces the number of params you need to pass to each function since you set them up once, when you create the instance, and don't need to keep passing them into the functions. This makes the code easier to write and maintain. 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 From __peter__ at web.de Fri Oct 28 04:22:44 2016 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 Oct 2016 10:22:44 +0200 Subject: [Tutor] Assessing local variable outside function References: Message-ID: nils wagenaar wrote: > Hello, > > > Could i use a variable defined in a function in another function? > > I have now: > > > def DatasetToSubset(file, LatUpbound, LatLowBound, LonUpBound, > LonLowBound): > nc=netCDF4.Dataset(file) > lats=nc.variables['lat'][:]; lons=nc.variables['lon'][:] > latselect=np.logical_and(lats > LatLowBound, lats < LatUpBound) > lonselect=np.logical_and(lon > LonLowBound, lon < LonUpBound) > data=nc.variables['Runoff'][1000, latselect, lonselect] > return data; return latselect; return lonselect It doesn't help that you put all return statements on the same line, only the first return data is executed; the other two are unreachable code. > So, i want to use latselect and lonselect in a different function where i > interpolate for the subsetted area. In Python while you can return only one value you can easily combine multiple values into one tuple. Instead of > return data; return latselect; return lonselect write return data, latselect, lonselect When you call the function you can either access the parts of the tuple with their respective index result = DatasetToSubset(...) lat = result[1] or use a language feature called "unpacking" to break the tuple into the individual values: data, lat, lon = DatasetToSubset(...) From ben+python at benfinney.id.au Fri Oct 28 04:28:36 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 28 Oct 2016 19:28:36 +1100 Subject: [Tutor] Assessing local variable outside function References: Message-ID: <8537jgdgi3.fsf@benfinney.id.au> Alan Gauld via Tutor writes: > On 28/10/16 02:38, nils wagenaar wrote: > > Could i use a variable defined in a function in another function? My answer would be: You can't because Python variables don't exist outside their namespace. You can make the object available in various ways, but not the variable. > By returning it to the caller. That's somewhat misleading. Returning the *object* would not grant access to the local *variable*. Nils, it's important to realise that a variable in Python is not tractable: you can't hand them around, you can't access the name itself. A Python variable exists only in its namespace, and can't move. The variable is (at any given point) bound to an object; you can get *other* variables bound to the same object by explicitly doing that. Alan suggests one way. Whether that meets your request to ?use a variable defined in a function in another function? will have to wait for you to check how the Python data model actually works. Does that answer it, or do you need something different? -- \ ?Dare to be na?ve.? ?Richard Buckminster Fuller, personal motto | `\ | _o__) | Ben Finney From jf_byrnes at comcast.net Fri Oct 28 09:43:48 2016 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Fri, 28 Oct 2016 08:43:48 -0500 Subject: [Tutor] comp.lang.python on gmane In-Reply-To: <1477623246.300016.769833241.68D1FD1A@webmail.messagingengine.com> References: <1477623246.300016.769833241.68D1FD1A@webmail.messagingengine.com> Message-ID: On 10/27/2016 09:54 PM, Random832 wrote: > On Thu, Oct 27, 2016, at 20:40, Jim Byrnes wrote: >> Is comp.lang.python available on gmane? >> >> I've googled and found references to it being on gmane but I can't find >> it there. I'd like to use gmane because Comcast doesn't do usenet >> anymore. > > I don't know about the current viability of gmane in general, but it's > called "gmane.comp.python.general" on gmane. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > That worked. Not sure how I over looked it the other times I was trying to subscribe. Thanks much. Regards, Jim From danny.yoo at gmail.com Fri Oct 28 10:39:01 2016 From: danny.yoo at gmail.com (Danny Yoo) Date: Fri, 28 Oct 2016 07:39:01 -0700 Subject: [Tutor] comp.lang.python on gmane In-Reply-To: References: <1477623246.300016.769833241.68D1FD1A@webmail.messagingengine.com> Message-ID: >>> >>> Is comp.lang.python available on gmane? >>> >>> I've googled and found references to it being on gmane but I can't find >>> it there. I'd like to use gmane because Comcast doesn't do usenet >>> anymore. >> >> >> I don't know about the current viability of gmane in general, but it's >> called "gmane.comp.python.general" on gmane. Ah, excellent! Can someone correct the link on the wiki? https://wiki.python.org/moin/CompLangPython. (I'm away from a keyboard at the moment.) From danny.yoo at gmail.com Fri Oct 28 10:49:45 2016 From: danny.yoo at gmail.com (Danny Yoo) Date: Fri, 28 Oct 2016 07:49:45 -0700 Subject: [Tutor] comp.lang.python on gmane In-Reply-To: References: <1477623246.300016.769833241.68D1FD1A@webmail.messagingengine.com> Message-ID: Ah. The wiki link does point to the expected place after all. I think, then, that the initial assessment is accurate, that Gmane is still recovering their archives, and that eventually the link will work again. From nilswagenaar at hotmail.com Fri Oct 28 06:33:43 2016 From: nilswagenaar at hotmail.com (nils wagenaar) Date: Fri, 28 Oct 2016 10:33:43 +0000 Subject: [Tutor] Assessing local variable outside function In-Reply-To: <8537jgdgi3.fsf@benfinney.id.au> References: <8537jgdgi3.fsf@benfinney.id.au> Message-ID: Thank you all! It is clear now:) Verstuurd vanaf mijn iPhone > Op 28 okt. 2016 om 19:31 heeft Ben Finney het volgende geschreven: > > Alan Gauld via Tutor writes: > >>> On 28/10/16 02:38, nils wagenaar wrote: >>> Could i use a variable defined in a function in another function? > > My answer would be: You can't because Python variables don't exist > outside their namespace. > > You can make the object available in various ways, but not the variable. > >> By returning it to the caller. > > That's somewhat misleading. Returning the *object* would not grant > access to the local *variable*. > > Nils, it's important to realise that a variable in Python is not > tractable: you can't hand them around, you can't access the name itself. > A Python variable exists only in its namespace, and can't move. > > The variable is (at any given point) bound to an object; you can get > *other* variables bound to the same object by explicitly doing that. > Alan suggests one way. > > Whether that meets your request to ?use a variable defined in a function > in another function? will have to wait for you to check how the Python > data model actually works. Does that answer it, or do you need something > different? > > -- > \ ?Dare to be na?ve.? ?Richard Buckminster Fuller, personal motto | > `\ | > _o__) | > Ben Finney > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Fri Oct 28 22:10:44 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 29 Oct 2016 13:10:44 +1100 Subject: [Tutor] run local script on a remote machine In-Reply-To: <131d9be99cad9352d351837849e96b3d@sonic.net> References: <131d9be99cad9352d351837849e96b3d@sonic.net> Message-ID: <20161029021043.GT15983@ando.pearwood.info> If you're trying to do remote command execution, you should forget about rolling your own, and use a well-established RPC solution. I can recommend either of pyro or rpyc: https://pypi.python.org/pypi/Pyro4 https://pypi.python.org/pypi/rpyc If you need a standard library solution, you can try: https://docs.python.org/3/library/xmlrpc.html -- Steve From sonu311296 at gmail.com Sat Oct 29 00:42:35 2016 From: sonu311296 at gmail.com (SONU KUMAR) Date: Fri, 28 Oct 2016 21:42:35 -0700 Subject: [Tutor] why it is showing attribute error in line7 Message-ID: fname = raw_input("Enter file name: ") if len(fname) < 1 : fname = "mbox-short.txt" fh = open(fname) count = 0 for line in fh: line=line.rstrip if not line.startswith("From"):continue lst=line.split() print lst[1] count=count+1 print "There were", count, "lines in the file with From as the first word" From alan.gauld at yahoo.co.uk Sat Oct 29 03:56:46 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 29 Oct 2016 08:56:46 +0100 Subject: [Tutor] why it is showing attribute error in line7 In-Reply-To: References: Message-ID: Please always post the full error text in future. Meanwhile I'll guess: On 29/10/16 05:42, SONU KUMAR wrote: > fname = raw_input("Enter file name: ") > if len(fname) < 1 : fname = "mbox-short.txt" > fh = open(fname) > count = 0 > for line in fh: > line=line.rstrip missing parens means you reassign line to the method. > if not line.startswith("From"):continue The method does not have a startwith attribute. > lst=line.split() Nor a split method. > > print lst[1] > > count=count+1 > print "There were", count, "lines in the file with From as the first word" 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 From steve at pearwood.info Sat Oct 29 05:44:15 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 29 Oct 2016 20:44:15 +1100 Subject: [Tutor] why it is showing attribute error in line7 In-Reply-To: References: Message-ID: <20161029094414.GV15983@ando.pearwood.info> Hello, and welcome! Please always post the FULL traceback. Python gives you lots of information to debug problems, so you don't have to guess, but when you throw that information away, we have to guess. My guess follows below: On Fri, Oct 28, 2016 at 09:42:35PM -0700, SONU KUMAR wrote: > fname = raw_input("Enter file name: ") > if len(fname) < 1 : fname = "mbox-short.txt" > fh = open(fname) > count = 0 > for line in fh: > line=line.rstrip That's the problem. You are not calling the method, instead you are assigning the method line.rstrip to the variable "line". Watch the difference here: py> line = "some text " py> a = line.rstrip() # with parentheses means call the method py> b = line.rstrip # no parens means the method itself py> print(a) some text py> print(b) So using your code, you say: py> line = line.rstrip # no parens py> print(line) which means when you come to the next line of code, you get an error: > if not line.startswith("From"):continue py> line.startswith('From') Traceback (most recent call last): File "", line 1, in AttributeError: 'builtin_function_or_method' object has no attribute 'startswith' And look at the error message: it tells you *exactly* what is wrong. You have a built-in function or method, not a string. Always read the full traceback. When you have to ask for help, always copy and paste the full traceback. -- Steve From bfishbein79 at gmail.com Sun Oct 30 11:32:46 2016 From: bfishbein79 at gmail.com (Benjamin Fishbein) Date: Sun, 30 Oct 2016 10:32:46 -0500 Subject: [Tutor] looking for image library based on PIL Image Message-ID: <4C298CF5-25BB-4990-B384-D20E7EA1E195@gmail.com> I?m trying to automate a lot of images using PIL?s Image library, but I don?t want to write all the filters and manipulation algorithms myself. Do you know of any good code that people have written that does this? I?m not getting much luck simply googling it, since all the results lead me to basic image manipulators, while I want something more complex. Thanks. -Ben From alan.gauld at yahoo.co.uk Sun Oct 30 12:32:32 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 30 Oct 2016 16:32:32 +0000 Subject: [Tutor] looking for image library based on PIL Image In-Reply-To: <4C298CF5-25BB-4990-B384-D20E7EA1E195@gmail.com> References: <4C298CF5-25BB-4990-B384-D20E7EA1E195@gmail.com> Message-ID: On 30/10/16 15:32, Benjamin Fishbein wrote: > I?m trying to automate a lot of images using PIL?s Image library, > but I don?t want to write all the filters and manipulation > algorithms myself. Do you know of any good code that people > have written that does this? It depends on what kind of image manipulation you want. You might find something on SciKit and there are libraries such as Pymunk and and cgkit for 2&3D modelling. And don't forget Imagemagick has Python bindings too, Blender has a Python API while cgkit also comes with bindings to Maya. As for add-ons for Pillow (the v3 version of PIL) you should ask on their dedicated forum. Last time I looked it was fairly active. -- 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 From joseph.c.slater at gmail.com Mon Oct 31 10:09:00 2016 From: joseph.c.slater at gmail.com (Joseph Slater) Date: Mon, 31 Oct 2016 10:09:00 -0400 Subject: [Tutor] nosetests on travis-ci.org Message-ID: <4FCC2C0A-D21B-472C-9165-5EAF7672C047@gmail.com> I've created a relatively simple package, partly for utility, but partly for self-education. The port installs and works fine on pypi, but I need to know how to run automated tests for my other projects. Specifically, nose tests works at my command line, but fail on travis-ci . I have no understanding why and would appreciate any help. Logs for the failures are at https://travis-ci.org/josephcslater/array_to_latex/builds/171993088 for the project at https://github.com/josephcslater/array_to_latex Thank you, Joe From steve at pearwood.info Mon Oct 31 20:12:31 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 1 Nov 2016 11:12:31 +1100 Subject: [Tutor] nosetests on travis-ci.org In-Reply-To: <4FCC2C0A-D21B-472C-9165-5EAF7672C047@gmail.com> References: <4FCC2C0A-D21B-472C-9165-5EAF7672C047@gmail.com> Message-ID: <20161101001230.GF3365@ando.pearwood.info> Hi Joseph, On Mon, Oct 31, 2016 at 10:09:00AM -0400, Joseph Slater wrote: > I've created a relatively simple package, partly for utility, but > partly for self-education. > > The port installs and works fine on pypi, but I need to know how to > run automated tests for my other projects. > > Specifically, nose tests works at my command line, but fail on > travis-ci . I have no understanding why and would appreciate any help. travis-ci is rather advanced for this list, which is aimed more at beginners still learning the syntax of Python and basic programming. You might be lucky enough to find somebody here who knows travis, but it isn't me :-) You may have better luck on the main Python list: python-list at python.org also available on Usenet as comp.lang.python, as it tends to have people with a much broader range of experience than here. But even there, you'll probably be asked to come up with a minimum example that demonstrates the problem: http://sscce.org/ Good luck! -- Steve From Joaquin.Alzola at lebara.com Mon Oct 31 20:16:18 2016 From: Joaquin.Alzola at lebara.com (Joaquin Alzola) Date: Tue, 1 Nov 2016 00:16:18 +0000 Subject: [Tutor] nosetests on travis-ci.org In-Reply-To: <20161101001230.GF3365@ando.pearwood.info> References: <4FCC2C0A-D21B-472C-9165-5EAF7672C047@gmail.com> <20161101001230.GF3365@ando.pearwood.info> Message-ID: >python-list at python.org >also available on Usenet as comp.lang.python, as it tends to have people >with a much broader range of experience than here. But even there, >you'll probably be asked to come up with a minimum example that >demonstrates the problem: Also try on IRC chat.freenode.net There might be a channel of travis-ci and people might help you. _____ Joaquin This email is confidential and may be subject to privilege. If you are not the intended recipient, please do not copy or disclose its content but contact the sender immediately upon receipt.
>99 10.00 (-0.1%) >class="ThemeColor" target="_blank">Menuwidth="11" height="11" border="0" align="absmiddle" /> >Max Quantity
>100.000
Average Quantity
>822
Previous Order
>96
Max Price
>104
Number of Trades
>383
Min Price
>59
Total Amount
>800
Start
>10
Low
>98