From swdunning at cox.net Sat Mar 1 07:46:02 2014 From: swdunning at cox.net (Scott W Dunning) Date: Fri, 28 Feb 2014 23:46:02 -0700 Subject: [Tutor] Help with "Guess the number" script Message-ID: <43B63C46-3A2D-4374-8A42-EE931BA9A6C4@cox.net> Hello, i am working on a project for learning python and I?m stuck. The directions are confusing me. Please keep in mind I?m very ne to this. The directions are long so I?ll just add the paragraphs I?m confused about and my code if someone could help me out I?d greatly appreciate it! Also, we haven?t learned loops yet so just conditional operators and for some reason we can?t use global variables. from random import randrange randrange(1, 101) from random import seed seed(129) def print_description(): print """Welcome to Guess the Number. I have seleted a secret number in the range 1 ... 100. You must guess the number within 10 tries. I will tell you if you ar high or low, and I will tell you if you are hot or cold.\n""" def get_guess(guess_number): print "(",guess_number,")""Plese enter a guess:" current_guess = raw_input() return int(guess_number) def main(): print_description() secret = 50 current_guess = 1 get_guess(1) if current_guess != secret(): print "Congratulations you win!!" main() Here are the instructions I?m having a hard time with and just not sure I?m doing it correctly. I?m not sure the get_guess function is correct and I?m a little lost with the secret and current_guess variable. From within the body of the main function, immediately after the call to print description, create variable secret and assign it a random number between 1 and 100, generated using the randrange function. You will need to pass two argument to randrange, what do you think they should be? You should be able to use the python help system or online python documentation to make sure you understand the arguments to randrange. After the end of the body of the print description function, define a new global function named get guess that takes a single parameter. Name the parameter guess number, because it will hold the index (1, 2, 3, ..., 10) of current guess attempt. Make the function ask the user to enter guess using the raw input function. The function will return the number entered by the user, after it has been converted to an integer. Return to the main function after the statement that assigned a value to the secret variable. In a new variable named current guess store the result of calling the get guess function with an argument of 1. Run your program to make sure it works correctly. At the end of the main function, check if the current guess matches the secret. If it matches, print ?Congratulations, you win!?. If it does not, print ?Please play again!? Thanks again!!! -------------- next part -------------- An HTML attachment was scrubbed... URL: From swdunning at me.com Sat Mar 1 07:05:29 2014 From: swdunning at me.com (Scott Dunning) Date: Fri, 28 Feb 2014 23:05:29 -0700 Subject: [Tutor] Help with "Guess the Number" script Message-ID: <0483331B-2CC2-4375-A90C-34C5B704468C@me.com> Hello, i am working on a project for learning python and I?m stuck. The directions are confusing me. Please keep in mind I?m very new to this. The directions are long so I?ll just add the paragraphs I?m confused about and my code if someone could help me out I?d greatly appreciate it! Also, we haven?t learned loops yet so just conditional operators and for some reason we can?t use global variables. from random import randrange randrange(1, 101) from random import seed seed(129) def print_description(): print """Welcome to Guess the Number. I have seleted a secret number in the range 1 ... 100. You must guess the number within 10 tries. I will tell you if you ar high or low, and I will tell you if you are hot or cold.\n""" def get_guess(guess_number): print "(",guess_number,")""Plese enter a guess:" current_guess = raw_input() return int(guess_number) def main(): print_description() secret = 50 current_guess = 1 get_guess(1) if current_guess != secret(): print "Congratulations you win!!" main() Here are the instructions I?m having a hard time with and just not sure I?m doing it correctly. I?m not sure the get_guess function is correct and I?m a little lost with the secret and current_guess variable. From within the body of the main function, immediately after the call to print description, create variable secret and assign it a random number between 1 and 100, generated using the randrange function. You will need to pass two argument to randrange, what do you think they should be? You should be able to use the python help system or online python documentation to make sure you understand the arguments to randrange. After the end of the body of the print description function, define a new global function named get guess that takes a single parameter. Name the parameter guess number, because it will hold the index (1, 2, 3, ..., 10) of current guess attempt. Make the function ask the user to enter guess using the raw input function. The function will return the number entered by the user, after it has been converted to an integer. Return to the main function after the statement that assigned a value to the secret variable. In a new variable named current guess store the result of calling the get guess function with an argument of 1. Run your program to make sure it works correctly. At the end of the main function, check if the current guess matches the secret. If it matches, print ?Congratulations, you win!?. If it does not, print ?Please play again!? Thanks again!!! -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Sat Mar 1 08:47:46 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 01 Mar 2014 18:47:46 +1100 Subject: [Tutor] Help with "Guess the number" script References: <43B63C46-3A2D-4374-8A42-EE931BA9A6C4__25474.1337303587$1393659422$gmane$org@cox.net> Message-ID: <85txbil5r1.fsf@benfinney.id.au> Scott W Dunning writes: > def get_guess(guess_number): > print "(",guess_number,")""Plese enter a guess:" > current_guess = raw_input() > return int(guess_number) You've bound the name ?current_guess? to the user's input, but then do nothing with it for the rest of the function; it will be discarded without being used. Then, you use the parameter ?guess_number?, create a new integer from it, and return that integer. I think you've used the wrong name for the ?int()? parameter. -- \ ?The most merciful thing in the world? is the inability of the | `\ human mind to correlate all its contents.? ?Howard Philips | _o__) Lovecraft | Ben Finney From davea at davea.name Sat Mar 1 11:36:51 2014 From: davea at davea.name (Dave Angel) Date: Sat, 1 Mar 2014 05:36:51 -0500 (EST) Subject: [Tutor] Help with "Guess the number" script References: <43B63C46-3A2D-4374-8A42-EE931BA9A6C4__25474.1337303587$1393659422$gmane$org@cox.net> Message-ID: Scott W Dunning Wrote in message: In addition to Ben's observation, you don't use anything random when initializing secret. And you don't store the result of get_guess. -- DaveA From denis.spir at gmail.com Sat Mar 1 14:53:57 2014 From: denis.spir at gmail.com (spir) Date: Sat, 01 Mar 2014 14:53:57 +0100 Subject: [Tutor] Help with "Guess the number" script In-Reply-To: <43B63C46-3A2D-4374-8A42-EE931BA9A6C4@cox.net> References: <43B63C46-3A2D-4374-8A42-EE931BA9A6C4@cox.net> Message-ID: <5311E675.9020102@gmail.com> On 03/01/2014 07:46 AM, Scott W Dunning wrote: > Hello, i am working on a project for learning python and I?m stuck. The directions are confusing me. Please keep in mind I?m very ne to this. The directions are long so I?ll just add the paragraphs I?m confused about and my code if someone could help me out I?d greatly appreciate it! Also, we haven?t learned loops yet so just conditional operators and for some reason we can?t use global variables. > > > from random import randrange > randrange(1, 101) > > from random import seed > seed(129) > > def print_description(): > print """Welcome to Guess the Number. > I have seleted a secret number in the range 1 ... 100. > You must guess the number within 10 tries. > I will tell you if you ar high or low, and > I will tell you if you are hot or cold.\n""" > > def get_guess(guess_number): > print "(",guess_number,")""Plese enter a guess:" > current_guess = raw_input() > return int(guess_number) > > def main(): > print_description() > secret = 50 > current_guess = 1 > get_guess(1) > if current_guess != secret(): > print "Congratulations you win!!" > > main() > > > Here are the instructions I?m having a hard time with and just not sure I?m doing it correctly. I?m not sure the get_guess function is correct and I?m a little lost with the secret and current_guess variable. > > From within the body of the main function, immediately after the call to print description, create variable secret and assign it a random number between 1 and 100, generated using the randrange function. You will need to pass two argument to randrange, what do you think they should be? You should be able to use the python help system or online python documentation to make sure you understand the arguments to randrange. > > After the end of the body of the print description function, define a new global function named get guess that takes a single parameter. Name the parameter guess number, because it will hold the index (1, 2, 3, ..., 10) of current guess attempt. Make the function ask the user to enter guess using the raw input function. The function will return the number entered by the user, after it has been converted to an integer. > > Return to the main function after the statement that assigned a value to the secret variable. In a new variable named current guess store the result of calling the get guess function with an argument of 1. Run your program to make sure it works correctly. > > At the end of the main function, check if the current guess matches the secret. If it matches, print ?Congratulations, you win!?. If it does not, print ?Please play again!? I find directions very confusing. Also, they completely control you while explaining about nothing, like a user manual saying "press this, turn that". This is inappropriate for programming (and anything else): you need to understand! You need the why's and the how's, not only the what's. If not enough, they seem to teach you pretty weird practices: what is the point of the parameter guess_number? It is not a parameter, less so of this function, but a counter proper to the game control, possibly used at the end to write "You won in [counter] trials." But it is not and cannot be used as a parameter to get_guess. Also, what is the point of requiring you to write this game without a loop? You need a loop. If they want to teach you other notions first, they must find another sample program. If the rest of the book is similar, I would encourage you to change. Maybe try one of those (or why not both in //): * Alan Gauld's "Learning to Program": a very good point is this guide teaches to program, in general, *using* Python, mainly: http://www.alan-g.me.uk/l2p/index.htm * Al sweigart's "invent with python": this one teaches python & programming, using games as learning material: http://inventwithpython.com/ The first example in the latter book is precisely "guess my number". So, you can find correct code for it there. d From breamoreboy at yahoo.co.uk Sat Mar 1 16:57:22 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 01 Mar 2014 15:57:22 +0000 Subject: [Tutor] Help with "Guess the Number" script In-Reply-To: <0483331B-2CC2-4375-A90C-34C5B704468C@me.com> References: <0483331B-2CC2-4375-A90C-34C5B704468C@me.com> Message-ID: On 01/03/2014 06:05, Scott Dunning wrote: In addition to the answers you've already had, I suggest that you learn to run code at the interactive prompt, it's a great way of seeing precisely what snippets of code actually do. Also use the print statement in Python 2 or print function in Python 3, again a great way to observe what your code is doing. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From eryksun at gmail.com Sat Mar 1 17:48:25 2014 From: eryksun at gmail.com (eryksun) Date: Sat, 1 Mar 2014 11:48:25 -0500 Subject: [Tutor] When to use multiprocessing Managers? In-Reply-To: References: Message-ID: On Fri, Feb 28, 2014 at 6:31 AM, James Chapman wrote: > > log_Q = multiprocessing.Queue() This is a Queue from multiprocessing.queues. It uses system resources (e.g. a semaphore for the queue capacity) that can be shared with processes on the same machine. A value `put` in a queue.Queue is available immediately: >>> import queue >>> q1 = queue.Queue() >>> try: q1.put('value'); q1.get_nowait() ... except queue.Empty: 'empty' ... 'value' On the other hand, a Queue from multiprocessing.queues writes to a pipe using a background thread, so there can be a small delay: >>> import multiprocessing as mp >>> q2 = mp.Queue() >>> try: q2.put('value'); q2.get_nowait() ... except queue.Empty: 'empty' ... 'empty' >>> q2.get_nowait() 'value' > or whether I create it like this: > > multimanager = multiprocessing.Manager() > log_Q = multimanager.Queue() This is a queue.Queue wrapped by an AutoProxy. For example, its `get` method calls _callmethod('get', *args, **kwds), which connects to the manager, sends the request, and receives the result. The docs demonstrate using a manager with remote processes: http://docs.python.org/3/library/multiprocessing#using-a-remote-manager You can also proxy the Queue type from multiprocessing.queues. In that case, remote processes use a proxy, but local processes can use the queue directly. > Perhaps the manager would be important if I was writing to a Queue and > expecting all threads to see that message? Only 1 thread will `get` the message. From alan.gauld at btinternet.com Sat Mar 1 18:16:02 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 01 Mar 2014 17:16:02 +0000 Subject: [Tutor] Help with "Guess the number" script In-Reply-To: <85txbil5r1.fsf@benfinney.id.au> References: <43B63C46-3A2D-4374-8A42-EE931BA9A6C4__25474.1337303587$1393659422$gmane$org@cox.net> <85txbil5r1.fsf@benfinney.id.au> Message-ID: Scott W Dunning writes: > def get_guess(guess_number): > print "(",guess_number,")""Plese enter a guess:" Aren't you missing a comma before the last string? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Sat Mar 1 18:29:46 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 01 Mar 2014 17:29:46 +0000 Subject: [Tutor] Help with "Guess the number" script In-Reply-To: References: <43B63C46-3A2D-4374-8A42-EE931BA9A6C4__25474.1337303587$1393659422$gmane$org@cox.net> <85txbil5r1.fsf@benfinney.id.au> Message-ID: On 01/03/14 17:16, Alan Gauld wrote: > > Scott W Dunning writes: > >> def get_guess(guess_number): >> print "(",guess_number,")""Plese enter a guess:" > > Aren't you missing a comma before the last string? > I just realized it will work because Python auto joins adjacent string literals. But in this case you should probably just remove both quotes and make it more readable. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From swdunning at cox.net Sun Mar 2 01:43:57 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sat, 1 Mar 2014 17:43:57 -0700 Subject: [Tutor] Help with "Guess the number" script In-Reply-To: References: <43B63C46-3A2D-4374-8A42-EE931BA9A6C4__25474.1337303587$1393659422$gmane$org@cox.net> Message-ID: On Mar 1, 2014, at 12:47 AM, Ben Finney wrote: > You've bound the name ?current_guess? to the user's input, but then do > nothing with it for the rest of the function; it will be discarded > without being used. Hmm, I?m not quite sure I understand. I got somewhat confused because the directions were changed a little and current_guess was removed from the get_guess function. Is this more like what I should be doing? def get_guess(guess_number): raw_input(?Please enter a guess?) guess_number = int(guess_number) return (guess_number) get_guess(1) > > Then, you use the parameter ?guess_number?, create a new integer from > it, and return that integer. I think you've used the wrong name for the > ?int()? parameter. Well, since there are no loops allowed I?m guessing get_guess will be called 9 times. I believe guess_number is the number of tries the user has used. So; (1) Please enter a guess: (2) Please enter a guess: From swdunning at cox.net Sun Mar 2 01:45:25 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sat, 1 Mar 2014 17:45:25 -0700 Subject: [Tutor] Help with "Guess the Number" script In-Reply-To: References: <0483331B-2CC2-4375-A90C-34C5B704468C@me.com> Message-ID: <8D6BCEFC-CED5-4FA6-9AD5-1E3256B957C8@cox.net> On Mar 1, 2014, at 8:57 AM, Mark Lawrence wrote: > On 01/03/2014 06:05, Scott Dunning wrote: > > In addition to the answers you've already had, I suggest that you learn to run code at the interactive prompt, it's a great way of seeing precisely what snippets of code actually do. Also use the print statement in Python 2 or print function in Python 3, again a great way to observe what your code is doing. That makes sense, easier then running the script over and over. From swdunning at cox.net Sun Mar 2 01:52:15 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sat, 1 Mar 2014 17:52:15 -0700 Subject: [Tutor] Help with "Guess the number" script In-Reply-To: References: <43B63C46-3A2D-4374-8A42-EE931BA9A6C4@cox.net> Message-ID: <27132202-0FE6-45BC-99C2-13B2EE33B323@cox.net> On Mar 1, 2014, at 6:53 AM, spir wrote: > > I find directions very confusing. Also, they completely control you while explaining about nothing, like a user manual saying "press this, turn that". This is inappropriate for programming (and anything else): you need to understand! You need the why's and the how's, not only the what?s. Trust me I?m confused by the directions as well. The point of the ?project? is to learn the conditional operators (if, else, elif). > > If not enough, they seem to teach you pretty weird practices: what is the point of the parameter guess_number? guess_number is the number of guesses the user has used because there are only 10 allowed. So; (1) Please enter a number (2) Please try again: (3) ????????.? (4) ???????.." > It is not a parameter, less so of this function, but a counter proper to the game control, possibly used at the end to write "You won in [counter] trials." But it is not and cannot be used as a parameter to get_guess. Also, what is the point of requiring you to write this game without a loop? You need a loop. If they want to teach you other notions first, they must find another sample program. We haven?t learned loops yet so he wanted us to try and just use conditional functions and be repetitive I guess. I?m not even worries about that part, I?m just trying to get through this part first because it?s confusing me. I can post more of the instructions if needed too. > > If the rest of the book is similar, I would encourage you to change. Maybe try one of those (or why not both in //): > > * Alan Gauld's "Learning to Program": a very good point is this guide teaches to program, in general, *using* Python, mainly: > http://www.alan-g.me.uk/l2p/index.htm > > * Al sweigart's "invent with python": this one teaches python & programming, using games as learning material: > http://inventwithpython.com/ Thank you for the links!! -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Sun Mar 2 08:43:59 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 02 Mar 2014 18:43:59 +1100 Subject: [Tutor] Help with "Guess the number" script References: <43B63C46-3A2D-4374-8A42-EE931BA9A6C4__25474.1337303587$1393659422$gmane$org@cox.net> Message-ID: <85zjl9jb9c.fsf@benfinney.id.au> Scott W Dunning writes: > On Mar 1, 2014, at 12:47 AM, Ben Finney wrote: > > > You've bound the name ?current_guess? to the user's input, but then do > > nothing with it for the rest of the function; it will be discarded > > without being used. > Hmm, I?m not quite sure I understand. I got somewhat confused because > the directions were changed a little and current_guess was removed > from the get_guess function. Removed by whom? It is still there in the example you posted, and it's ideal for use. > Is this more like what I should be doing? > > def get_guess(guess_number): > raw_input(?Please enter a guess?) > guess_number = int(guess_number) > return (guess_number) > get_guess(1) No, that's the opposite direction :-) Inside the ?get_guess? function you should use as many names as you need for the different purposes. So, you have one name ?guess_number? bound to the function's parameter. Don't bind anything else to it! Then, for the return value from ?raw_input?, you should choose a different suitable name and bind that name to the value (with an assignment statement). Then, for the computed result, you should choose yet another suitable name, and bind *that* name to the computed value. All these different names will make clear in the code what the meaning of each value is. -- \ ?Why should I care about posterity? What's posterity ever done | `\ for me?? ?Groucho Marx | _o__) | Ben Finney From ben+python at benfinney.id.au Sun Mar 2 08:48:37 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 02 Mar 2014 18:48:37 +1100 Subject: [Tutor] Help with "Guess the number" script References: <43B63C46-3A2D-4374-8A42-EE931BA9A6C4__25474.1337303587$1393659422$gmane$org@cox.net> <85zjl9jb9c.fsf@benfinney.id.au> Message-ID: <85vbvxjb1m.fsf@benfinney.id.au> Ben Finney writes: > So, you have one name ?guess_number? bound to the function's parameter. > Don't bind anything else to it! By which I mean, don't bind that name to anything else in the function (don't re-assign any other value to that name in the function). Keep that name's meaning by leaving it bound to the parameter value. -- \ ?When I was a baby I kept a diary. Recently I was re-reading | `\ it, it said ?Day 1: Still tired from the move. Day 2: Everybody | _o__) talks to me like I'm an idiot.?? ?Steven Wright | Ben Finney From davea at davea.name Sun Mar 2 13:37:49 2014 From: davea at davea.name (Dave Angel) Date: Sun, 2 Mar 2014 07:37:49 -0500 (EST) Subject: [Tutor] Help with "Guess the number" script References: <43B63C46-3A2D-4374-8A42-EE931BA9A6C4__25474.1337303587$1393659422$gmane$org@cox.net> Message-ID: Scott W Dunning Wrote in message: > > On Mar 1, 2014, at 12:47 AM, Ben Finney wrote: > >> You've bound the name ???current_guess??? to the user's input, but then do >> nothing with it for the rest of the function; it will be discarded >> without being used. > Hmm, I???m not quite sure I understand. I got somewhat confused because the directions were changed a little and current_guess was removed from the get_guess function. Is this more like what I should be doing? > > def get_guess(guess_number): > raw_input(???Please enter a guess???) > guess_number = int(guess_number) > return (guess_number) That block of code is a huge step backwards from what you already had. So let's go back a step. def get_guess(guess_number): ?? ?? print "(",guess_number,")""Plese enter a guess:" ?? ?? current_guess = raw_input() ?? ?? return int(guess_number First thing to do is decide what that function is 'supposed' to do. What do you suppose a caller might expect as a return value? Once you've decided a description, write it down as a set of comments (or docstring, but that's another lesson). > >> >> Then, you use the parameter ???guess_number???, create a new integer from >> it, and return that integer. I think you've used the wrong name for the >> ???int()??? parameter. > Well, since there are no loops allowed I???m guessing get_guess will be called 9 times. It will be called (up to) 9 times even after you learn about loops. It's called get_guess, not get_guesses. > I believe guess_number is the number of tries the user has used. > So; > (1) Please enter a guess: > (2) Please enter a guess: If that's a specification, then add it to your comments above. I would guess you're missing a print in the function. -- DaveA From emeraudekwilu at hotmail.com Sun Mar 2 19:14:14 2014 From: emeraudekwilu at hotmail.com (Emeraude kwilu) Date: Sun, 2 Mar 2014 18:14:14 +0000 Subject: [Tutor] (no subject) Message-ID: Read in a list of English words. Randomly select a long word and show it to the contestant. Challenge the contestant to find shorter words using letters from the long word. They should type each one and press Enter. After 30seconds,the game stops accepting entries. It evaluates the user?s submissions and finds which ones were valid words. It prints the final tally, and shows the words the user guessed correctly, and the invalid words the user submitted. Finally it shows all the valid words that could be made. selectWord = [ "abjuring",] #this is the random word selectedvalidWordList = ['bar','bug'...] # this is all the words using letters from the long wordrandWord = random.choice(selectWord) time.time () = nowcount = 0while time() <= now +30: print raw_input("enter a word in abjuring:") count += 1#? I am stuck there my loop is not working and I don't know how to print the user word etherI have to print the number of the valid word the enter and print it also if they print invalid word I have to print it as wellat the end I prunt all the valid word. I know I have to use if and else statement but I'm not able to do so :( example:you enter 2 valid ['bar','jar']you enter 2 invalid [' jirg', 'rig']the full list is: ['bar','bug',...] -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Mar 2 20:37:30 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 02 Mar 2014 19:37:30 +0000 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On 02/03/14 18:14, Emeraude kwilu wrote: > selectWord = [ "abjuring",] #this is the random word selected > validWordList = ['bar','bug'...] Obviously this is not your real code since this is not valid syntax. And since its clearly homework it will help us if you post your actual code that is failing plus any error messages(in their entirety) > randWord = random.choice(selectWord) > > time.time () = now > count = 0 > while time() <= now +30: > print raw_input("enter a word in abjuring:") You need to store the word that the user entered. Here you just print it then throw it away. You will need another variable, and probably a list as well, to hold the previous words entered. > count += 1 > I am stuck there my loop is not working Define 'not working' What is happening? What did you expect to happen? Being precise in your descriptions is very important. Often describing the problem in detail is enough for you to find the answer to it yourself! > and I don't know how to print the user word ether You seem to be printing the word the user entered OK, That is all you are doing with it in fact. What you are not doing is comparing it to the valid words list. That's where your if/else code should come in. > I have to print the number of the valid word the enter and print it also > if they print invalid word I have to print it as well > > at the end I prunt all the valid word. I know I have to use if and else > statement but I'm not able to do so :( Show us your actual code plus any error messages. It won't do any harm to tell us the python version too, it's obviously Python 2.X but what is X? 2.5, 2.6 or 2.7? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From amonroe at columbus.rr.com Sun Mar 2 20:38:34 2014 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun, 2 Mar 2014 14:38:34 -0500 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <1299002762.20140302143834@columbus.rr.com> > I am stuck there my loop is not working > ... > I know I have to use if and > else statement but I'm not able to do so :( Hint: Set the assignment aside and write a couple smaller practice programs. Like a very simple one that just asks for a word and prints that word. Or a simple one that checks if 2 is greater than 1. In other words, some baby steps before you tackle the real assignment. Alan From breamoreboy at yahoo.co.uk Sun Mar 2 22:12:38 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 02 Mar 2014 21:12:38 +0000 Subject: [Tutor] What is the unladen airspeed velocity of a swallow in flight? In-Reply-To: References: Message-ID: On 02/03/2014 18:14, Emeraude kwilu wrote: [snipped as it's been answered] Or to put it another way, please use a sensible subject line, there may be some intelligent people on this list, but we're not mind readers :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From tsimko at princeton.edu Sun Mar 2 22:10:02 2014 From: tsimko at princeton.edu (Tyler Simko) Date: Sun, 2 Mar 2014 16:10:02 -0500 Subject: [Tutor] Equality Check. Message-ID: <4FDA15C7-8FB4-4C74-B100-841DDE4261F3@princeton.edu> Hi all! I'm embarrassingly new at Python, so please forgive my probably simple mistakes. So I called readlines() on a file, and I'm wondering how I can check the equality of a specific line with a raw_input set variable as a condition. For example, file = open('filename.txt,' 'r') file.readlines() variable_name = raw_input() if file[2] == variable_name: #whatever This approach hasn't worked so far, does anyone have any tips? Thanks so much!! -Tyler From breamoreboy at yahoo.co.uk Mon Mar 3 00:29:16 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 02 Mar 2014 23:29:16 +0000 Subject: [Tutor] Equality Check. In-Reply-To: <4FDA15C7-8FB4-4C74-B100-841DDE4261F3@princeton.edu> References: <4FDA15C7-8FB4-4C74-B100-841DDE4261F3@princeton.edu> Message-ID: On 02/03/2014 21:10, Tyler Simko wrote: > Hi all! > > I'm embarrassingly new at Python, so please forgive my probably simple mistakes. > > So I called readlines() on a file, and I'm wondering how I can check the equality of a specific line with a raw_input set variable as a condition. For example, > > file = open('filename.txt,' 'r') > file.readlines() > variable_name = raw_input() > if file[2] == variable_name: > #whatever > > This approach hasn't worked so far, does anyone have any tips? Thanks so much!! > > -Tyler You haven't stripped the newline before doing the comparison. You also don't have to read the whole file just to compare a specific line. I'll leave you to find out how :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From joel.goldstick at gmail.com Mon Mar 3 00:32:31 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 2 Mar 2014 18:32:31 -0500 Subject: [Tutor] Equality Check. In-Reply-To: References: <4FDA15C7-8FB4-4C74-B100-841DDE4261F3@princeton.edu> Message-ID: On Mar 2, 2014 6:30 PM, "Mark Lawrence" wrote: > > On 02/03/2014 21:10, Tyler Simko wrote: >> >> Hi all! >> >> I'm embarrassingly new at Python, so please forgive my probably simple mistakes. >> >> So I called readlines() on a file, and I'm wondering how I can check the equality of a specific line with a raw_input set variable as a condition. For example, >>readlines result must be put somewhere >> file = open('filename.txt,' 'r') >> file.readlines() >> variable_name = raw_input() >> if file[2] == variable_name: >> #whatever >> >> This approach hasn't worked so far, does anyone have any tips? Thanks so much!! >> >> -Tyler > > > You haven't stripped the newline before doing the comparison. You also don't have to read the whole file just to compare a specific line. I'll leave you to find out how :) > > -- > My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. > > Mark Lawrence > > --- > This email is free from viruses and malware because avast! Antivirus protection is active. > http://www.avast.com > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Mon Mar 3 00:38:43 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sun, 2 Mar 2014 15:38:43 -0800 Subject: [Tutor] Equality Check. In-Reply-To: <4FDA15C7-8FB4-4C74-B100-841DDE4261F3@princeton.edu> References: <4FDA15C7-8FB4-4C74-B100-841DDE4261F3@princeton.edu> Message-ID: The call to readlines () has a return value that is currently being dropped to the floor. Look at its value. Feel free to ask more questions. Good luck! -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Mar 3 00:44:04 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 02 Mar 2014 23:44:04 +0000 Subject: [Tutor] Equality Check. In-Reply-To: <4FDA15C7-8FB4-4C74-B100-841DDE4261F3@princeton.edu> References: <4FDA15C7-8FB4-4C74-B100-841DDE4261F3@princeton.edu> Message-ID: On 02/03/14 21:10, Tyler Simko wrote: > So I called readlines() on a file, and I'm wondering how > I can check the equality of a specific line with a raw_input > file = open('filename.txt,' 'r') > file.readlines() This opens the file and reads all the lines but it doesn't store the result anywhere so you just throw those lines away. The recommended way to do this in Python nowadays is: with open('filename.txt') as infile: for line in infile: # process line here > variable_name = raw_input() > if file[2] == variable_name: file is a file object you cannot index into it using [2]. But even if you had used readlines and stored the result checking line by line as shown above is probably a better approach. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From breamoreboy at yahoo.co.uk Mon Mar 3 01:01:17 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 03 Mar 2014 00:01:17 +0000 Subject: [Tutor] Equality Check. In-Reply-To: References: <4FDA15C7-8FB4-4C74-B100-841DDE4261F3@princeton.edu> Message-ID: On 02/03/2014 23:38, Danny Yoo wrote: > The call to readlines () has a return value that is currently being > dropped to the floor. Look at its value. > > Feel free to ask more questions. Good luck! > He'll need it after reading my response, I must stop replying when I'm knackered and not thinking straight :( -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From ben+python at benfinney.id.au Mon Mar 3 01:16:59 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 03 Mar 2014 11:16:59 +1100 Subject: [Tutor] Equality Check. References: <4FDA15C7-8FB4-4C74-B100-841DDE4261F3@princeton.edu> Message-ID: <85iorwjfus.fsf@benfinney.id.au> Tyler Simko writes: > I'm embarrassingly new at Python, so please forgive my probably simple > mistakes. Welcome, and congratulations on starting with Python! No forgiveness needed for asking questions or making mistakes; the important thing is to learn from both. > So I called readlines() on a file, and I'm wondering how I can check > the equality of a specific line with a raw_input set variable as a > condition. You don't need to use ?file.readlines? for this purpose; that method consumes the entire file, which you don't need. You only need the specific line. You could iterate over the file, discarding lines, until you get to the one line you need, and bind a name to just that line. > For example, > > file = open('filename.txt,' 'r') Best not to clobber the built-in name ?file?. Choose a more descriptive name for the *purpose* of this value; e.g. ?input_file?. > file.readlines() This consumes the entire file, and returns a new sequence containing each line as an item of the sequence. You then throw this new object away, because you haven't bound anything to it. > variable_name = raw_input() > if file[2] == variable_name: > #whatever Again, ?variable_name? is utterly opaque as to the purpose. Choose names that clearly indicate what the value *means* in the program. > This approach hasn't worked so far, does anyone have any tips? You're attempting to access an item of the file. But files don't have items that can be indexed that way. Files are, on the other hand, iterable. You get each line of a file by iterating over the file object. (The ?file.readlines? method is specific to file objects, and does the entire iteration behind the scenes. That might be what is confusing you.) This is the difference between iterables (objects which you can loop over to get an object each iteration), versus sequences (objects with a sequence of items all present and addressible by index). All sequences are iterable, but not all iterables are sequences. A Python file object is an iterable, but is not a sequence. -- \ ?I wish there was a knob on the TV to turn up the intelligence. | `\ There's a knob called ?brightness? but it doesn't work.? | _o__) ?Eugene P. Gallagher | Ben Finney From swdunning at cox.net Mon Mar 3 02:32:34 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sun, 2 Mar 2014 18:32:34 -0700 Subject: [Tutor] Help with "Guess the number" script In-Reply-To: References: <43B63C46-3A2D-4374-8A42-EE931BA9A6C4__25474.1337303587$1393659422$gmane$org@cox.net> Message-ID: On Mar 2, 2014, at 12:43 AM, Ben Finney wrote: > > No, that's the opposite direction :-) Inside the ?get_guess? function > you should use as many names as you need for the different purposes. > > So, you have one name ?guess_number? bound to the function's parameter. > Don't bind anything else to it! > > Then, for the return value from ?raw_input?, you should choose a > different suitable name and bind that name to the value (with an > assignment statement). > > Then, for the computed result, you should choose yet another suitable > name, and bind *that* name to the computed value. > > All these different names will make clear in the code what the meaning > of each value is. > Ok, I see. So, I think I got a good portion of this done thanks to you guys and understanding the directions a little better. I?ll post my code. For some reason I?m not sure what the user_guess variable in the get_guess is actually doing, or if it?s even an appropriate variable name?? Also, I?m going to bold another part I?m struggling with about the number being out of range, I?m not sure I?m going in the right direction with that, mainly because it does not work. Here is what I have so far? from random import randrange randrange(1, 101) from random import seed seed(129) def print_description(): print """Welcome to Guess the Number. I have seleted a secret number in the range 1 ... 100. You must guess the number within 10 tries. I will tell you if you ar high or low, and I will tell you if you are hot or cold.\n""" def get_guess(guess_number): promt = "(" + str(guess_number) +") Please enter a guess:" user_guess = raw_input(promt) user_guess = int(user_guess) return user_guess def print_hints(secrets, guess): if guess < 0 or guess> 101: print "Out of range!" def main(): print_description() secret = randrange(1,101) current_guess = get_guess(1) if secret == current_guess: print "Congratulations, you win!" else: print "Please play again" print "The secret number was", secret main() print_hints() -------------- next part -------------- An HTML attachment was scrubbed... URL: From swdunning at cox.net Mon Mar 3 05:03:36 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sun, 2 Mar 2014 21:03:36 -0700 Subject: [Tutor] Help with "Guess the number" script In-Reply-To: References: <43B63C46-3A2D-4374-8A42-EE931BA9A6C4__25474.1337303587$1393659422$gmane$org@cox.net> Message-ID: This is what Im having trouble with now. Here are the directions I?m stuck on and what I have so far, I?ll bold the part that?s dealing with the instructions if anyone could help me figure out where I?m going wrong. Thanks! from random import randrange randrange(1, 101) from random import seed seed(129) def print_description(): print """Welcome to Guess the Number. I have seleted a secret number in the range 1 ... 100. You must guess the number within 10 tries. I will tell you if you ar high or low, and I will tell you if you are hot or cold.\n""" def get_guess(guess_number): promt = "(" + str(guess_number) +") Please enter a guess:" user_guess = raw_input(promt) user_guess = int(user_guess) return user_guess def print_hints(secrets, guess): secret_number = secret guess = guess if guess < 0 or user_guess> 101: print "Out of range!" def main(): print_description() secret = randrange(1,101) current_guess = get_guess(1) if current_guess != secret: print_hints(secret_number, guess) current_guess = get_guess(2) if secret == current_guess: print "Congratulations, you win!" else: print "Please play again" print "The secret number was", secret main() Just below the body of the get guess function, define a new function named print hints that takes two arguments. The first is a secret num- ber and is kept in a parameter named secret. The second is a guess made by the user and it is held in a parameter named guess. The user?s guess is supposed to be within the range 1 ... 100. Write a conditional statement that checks if the guess is out of that range, and if it is print ?out of range? in the body of the print hints function. Now we are going to give the user the option to make a second guess. You must add code to the main function immediately after assignment statement you wrote for task 7. Write a conditional statement to check if the current guess does not match the secret number. If the numbers to not match, in the body of the conditional statement you will do two things. (a) call print hints to give the user hints, (b) re-assign current guess to the result of calling get guess with an argument of 2. -- -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Mon Mar 3 09:51:35 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 03 Mar 2014 19:51:35 +1100 Subject: [Tutor] Help with "Guess the number" script References: <43B63C46-3A2D-4374-8A42-EE931BA9A6C4__25474.1337303587$1393659422$gmane$org@cox.net> Message-ID: <8538izk6lk.fsf@benfinney.id.au> Scott W Dunning writes: > This is what Im having trouble with now. Here are the directions I?m > stuck on and what I have so far, I?ll bold the part that?s dealing > with the instructions if anyone could help me figure out where I?m > going wrong. ?Bold? assumes that markup of text will survive; that's not reliable, since this is a text-only medium and only the plain text will reliably survive to all readers. Instead, explain what is confusing you, and if you need to show someone else's words, use the plain-text quotation. > def get_guess(guess_number): > promt = "(" + str(guess_number) +") Please enter a guess:" You're creating a prompt string, so this is a good choice of name; except that its correct spelling is ?prompt?. > user_guess = raw_input(promt) > user_guess = int(user_guess) These are two separate values, why are you binding one name and then immediately re-binding the same name to a different value? Have a think about what each intermediate value *means*, and choose names on that basis. This is valuable! Thinking about what the values mean is vital to understanding what the program is doing, which is of course a big part of what you're in this to learn. > def print_hints(secrets, guess): > secret_number = secret You never use this ?secret_number? name again, so the binding is useless. What was your intention? You also never use the ?secrets? parameter; and the ?secret? name was not bound before you used it. Have you mis-spelled one of those? > guess = guess I don't know what the point of this no-op assignment is. What are you trying to do? > if guess < 0 or user_guess> 101: Likewise, you never bind the name ?user_guess?. Where are you expecting it to be bound? I suspect at this point you've been flailing around without much understanding of the changes you're making. This leads to a confused mass of code that you can't understand or explain. Better would be to experiment at the interactive Python prompt to test what these changes *do*, before putting them into your code. Reduce the mechanisms down to very minimal cases, and try them out; confirm your assumptions and guesses. Only then should you plan a change to the program file. -- \ ?I must have a prodigious quantity of mind; it takes me as much | `\ as a week sometimes to make it up.? ?Mark Twain, _The Innocents | _o__) Abroad_ | Ben Finney From denis.spir at gmail.com Mon Mar 3 11:27:35 2014 From: denis.spir at gmail.com (spir) Date: Mon, 03 Mar 2014 11:27:35 +0100 Subject: [Tutor] Help with "Guess the number" script In-Reply-To: References: <43B63C46-3A2D-4374-8A42-EE931BA9A6C4__25474.1337303587$1393659422$gmane$org@cox.net> Message-ID: <53145917.4040209@gmail.com> On 03/03/2014 05:03 AM, Scott W Dunning wrote: Ben Finney makes numerous fine comments already. I'll add a few, some on the same points but but expressed a bit differently (case it helps). > This is what Im having trouble with now. Here are the directions I?m stuck on and what I have so far, I?ll bold the part that?s dealing with the instructions if anyone could help me figure out where I?m going wrong. > > Thanks! > > from random import randrange > randrange(1, 101) > from random import seed > seed(129) > > def print_description(): > print """Welcome to Guess the Number. > I have seleted a secret number in the range 1 ... 100. > You must guess the number within 10 tries. > I will tell you if you ar high or low, and > I will tell you if you are hot or cold.\n""" > > def get_guess(guess_number): > promt = "(" + str(guess_number) +") Please enter a guess:" > user_guess = raw_input(promt) > user_guess = int(user_guess) > return user_guess Very good choice of variable name for 'promt'. (Apart from ortography, but since you are consistent with the error... ;-) There are 2 user guesses here, and only 1 variable, thus 1 name. The name should say what (idea) the variable represents in the program; this should be said by the name's *meaning*. It is one of the greatest difficulties in programming. How would you define what these variables represent, using everyday language? My own definitions would lead me to choose the following variable names: guess_text = raw_input(promt) guess_number = int(user_guess) return guess_number Note: it is especially obviuos that these are 2 separate numbers, since they do not even are of the same type (a piece of text, or "string", vs a number, here an "int"). Good naming is very, very hard; differences of naming can make some piece of program nearly trivial or instead nearly impossible to understand; often bad naming is worse than hypothetical randomly chosen names, because bad naming *misleads* your thinking. Changing the value of a local variable is always, or nearly, a sign that there are here 2 ideas which should be represented by 2 variables with 2 names. Example of 2 programming styles (note the difference in ease of understanding, even if you don't know the python features used here): def get_data (data): data = File(data) # (a file) data = data.read() # (a piece of text) data = data.split("") # (a list of words) return data ... data = get_data("data.text") def data_words (file_name): data_file = File(file_name) # (a file) text = data_file.read() # (a piece of text) words = text.split(" ") # (a list of words) return words ... words = data_words("data.text") (A special case is loop variables, but even then you only write the assignment once, the value chages across multiple passes on the same code. The only real exception is accumulators, like for computing a sum, which need to be first initialised to a start value, often 0.) > def print_hints(secrets, guess): > secret_number = secret > guess = guess > if guess < 0 or user_guess> 101: > print "Out of range!" Parameters are input variables. Once they are given execution values by a call like print_hints(input_value1, input_value2) these variables exist _inside_ the function body (each with a name and a value). As if functions were defined like: def print_hints: # note: no param secret = input_value1 guess = input_value2 ... use these variables ... This is more or less what the language does for you. This is the whole point of defining parameters, in fact. So, _you_ do not need to _rebind_ parameters to local variables; they already are local variables. In addition, you are not consistent with variable _names_, evendently, so your programs have no chance to work. This is an annoying, but necessary part of programming. But the language will always tell about such errors, at once, *if and only if* the wrong name does *not* otherwise exist. --> pay attention! > def main(): > print_description() > secret = randrange(1,101) > current_guess = get_guess(1) > if current_guess != secret: > print_hints(secret_number, guess) > current_guess = get_guess(2) * 'secret_number' appears from nowhere: pay attention! * To be more coherent checking if the guess is right or wrong (or too high or too low) should be done in function print_hints as well. This function _evaluates_ the guess (maybe it should be renamed). > if secret == current_guess: > print "Congratulations, you win!" > else: > print "Please play again" > print "The secret number was", secret These are (also) hints to the player, actually, aren't they? > main() d From denis.spir at gmail.com Mon Mar 3 11:29:26 2014 From: denis.spir at gmail.com (spir) Date: Mon, 03 Mar 2014 11:29:26 +0100 Subject: [Tutor] Help with "Guess the number" script In-Reply-To: <53145917.4040209@gmail.com> References: <43B63C46-3A2D-4374-8A42-EE931BA9A6C4__25474.1337303587$1393659422$gmane$org@cox.net> <53145917.4040209@gmail.com> Message-ID: <53145986.9070905@gmail.com> On 03/03/2014 11:27 AM, spir wrote: > How would you define what these variables represent, using everyday language? My > own definitions would lead me to choose the following variable names: > guess_text = raw_input(promt) > guess_number = int(user_guess) > return guess_number sorry, should be: > guess_text = raw_input(promt) > guess_number = int(guess_text) > return guess_number d From james at uplinkzero.com Mon Mar 3 12:45:40 2014 From: james at uplinkzero.com (James Chapman) Date: Mon, 3 Mar 2014 11:45:40 +0000 Subject: [Tutor] When to use multiprocessing Managers? In-Reply-To: References: Message-ID: Thanks for the explanation. Is there any reason or case you can think of where on a single system you would use the manager (proxied) queue over the multiprocessing (piped) queue? Actually I can probably answer this myself... The manager could potentially be extended to do some kind of data validation / error checking before submitting to the Queue. This could be important if the data going into the Queue was for example, user generated. Hmm, yeah I'd say question answered. Thanks eryksun. -- James On 1 March 2014 16:48, eryksun wrote: > On Fri, Feb 28, 2014 at 6:31 AM, James Chapman wrote: >> >> log_Q = multiprocessing.Queue() > > This is a Queue from multiprocessing.queues. It uses system resources > (e.g. a semaphore for the queue capacity) that can be shared with > processes on the same machine. > > A value `put` in a queue.Queue is available immediately: > > >>> import queue > >>> q1 = queue.Queue() > >>> try: q1.put('value'); q1.get_nowait() > ... except queue.Empty: 'empty' > ... > 'value' > > On the other hand, a Queue from multiprocessing.queues writes to a > pipe using a background thread, so there can be a small delay: > > >>> import multiprocessing as mp > >>> q2 = mp.Queue() > >>> try: q2.put('value'); q2.get_nowait() > ... except queue.Empty: 'empty' > ... > 'empty' > >>> q2.get_nowait() > 'value' > >> or whether I create it like this: >> >> multimanager = multiprocessing.Manager() >> log_Q = multimanager.Queue() > > This is a queue.Queue wrapped by an AutoProxy. For example, its `get` > method calls _callmethod('get', *args, **kwds), which connects to the > manager, sends the request, and receives the result. > > The docs demonstrate using a manager with remote processes: > > http://docs.python.org/3/library/multiprocessing#using-a-remote-manager > > You can also proxy the Queue type from multiprocessing.queues. In that > case, remote processes use a proxy, but local processes can use the > queue directly. > >> Perhaps the manager would be important if I was writing to a Queue and >> expecting all threads to see that message? > > Only 1 thread will `get` the message. From eryksun at gmail.com Mon Mar 3 16:40:23 2014 From: eryksun at gmail.com (eryksun) Date: Mon, 3 Mar 2014 10:40:23 -0500 Subject: [Tutor] When to use multiprocessing Managers? In-Reply-To: References: Message-ID: On Mon, Mar 3, 2014 at 6:45 AM, James Chapman wrote: > Thanks for the explanation. > > Is there any reason or case you can think of where on a single system > you would use the manager (proxied) queue over the multiprocessing > (piped) queue? Not really. But a manager also lets you share lists, dicts, namespaces, or other registered types. Note that a proxy isn't thread safe, so it should be used by only a single thread, or with a lock. > The manager could potentially be extended to do some kind of data > validation / error checking before submitting to the Queue. This could > be important if the data going into the Queue was for example, user > generated. You could have another function that does that, or subclass multiprocessing.queues.Queue to override its `put` method. From gb.gabrielebrambilla at gmail.com Tue Mar 4 02:00:52 2014 From: gb.gabrielebrambilla at gmail.com (Gabriele Brambilla) Date: Mon, 3 Mar 2014 20:00:52 -0500 Subject: [Tutor] numerical problem Message-ID: Hi, I'm doing a sum in a for loop: www is the quantity I add. MYMAP[i, j, k] = MYMAP[i, j, k] + www MYMAP is a numpy array I have strong reasons to think that in this operation happens some numerical error...Have you suggestions to discover where it is? thanks Gabriele -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Tue Mar 4 03:01:16 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 04 Mar 2014 13:01:16 +1100 Subject: [Tutor] numerical problem References: Message-ID: <85lhwqhgcz.fsf@benfinney.id.au> Gabriele Brambilla writes: > www is the quantity I add. > > MYMAP[i, j, k] = MYMAP[i, j, k] + www > > MYMAP is a numpy array Unfortunately, we have no idea what values are in ?MYMAP? nor ?www?. So it's difficult for us to see what might be causing any problem, or even whether there is any problem. > I have strong reasons to think that in this operation happens some > numerical error...Have you suggestions to discover where it is? Can you show a complete example which demonstrates that there is an error? For example:: >>> import numpy >>> map = numpy.array([10, 20, 30]) >>> map[1] + 4 24 Please show a simple, self-contained, correct example like the above, which demonstrates the problematic behaviour. You'll also need to be more descriptive of what you think the problem is: What are you expecting? What are you experiencing instead? -- \ ?Not using Microsoft products is like being a non-smoker 40 or | `\ 50 years ago: You can choose not to smoke, yourself, but it's | _o__) hard to avoid second-hand smoke.? ?Michael Tiemann | Ben Finney From dyoo at hashcollision.org Tue Mar 4 03:01:28 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 3 Mar 2014 18:01:28 -0800 Subject: [Tutor] numerical problem In-Reply-To: References: Message-ID: > I'm doing a sum in a for loop: > > www is the quantity I add. > > MYMAP[i, j, k] = MYMAP[i, j, k] + www > > MYMAP is a numpy array > > I have strong reasons to think that in this operation happens some numerical > error...Have you suggestions to discover where it is? Hi Gabriele, Can you explain those reasons why you suspect that this operation is responsible? Otherwise, we can not give you as good suggestions as we'd like. If you have literal error messages, that would also be helpful to present those to us. Basically, if you can provide a code snippet of what you're doing, then we can independently try to reproduce the error you're seeing. The question above omits too much details because it prevents folks from knowing that they are answering the right question. Here is an example of a program that adds a delta to every element in a 3d numpy array. ###################################### >>> import numpy as np >>> x = np.array([[[ 0, 1, 2], ... [ 3, 4, 5], ... [ 6, 7, 8]], ... [[ 9, 10, 11], ... [12, 13, 14], ... [15, 16, 17]], ... [[18, 19, 20], ... [21, 22, 23], ... [24, 25, 26]]]) >>> x + 42 array([[[42, 43, 44], [45, 46, 47], [48, 49, 50]], [[51, 52, 53], [54, 55, 56], [57, 58, 59]], [[60, 61, 62], [63, 64, 65], [66, 67, 68]]]) ###################################### Note: adding a scalar to the numpy array has the addition apply pointwise to every component of the array. This is the direct and natural approach. When you mention "loop" in your question above, this makes me pause. If you are doing an explicit loop, as discussed in: http://docs.scipy.org/doc/numpy/reference/arrays.nditer.html then it would be very helpful to see the code you are doing. From steve at pearwood.info Tue Mar 4 03:02:02 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 4 Mar 2014 13:02:02 +1100 Subject: [Tutor] numerical problem In-Reply-To: References: Message-ID: <20140304020202.GO28804@ando> On Mon, Mar 03, 2014 at 08:00:52PM -0500, Gabriele Brambilla wrote: > Hi, > > I'm doing a sum in a for loop: > > www is the quantity I add. > > MYMAP[i, j, k] = MYMAP[i, j, k] + www > > MYMAP is a numpy array > > I have strong reasons to think that in this operation happens some > numerical error...Have you suggestions to discover where it is? You are almost certainly correct. Unless all the numbers are exact integers, nearly every floating point operation will add some error. Without seeing your code, and some representative sample data, it is impossible to tell whether the error is tiny or huge. Tiny error: MYMAP[1, j, k] = 1.001 www = 0.25 Huge error: MYMAP[1, j, k] = 1.001e19 www = 0.25 -- Steven From gb.gabrielebrambilla at gmail.com Tue Mar 4 04:44:07 2014 From: gb.gabrielebrambilla at gmail.com (Gabriele Brambilla) Date: Mon, 3 Mar 2014 22:44:07 -0500 Subject: [Tutor] numerical problem In-Reply-To: <20140304020202.GO28804@ando> References: <20140304020202.GO28804@ando> Message-ID: ok, the things I get is very specific. my results differs from the other guy's ones with which I compare them for slightly details. We fit the data with a function and we obtain different but similar values. our fit routines on the same data return the same results. So we produce different data. the values in www are like 1.01e-134 and also smaller, and I sum values like this: there could be any problem summing so small numbers? is there a Python guide that helps in using strange values numbers? thanks Gabriele 2014-03-03 21:02 GMT-05:00 Steven D'Aprano : > On Mon, Mar 03, 2014 at 08:00:52PM -0500, Gabriele Brambilla wrote: > > Hi, > > > > I'm doing a sum in a for loop: > > > > www is the quantity I add. > > > > MYMAP[i, j, k] = MYMAP[i, j, k] + www > > > > MYMAP is a numpy array > > > > I have strong reasons to think that in this operation happens some > > numerical error...Have you suggestions to discover where it is? > > You are almost certainly correct. Unless all the numbers are exact > integers, nearly every floating point operation will add some error. > > Without seeing your code, and some representative sample data, it is > impossible to tell whether the error is tiny or huge. > > Tiny error: > > MYMAP[1, j, k] = 1.001 > www = 0.25 > > > Huge error: > > MYMAP[1, j, k] = 1.001e19 > www = 0.25 > > > > -- > Steven > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gb.gabrielebrambilla at gmail.com Tue Mar 4 04:51:32 2014 From: gb.gabrielebrambilla at gmail.com (Gabriele Brambilla) Date: Mon, 3 Mar 2014 22:51:32 -0500 Subject: [Tutor] numerical problem In-Reply-To: References: <20140304020202.GO28804@ando> Message-ID: for example I read this: On Pythons prior to 2.7 and 3.1, once you start experimenting with floating-point numbers, you're likely to stumble across something that may look a bit odd at first glance: >>> 3.1415 * 2 # repr: as code (Pythons < 2.7 and 3.1) 6.2830000000000004 >>> print(3.1415 * 2) # str: user-friendly 6.283 The first result isn't a bug; it's a display issue. It turns out that there are two ways to print every object in Python--with full precision (as in the first result shown here), and in a user-friendly form (as in the second). Formally, the first form is known as an object's as-code repr, and the second is its user-friendly str. In older Pythons, the floating-point repr sometimes displays more precision than you might expect. The difference can also matter when we step up to using classes. For now, if something looks odd, try showing it with a print built-in function call statement. Better yet, upgrade to Python 2.7 and the latest 3.X, where floating-point numbers display themselves more intelligently, usually with fewer extraneous digits--since this book is based on Pythons 2.7 and 3.3, this is the display form I'll be showing throughout this book for floating-point numbers: >>> 3.1415 * 2 # repr: as code (Pythons >= 2.7 and 3.1) 6.283 Besides expressions, there are a handful of useful numeric modules that ship with Python--modules are just packages of additional tools that we import to use: >>> import math >>> math.pi 3.141592653589793 >>> math.sqrt(85) 9.219544457292887 The math module contains more advanced numeric tools as functions, while the ran dom module performs random-number generation and random selections (here, from a Python list coded in square brackets--an ordered collection of other objects to be introduced later in this chapter): >>> import random >>> random.random() 0.7082048489415967 >>> random.choice([1, 2, 3, 4]) 1 Could the problem be something like this? thanks Gabriele 2014-03-03 22:44 GMT-05:00 Gabriele Brambilla < gb.gabrielebrambilla at gmail.com>: > ok, > the things I get is very specific. > my results differs from the other guy's ones with which I compare them for > slightly details. > We fit the data with a function and we obtain different but similar > values. our fit routines on the same data return the same results. So we > produce different data. > the values in www are like 1.01e-134 and also smaller, and I sum values > like this: there could be any problem summing so small numbers? is there a > Python guide that helps in using strange values numbers? > > thanks > > Gabriele > > > > > 2014-03-03 21:02 GMT-05:00 Steven D'Aprano : > > On Mon, Mar 03, 2014 at 08:00:52PM -0500, Gabriele Brambilla wrote: >> > Hi, >> > >> > I'm doing a sum in a for loop: >> > >> > www is the quantity I add. >> > >> > MYMAP[i, j, k] = MYMAP[i, j, k] + www >> > >> > MYMAP is a numpy array >> > >> > I have strong reasons to think that in this operation happens some >> > numerical error...Have you suggestions to discover where it is? >> >> You are almost certainly correct. Unless all the numbers are exact >> integers, nearly every floating point operation will add some error. >> >> Without seeing your code, and some representative sample data, it is >> impossible to tell whether the error is tiny or huge. >> >> Tiny error: >> >> MYMAP[1, j, k] = 1.001 >> www = 0.25 >> >> >> Huge error: >> >> MYMAP[1, j, k] = 1.001e19 >> www = 0.25 >> >> >> >> -- >> Steven >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Tue Mar 4 04:56:57 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 04 Mar 2014 14:56:57 +1100 Subject: [Tutor] numerical problem References: <20140304020202.GO28804@ando> Message-ID: <85ha7ehb06.fsf@benfinney.id.au> Gabriele Brambilla writes: > the values in www are like 1.01e-134 and also smaller, and I sum values > like this: there could be any problem summing so small numbers? The default floating-point number type in Python is a fixed-precision float . Yes, with the ?float? type calcuations will lose information, and calculations at differing orders of magnitude will lose information faster. That's a limitation of any fixed-precision float implementation. If you want to use different types with different trade-offs, see the Python documentation and the NumPy documentation for the numeric data types they support. -- \ ?If [a technology company] has confidence in their future | `\ ability to innovate, the importance they place on protecting | _o__) their past innovations really should decline.? ?Gary Barnett | Ben Finney From __peter__ at web.de Tue Mar 4 09:31:16 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 Mar 2014 09:31:16 +0100 Subject: [Tutor] numerical problem References: <20140304020202.GO28804@ando> Message-ID: Gabriele Brambilla wrote: > for example I read this: > > On Pythons prior to 2.7 and 3.1, once you start experimenting with > floating-point numbers, you're likely to stumble across something that may > look a bit odd at first glance: >>>> 3.1415 * 2 # repr: as code (Pythons < 2.7 and 3.1) > 6.2830000000000004 >>>> print(3.1415 * 2) # str: user-friendly > 6.283 > The first result isn't a bug; it's a display issue. It turns out that > there are two ways to print every object in Python--with full precision > (as in the first result shown here), and in a user-friendly form (as in > the second). Formally, the first form is known as an object's as-code > repr, and the second is its user-friendly str. In older Pythons, the > floating-point repr sometimes displays more precision than you might > expect. The difference can also matter when we step up to using classes. > For now, if something looks odd, try showing it with a print built-in > function call statement. Better yet, upgrade to Python 2.7 and the latest > 3.X, where floating-point numbers display themselves more intelligently, > usually with fewer extraneous digits--since this book is based on Pythons > 2.7 and 3.3, this is the display form I'll be showing throughout this book > for floating-point numbers: >>>> 3.1415 * 2 # repr: as code (Pythons >= 2.7 and 3.1) > 6.283 > Besides expressions, there are a handful of useful numeric modules that > ship with Python--modules are just packages of additional tools that we > import to use: >>>> import math >>>> math.pi > 3.141592653589793 >>>> math.sqrt(85) > 9.219544457292887 > The math module contains more advanced numeric tools as functions, while > the ran dom module performs random-number generation and random selections > (here, from a Python list coded in square brackets--an ordered collection > of other objects to be introduced later in this chapter): >>>> import random >>>> random.random() > 0.7082048489415967 >>>> random.choice([1, 2, 3, 4]) > 1 > > Could the problem be something like this? Like what? A display issue? I'd say that's unlikely, but only you can answer that. Print the result with more precision, but note that this doesn't change the actual value, it typically adds more bogus digits: >>> sum([1.e17] + [1.]*1000) 1e+17 >>> "%30f" % sum([1.e17] + [1.]*1000) ' 100000000000000000.000000' As Steven hinted the error of floating point calculation depends on the actual numbers. You can sometimes improve accuracy by reshuffling the operations: >>> x = 1.0e17 >>> for i in range(1000): ... x += 1 ... >>> y = 0.0 >>> for i in range(1000): ... y += 1 ... >>> y += 1.0e17 >>> int(x) 100000000000000000 >>> int(y) 100000000000000992 1e17 is so big that 1.e17 + 1. == 1.e17, and repeating the addition doesn't fix that. Adding 1.e17 + 1000. gives a result much closer to the exact value. From swdunning at cox.net Tue Mar 4 03:08:24 2014 From: swdunning at cox.net (Scott W Dunning) Date: Mon, 3 Mar 2014 19:08:24 -0700 Subject: [Tutor] Help with "Guess the number" script In-Reply-To: References: <43B63C46-3A2D-4374-8A42-EE931BA9A6C4__25474.1337303587$1393659422$gmane$org@cox.net> Message-ID: <07023D8C-CFC7-4F6F-9C59-29C75E79BB7C@cox.net> On Mar 3, 2014, at 1:51 AM, Ben Finney wrote: > "Bold? assumes that markup of text will survive; that's not reliable, > since this is a text-only medium and only the plain text will reliably > survive to all readers. Sorry, I didn?t realize. I?m still new to this. > > You're creating a prompt string, so this is a good choice of name; > except that its correct spelling is ?prompt?. Haha, I didn?t even catch that, thx. > This is valuable! Thinking about what the values mean is vital to > understanding what the program is doing, which is of course a big part > of what you're in this to learn. That?s where I?ve been getting the most confused, because the instructor is giving variables he wants used and I was having a hard time figuring out what some of them were doing. I think I have a better understanding now though. > >> def print_hints(secrets, guess): >> secret_number = secret > > You never use this ?secret_number? name again, so the binding is > useless. What was your intention? I honestly don?t know, I?ve since taken that out completely. > > You also never use the ?secrets? parameter; and the ?secret? name was > not bound before you used it. Have you mis-spelled one of those? > >> guess = guess > > I don't know what the point of this no-op assignment is. What are you > trying to do? > >> if guess < 0 or user_guess> 101: > > Likewise, you never bind the name ?user_guess?. Where are you expecting > it to be bound? That was a mistake. I?m trying to get it to print ?Out of range? if the user guesses a number out of the range of 1-100. > > > I suspect at this point you've been flailing around without much > understanding of the changes you're making. This leads to a confused > mass of code that you can't understand or explain. Yes, correct. > > Better would be to experiment at the interactive Python prompt to test > what these changes *do*, before putting them into your code. Reduce the > mechanisms down to very minimal cases, and try them out; confirm your > assumptions and guesses. Only then should you plan a change to the > program file. Ok that makes sense. Thanks again! -------------- next part -------------- An HTML attachment was scrubbed... URL: From swdunning at cox.net Tue Mar 4 03:29:26 2014 From: swdunning at cox.net (Scott W Dunning) Date: Mon, 3 Mar 2014 19:29:26 -0700 Subject: [Tutor] Help with "Guess the number" script In-Reply-To: References: <43B63C46-3A2D-4374-8A42-EE931BA9A6C4__25474.1337303587$1393659422$gmane$org@cox.net> Message-ID: On Mar 3, 2014, at 3:27 AM, spir wrote: > > There are 2 user guesses here, and only 1 variable, thus 1 name. The name should say what (idea) the variable represents in the program; this should be said by the name's *meaning*. It is one of the greatest difficulties in programming. How would you define what these variables represent, using everyday language? My own definitions would lead me to choose the following variable names: > guess_text = raw_input(promt) > guess_number = int(user_guess) > return guess_number > Note: it is especially obviuos that these are 2 separate numbers, since they do not even are of the same type (a piece of text, or "string", vs a number, here an "int"). > > Good naming is very, very hard; differences of naming can make some piece of program nearly trivial or instead nearly impossible to understand; often bad naming is worse than hypothetical randomly chosen names, because bad naming *misleads* your thinking. > > Changing the value of a local variable is always, or nearly, a sign that there are here 2 ideas which should be represented by 2 variables with 2 names. Example of 2 programming styles (note the difference in ease of understanding, even if you don't know the python features used here): > > def get_data (data): > data = File(data) # (a file) > data = data.read() # (a piece of text) > data = data.split("") # (a list of words) > return data > ... > data = get_data("data.text") > > def data_words (file_name): > data_file = File(file_name) # (a file) > text = data_file.read() # (a piece of text) > words = text.split(" ") # (a list of words) > return words > ... > words = data_words("data.text") > > (A special case is loop variables, but even then you only write the assignment once, the value chages across multiple passes on the same code. The only real exception is accumulators, like for computing a sum, which need to be first initialised to a start value, often 0.) > >> def print_hints(secrets, guess): >> secret_number = secret >> guess = guess >> if guess < 0 or user_guess> 101: >> print "Out of range!" > > Parameters are input variables. Once they are given execution values by a call like > print_hints(input_value1, input_value2) > > these variables exist _inside_ the function body (each with a name and a value). As if functions were defined like: > def print_hints: # note: no param > secret = input_value1 > guess = input_value2 > ... use these variables ... > This is more or less what the language does for you. This is the whole point of defining parameters, in fact. So, _you_ do not need to _rebind_ parameters to local variables; they already are local variables. > > In addition, you are not consistent with variable _names_, evendently, so your programs have no chance to work. This is an annoying, but necessary part of programming. But the language will always tell about such errors, at once, *if and only if* the wrong name does *not* otherwise exist. --> pay attention! > >> def main(): >> print_description() >> secret = randrange(1,101) >> current_guess = get_guess(1) >> if current_guess != secret: >> print_hints(secret_number, guess) >> current_guess = get_guess(2) > > * 'secret_number' appears from nowhere: pay attention! > * To be more coherent checking if the guess is right or wrong (or too high or too low) should be done in function print_hints as well. This function _evaluates_ the guess (maybe it should be renamed). > >> if secret == current_guess: >> print "Congratulations, you win!" >> else: >> print "Please play again" >> print "The secret number was", secret > > These are (also) hints to the player, actually, aren't they? ***Wow, thanks a lot Denis!! Although I didn?t get everything you said I definitely understand a lot more!**** I?ve made some changes and have a couple questions, I?ll speak in between the code. Thanks again everyone, especially for your patients, I know I?ve made several mistakes and I don?t know anything about programming and even less about these forums. I apologize about that and again appreciate your patients!!! from random import randrange randrange(1, 101) from random import seed seed(129) def print_description(): print """Welcome to Guess the Number. I have selected a secret number in the range 1 ... 100. You must guess the number within 10 tries. I will tell you if you are high or low, and I will tell you if you are hot or cold.\n""" So, this is what I gather from the function below. I?m basically taking the parameter guess_number and making it a str with prompt, then using the variable guess_text and turning the prompt into an int? and returning the original value the user inputed? def get_guess(guess_number): prompt = "(" + str(guess_number) +") Please enter a guess:" guess_text = raw_input(prompt) guess_number = int(guess_text) return guess_number I?m a little confused about the parameter guess below and how I?m able to use it with the conditional statement for when it?s out of range? Is it because when I call the function print_hints(secret, current_guess) I?m essentially defining it because guess_number was turned into current_guess when I call it equal to get_guess(1)?? I hope I?m not just confusing you guys. I?m just trying to make sense of everything. I feel like it would be a lot clearer if we were allowed to use global variables. Anyways? def print_hints(secret, guess): if guess < 1 or guess > 101: print print "Out of range!" print def main(): print_description() secret = randrange(1,101) current_guess = get_guess(1) if current_guess != secret: print "please play again!" print_hints(secret, current_guess) current_guess = get_guess(2) if current_guess != secret: print "please play again!" print_hints(secret, current_guess) current_guess = get_guess(3) if current_guess != secret: print "please play again!" print_hints(secret, current_guess) current_guess = get_guess(4) if current_guess != secret: print "please play again!" print_hints(secret, current_guess) current_guess = get_guess(5) if current_guess != secret: print "please play again!" print_hints(secret, current_guess) current_guess = get_guess(6) if current_guess != secret: print "please play again!" print_hints(secret, current_guess) current_guess = get_guess(7) if current_guess != secret: print "please play again!" print_hints(secret, current_guess) current_guess = get_guess(8) if current_guess != secret: print "please play again!" print_hints(secret, current_guess) current_guess = get_guess(9) if current_guess != secret: print "please play again!" print_hints(secret, current_guess) current_guess = get_guess(10) if current_guess == secret: print "Congratulations, you win!" if secret != current_guess: print "Please play again" print "The secret number was:", secret main() -------------- next part -------------- An HTML attachment was scrubbed... URL: From swdunning at cox.net Tue Mar 4 06:10:22 2014 From: swdunning at cox.net (Scott W Dunning) Date: Mon, 3 Mar 2014 22:10:22 -0700 Subject: [Tutor] Help with "Guess the number" script In-Reply-To: References: <43B63C46-3A2D-4374-8A42-EE931BA9A6C4__25474.1337303587$1393659422$gmane$org@cox.net> <53145917.4040209@gmail.com> Message-ID: <8F81287A-D181-4AF9-A6B8-D5F40B15D9D3@cox.net> On Mar 3, 2014, at 3:29 AM, spir wrote: I have another question in regard to this guess the number script I?m working on. I?m banging my head over why this isn?t working?. def print_hints(secret, guess): if guess < 1 or guess > 101: print print "Out of range!" print if guess < secret: print print "Too low!" if guess < (secret - 10) or guess > (secret - 10): print "You are cold!" print print "Please play again!" if guess > secret: print print "Too high!" print print "Please play again!" if guess < (secret - 5) or guess > (secret - 5): print "You are cold!" print print "Please play again!? I keep getting a syntax error about the indenting for this elif being wrong? Any suggestions? elif: print "You're on fire!!" Thanks again!! Scott From dyoo at hashcollision.org Tue Mar 4 11:08:11 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 4 Mar 2014 02:08:11 -0800 Subject: [Tutor] Help with "Guess the number" script In-Reply-To: <8F81287A-D181-4AF9-A6B8-D5F40B15D9D3@cox.net> References: <43B63C46-3A2D-4374-8A42-EE931BA9A6C4__25474.1337303587$1393659422$gmane$org@cox.net> <53145917.4040209@gmail.com> <8F81287A-D181-4AF9-A6B8-D5F40B15D9D3@cox.net> Message-ID: Once a function gets beyond about six or seven lines long, it's a bit hard to read, and harder to get the indentation right. You're having difficulty with the indentation, but that's often a sign that the function is too big to read comfortably. Can you break the function down into a few pieces? I see there's some duplicated blocks, such as: ######################### print "You are cold!" print print "Please play again!? ######################### You can define a function to do these three prints: ######################### def print_cold(): print "You are cold!" print print "Please play again!? ######################### Once you have this somewhere, you can use print_cold() whenever you want to do those three prints statements. Try it! Try to do the same for your other messages. You'll find that it should help make print_hints() more concise. Hopefully it'll be short enough that you can see where you're misindenting. Making it shorter should help make it easier to see that the code testing for "coldness" is not quite consistent from one place to another. In one, the code uses a threshold of ten, but in another place, a threshold of five. Is that difference intentional? If not, then you might even try something like: ######################### def maybe_print_cold(): if guess < (secret - 10) or guess > (secret - 10): print "You are cold!" print print "Please play again!? ######################### and use this function in the two places where you're checking for coldness. Point is: use functions. They're there to help. From dyoo at hashcollision.org Tue Mar 4 11:10:46 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 4 Mar 2014 02:10:46 -0800 Subject: [Tutor] Help with "Guess the number" script In-Reply-To: References: <43B63C46-3A2D-4374-8A42-EE931BA9A6C4__25474.1337303587$1393659422$gmane$org@cox.net> <53145917.4040209@gmail.com> <8F81287A-D181-4AF9-A6B8-D5F40B15D9D3@cox.net> Message-ID: > If not, then you might even try something like: > > ######################### > def maybe_print_cold(): > if guess < (secret - 10) or guess > (secret - 10): > print "You are cold!" > print > print "Please play again!? > ######################### ... Ooops. You probably need to pass "secret" and "guess" as parameters too. Here's an amended version of that helper function: ######################### def maybe_print_cold(secret, guess): if guess < (secret - 10) or guess > (secret - 10): print "You are cold!" print print "Please play again!? ######################### Apologies for the quick-fire email; I didn't want to leave that error hanging. From alan.gauld at btinternet.com Tue Mar 4 11:45:31 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 04 Mar 2014 10:45:31 +0000 Subject: [Tutor] Help with "Guess the number" script In-Reply-To: References: <43B63C46-3A2D-4374-8A42-EE931BA9A6C4__25474.1337303587$1393659422$gmane$org@cox.net> Message-ID: On 04/03/14 02:29, Scott W Dunning wrote: > I?ve made some changes and have a couple questions, I?ll speak in > between the code. > from random import randrange > randrange(1, 101) This call to randrange() doesn't do anything because you don't store the return value. You need to create a variable to hold the random number. > from random import seed You can import several names at once: from random import randrange, seed > seed(129) While this works for your purposes it is going to give you the same 'random' numbers each time. That is they won't really be random. The normal way to seed a random number is to use a number that changes each time, such as the current time. But you can leave that as a nicety for later... > So, this is what I gather from the function below. I?m basically taking > the parameter guess_number and making it a str with prompt, then using > the variable guess_text and turning the prompt into an int? and > returning the original value the user inputed? You have the gist of it but you need to watch your terminology. prompt is just the variable, its only a name or label that you attach to your data. It doesn't do anything. So your comment above should say: "I?m basically taking the parameter guess_number and making it a str and storing the string as the variable prompt" The next comment isn't quite right either. The raw_input() function displays the prompt to the user and returns the value that the user entered as a string. You then convert that string to an integer and store (then return) the result. So your comment should say something like: "then using the variable guess_text to store the value the user had input and then turning it into an int. Finally returning the converted value?" The variable names prompt, guess_text and guess_number are just temporary storage areas they don't do anything. The doing is all in the functions: raw_input() and int(). > def get_guess(guess_number): > prompt = "(" + str(guess_number) +") Please enter a guess:" > guess_text = raw_input(prompt) > guess_number = int(guess_text) > return guess_number > I?m a little confused about the parameter guess below and how I?m able > to use it with the conditional statement for when it?s out of range? Is > it because when I call the function print_hints(secret, current_guess) > I?m essentially defining it because guess_number was turned into > current_guess when I call it equal to get_guess(1)?? The names in the function (including the parameters) are completely separate from the names outside it. So you can modify a variable called guess in your main program and it has no effect on the parameter called guess. They are completely separate. Its just like people. I have a cousin called Scott. He is currently climbing mountains in Europe. That does not mean that you are climbing mountains, you are two different Scott's. You each have your own context, or as we say in programming, your own 'namespace'. The parameters of a function take on the values that are passed to the function when you call it - the arguments. You may choose to assign the variable guess to the parameter guess when you call it, or you may assign a different argument, Python doesn't care. It just takes whatever argument value is assigned to the guess parameter and uses it within the function. > I feel like it would be a lot clearer if we were allowed to use global > variables. Trust me, you don't want to do that. It creates a morass of unmaintainable code and a huge memory test as you try to remember which functions modify which variables and when. Global variables are one of the biggest causes of bugs in programs, especially once you get into bigger projects. > def print_hints(secret, guess): > if guess < 1 or guess > 101: > print > print "Out of range!" > print There is a small bug in this code. The test should be whether the value is between 1 and 100 but you are allowing a guess of 101 to pass. I'll leave you to figure out how to fix that! :-) > def main(): > print_description() > secret = randrange(1,101) > current_guess = get_guess(1) > if current_guess != secret: > print "please play again!" > print_hints(secret, current_guess) > current_guess = get_guess(2) I think you are supposed to call print_hints() after setting current_guess so the order would be something like: print "please play again!" current_guess = get_guess(2) print_hints(secret, current_guess) Also since you know about functions you could simplify the code and save typing by putting those three lines into a another function which returns the guess for use in the comparison. Also since this is a function you could reverse the logic of the comparison and return (thus exiting the program) when the guess == secret. That would look something like: current_guess = your_new_function(1) if current_guess === secret: print 'well done' return current_guess = your_new_function(2) if current_guess === secret: print 'well done' return etc... repeating that however many guesses you want to allow. In fact you could even wrap that whole thing, including the test, in a function and instead of returning the guess return a true/false value indicating if the guess was successful. That would then look like: if bigger_new_function(1): return if bigger_new_function(2): return etc... > .... > if current_guess != secret: > print "please play again!" > print_hints(secret, current_guess) > current_guess = get_guess(10) > if current_guess == secret: > print "Congratulations, you win!" This means you only tell them about success after comparing the result to secret many times. By inverting the test as suggested above you can respond to the correct guess immediately. > if secret != current_guess: > print "Please play again" > print "The secret number was:", secret This seems a tad pointless, telling them to play again then giving them the answer, and then the program terminates before they can try again! HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Tue Mar 4 17:26:01 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 04 Mar 2014 16:26:01 +0000 Subject: [Tutor] HTML Parser woes Message-ID: My turn to ask a question. This has me pulling my hair out. Hopefully it's something obvious... I'm trying to pull some dates out of an HTML web page generated from an Excel spreadsheet. I've simplified things somewhat so the file(sample.htm) looks like:
ItemID Name DateLent DateReturned
1 LawnMower Small Hover mower Fred Joe 4/1/2012 4/26/2012
The code looks like: import html.parser class SampleParser(html.parser.HTMLParser): def __init__(self): super().__init__() self.isDate = False def handle_starttag(self, name, attributes): if name == 'td': for key, value in attributes: if key == 'class': print ('Class Value: ',repr(value)) if value.endswith('165'): print ('We got a date') self.isDate = True break def handle_endtag(self,name): self.isDate = False def handle_data(self, data): if self.isDate: print('Date: ', data) if __name__ == '__main__': print('start test') htm = open('sample.htm').read() parser = SampleParser() parser.feed(htm) print('end test') And the output looks like: start test Class Value: 'xl66' Class Value: 'xl66' Class Value: 'xl66' Class Value: 'xl66' Class Value: 'xl65' Class Value: 'xl65' end test As you can see I'm picking up the class attribute and its value but the conditional test for x165 is failing. I've tried if value == 'x165' if 'x165' in value and every other test I can think of. Why am I not seeing the "We got a date" message? PS. Please don't suggest other modules/packages etc, I'm using html.parser for a reason. Frustratedly, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Tue Mar 4 17:31:02 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 5 Mar 2014 03:31:02 +1100 Subject: [Tutor] HTML Parser woes In-Reply-To: References: Message-ID: <20140304163102.GT28804@ando> On Tue, Mar 04, 2014 at 04:26:01PM +0000, Alan Gauld wrote: > My turn to ask a question. > This has me pulling my hair out. Hopefully it's something obvious... [...] > And the output looks like: > > start test > Class Value: 'xl66' > Class Value: 'xl66' > Class Value: 'xl66' > Class Value: 'xl66' > Class Value: 'xl65' > Class Value: 'xl65' > end test > > As you can see I'm picking up the class attribute and > its value but the conditional test for x165 is failing. It's "x L 65", not "x ONE 65". -- Steven From alan.gauld at btinternet.com Tue Mar 4 17:38:32 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 04 Mar 2014 16:38:32 +0000 Subject: [Tutor] HTML Parser woes In-Reply-To: <20140304163102.GT28804@ando> References: <20140304163102.GT28804@ando> Message-ID: On 04/03/14 16:31, Steven D'Aprano wrote: > On Tue, Mar 04, 2014 at 04:26:01PM +0000, Alan Gauld wrote: >> My turn to ask a question. >> This has me pulling my hair out. Hopefully it's something obvious... > [...] >> And the output looks like: >> >> start test >> Class Value: 'xl66' >> Class Value: 'xl66' >> Class Value: 'xl66' >> Class Value: 'xl66' >> Class Value: 'xl65' >> Class Value: 'xl65' >> end test >> >> As you can see I'm picking up the class attribute and >> its value but the conditional test for x165 is failing. > > It's "x L 65", not "x ONE 65". > > > Doh! I said it would be simple..,. :-( And xl = Excel, I should have guessed. Thanks Steven, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From denis.spir at gmail.com Tue Mar 4 19:19:10 2014 From: denis.spir at gmail.com (spir) Date: Tue, 04 Mar 2014 19:19:10 +0100 Subject: [Tutor] HTML Parser woes In-Reply-To: References: <20140304163102.GT28804@ando> Message-ID: <5316191E.2090303@gmail.com> On 03/04/2014 05:38 PM, Alan Gauld wrote: > On 04/03/14 16:31, Steven D'Aprano wrote: >> On Tue, Mar 04, 2014 at 04:26:01PM +0000, Alan Gauld wrote: >>> My turn to ask a question. >>> This has me pulling my hair out. Hopefully it's something obvious... >> [...] >>> And the output looks like: >>> >>> start test >>> Class Value: 'xl66' >>> Class Value: 'xl66' >>> Class Value: 'xl66' >>> Class Value: 'xl66' >>> Class Value: 'xl65' >>> Class Value: 'xl65' >>> end test >>> >>> As you can see I'm picking up the class attribute and >>> its value but the conditional test for x165 is failing. >> >> It's "x L 65", not "x ONE 65". >> >> >> > > Doh! I said it would be simple..,. :-( > > And xl = Excel, I should have guessed. I'm curious what font you use such that you even _can_ confuse '1' and 'l' in reading (modern fonts are made to avoid such issues, like between 'O' and '0'). d From alan.gauld at btinternet.com Tue Mar 4 19:58:12 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 04 Mar 2014 18:58:12 +0000 Subject: [Tutor] HTML Parser woes In-Reply-To: <5316191E.2090303@gmail.com> References: <20140304163102.GT28804@ando> <5316191E.2090303@gmail.com> Message-ID: On 04/03/14 18:19, spir wrote: >>>> As you can see I'm picking up the class attribute and >>>> its value but the conditional test for x165 is failing. >>> >>> It's "x L 65", not "x ONE 65". >>> > I'm curious what font you use such that you even _can_ confuse '1' and > 'l' in reading (modern fonts are made to avoid such issues, like between > 'O' and '0'). It's the default font in the Pythonwin IDE. There is a difference when you print them side by side but it is minimal. I just checked and it is CourierNew, Regular, size 10pt. I should probably change it (although aside from this issue I like it)! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From breamoreboy at yahoo.co.uk Tue Mar 4 21:08:19 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 04 Mar 2014 20:08:19 +0000 Subject: [Tutor] HTML Parser woes In-Reply-To: References: Message-ID: On 04/03/2014 16:26, Alan Gauld wrote: > My turn to ask a question. > This has me pulling my hair out. Hopefully it's something obvious... > > I'm trying to pull some dates out of an HTML web page generated > from an Excel spreadsheet. > > I've simplified things somewhat so the file(sample.htm) looks like: > > > > > style='border-collapse: > collapse;table-layout:fixed;width:564pt'> > > > > > > > > > > > > > > > >
style='height:15.75pt;width:48pt'>ItemIDNameDateLentDateReturned
1LawnMowerSmall Hover mowerFredJoe4/1/20124/26/2012
> > > > The code looks like: > > import html.parser > > class SampleParser(html.parser.HTMLParser): > def __init__(self): > super().__init__() > self.isDate = False > > def handle_starttag(self, name, attributes): > if name == 'td': > for key, value in attributes: > if key == 'class': > print ('Class Value: ',repr(value)) > if value.endswith('165'): > print ('We got a date') > self.isDate = True > break > > def handle_endtag(self,name): > self.isDate = False > > def handle_data(self, data): > if self.isDate: > print('Date: ', data) > > if __name__ == '__main__': > print('start test') > htm = open('sample.htm').read() > parser = SampleParser() > parser.feed(htm) > print('end test') > > And the output looks like: > > start test > Class Value: 'xl66' > Class Value: 'xl66' > Class Value: 'xl66' > Class Value: 'xl66' > Class Value: 'xl65' > Class Value: 'xl65' > end test > > As you can see I'm picking up the class attribute and > its value but the conditional test for x165 is failing. > > I've tried > > if value == 'x165' > if 'x165' in value > > and every other test I can think of. > > Why am I not seeing the "We got a date" message? > > PS. > Please don't suggest other modules/packages etc, > I'm using html.parser for a reason. > > Frustratedly, Steven has pointed out the symptoms. Cause, should have gone to Specsavers. :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From coffer.nick at hotmail.com Tue Mar 4 21:43:15 2014 From: coffer.nick at hotmail.com (coffer.nick) Date: Tue, 4 Mar 2014 14:43:15 -0600 Subject: [Tutor] (no subject) Message-ID: Hey I just need help plz! Sent via the Samsung GALAXY S?4 Active?, an AT&T 4G LTE smartphone -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Wed Mar 5 14:01:09 2014 From: wprins at gmail.com (Walter Prins) Date: Wed, 5 Mar 2014 13:01:09 +0000 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On 4 March 2014 20:43, coffer.nick wrote: > Hey I just need help plz! OK, what would you like help with? Walter From k-shweta at hcl.com Wed Mar 5 13:49:35 2014 From: k-shweta at hcl.com (Shweta Kaushik) Date: Wed, 5 Mar 2014 12:49:35 +0000 Subject: [Tutor] reg: How to import dll in python Message-ID: <7955538EC35A414B9B0A5DDD7DA0404716BB0148@chn-hclt-mbs04.HCLT.CORP.HCL.IN> Hi, Please find code used to create dll: add_1.cpp #include "add_1.h" using namespace std; Mathematics::Mathematics() { } void Mathematics::input() { cout << "Input two inetegers\n"; cin >> x >> y; } void Mathematics::add() { cout << "Result = " << x + y; } add_1.h #include class Mathematics { int x, y; public: __declspec(dllexport) Mathematics();//constructor __declspec(dllexport) void input(); __declspec(dllexport) void add(); }; Dll created: Addition.dll Python Code to import above dll: import ctypes From ctypes import * testDll = cdll.LoadLibrary("D:\Python Test Codes\DLL_Test\Addition.dll") test1 = ctypes.WINFUNCTYPE(None) test2 = test1 (("add", testDll)) Error Displayed Traceback (most recent call last): File "", line 1, in AttributeError: function 'add' not found ::DISCLAIMER:: ---------------------------------------------------------------------------------------------------------------------------------------------------- The contents of this e-mail and any attachment(s) are confidential and intended for the named recipient(s) only. E-mail transmission is not guaranteed to be secure or error-free as information could be intercepted, corrupted, lost, destroyed, arrive late or incomplete, or may contain viruses in transmission. The e mail and its contents (with or without referred errors) shall therefore not attach any liability on the originator or HCL or its affiliates. Views or opinions, if any, presented in this email are solely those of the author and may not necessarily reflect the views or opinions of HCL or its affiliates. Any form of reproduction, dissemination, copying, disclosure, modification, distribution and / or publication of this message without the prior written consent of authorized representative of HCL is strictly prohibited. If you have received this email in error please delete it and notify the sender immediately. Before opening any email and/or attachments, please check them for viruses and other defects. ---------------------------------------------------------------------------------------------------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Wed Mar 5 20:02:54 2014 From: emile at fenx.com (Emile van Sebille) Date: Wed, 05 Mar 2014 11:02:54 -0800 Subject: [Tutor] reg: How to import dll in python In-Reply-To: <7955538EC35A414B9B0A5DDD7DA0404716BB0148@chn-hclt-mbs04.HCLT.CORP.HCL.IN> References: <7955538EC35A414B9B0A5DDD7DA0404716BB0148@chn-hclt-mbs04.HCLT.CORP.HCL.IN> Message-ID: Hi Shweta, You'll likely get a better response posting this question on the main python list -- the Tutor list is primarily for teaching python Emile On 3/5/2014 4:49 AM, Shweta Kaushik wrote: > Hi, > > Please find code used to create dll: > > *_add_1.cpp_* > > #include "add_1.h" > > using namespace std; > > Mathematics::Mathematics() > > { > > } > > void Mathematics::input() > > { > > cout << "Input two inetegers\n"; > > cin >> x >> y; > > } > > void Mathematics::add() > > { > > cout << "Result = " << x + y; > > } > > *_add_1.h_* > > #include > > class Mathematics { > > int x, y; > > public: > > __declspec(dllexport) Mathematics();//constructor > > __declspec(dllexport) void input(); > > __declspec(dllexport) void add(); > > }; > > *_Dll created_*: Addition.dll > > *_Python Code to import above dll_*: > > import ctypes > > From ctypes import * > > testDll = cdll.LoadLibrary("D:\Python Test Codes\DLL_Test\Addition.dll") > > test1 = ctypes.WINFUNCTYPE(None) > > test2 = test1 (("add", testDll)) > > Error Displayed > > Traceback (most recent call last): > > File "", line 1, in > > AttributeError: function 'add' not found > > > > ::DISCLAIMER:: > ---------------------------------------------------------------------------------------------------------------------------------------------------- > > The contents of this e-mail and any attachment(s) are confidential and > intended for the named recipient(s) only. > E-mail transmission is not guaranteed to be secure or error-free as > information could be intercepted, corrupted, > lost, destroyed, arrive late or incomplete, or may contain viruses in > transmission. The e mail and its contents > (with or without referred errors) shall therefore not attach any > liability on the originator or HCL or its affiliates. > Views or opinions, if any, presented in this email are solely those of > the author and may not necessarily reflect the > views or opinions of HCL or its affiliates. Any form of reproduction, > dissemination, copying, disclosure, modification, > distribution and / or publication of this message without the prior > written consent of authorized representative of > HCL is strictly prohibited. If you have received this email in error > please delete it and notify the sender immediately. > Before opening any email and/or attachments, please check them for > viruses and other defects. > > ---------------------------------------------------------------------------------------------------------------------------------------------------- > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From wprins at gmail.com Wed Mar 5 20:10:56 2014 From: wprins at gmail.com (Walter Prins) Date: Wed, 5 Mar 2014 19:10:56 +0000 Subject: [Tutor] "Lab Three" query [was: Re: (no subject)] Message-ID: Hi, Please reply to the mailing list post and not to me directly so others can benefit/chime in. I'll send this response to the mailing list instead of directly to you, so you should receive it via that route. On 5 March 2014 13:20, nick coffer wrote: > Ok. I need help setting this up. I know how to mostly. Just I need to know > how to get the variables. Firstly please note, this is homework so I/we cannot provide a direct solution. Secondly, you're still not being very specific about what you're struggling with or indeed what you've tried. It usually works best if you're as concrete as possible, e.g. post the actual code that you've tried, and explain what you're struggling with or what errors you're running into that you cannot resolve. If you run into errors, always quote the exact error message and stack trace. Don't paraphrase code or error messages. So, what exactly have you written so far and how is it not working? I don't really understand what you mean by "get the variables", do you mean input them from the user, read them from a file, or what? Also, what version of Python are you using and what operating system are you using? (Windows, Mac, Ubuntu, BSD, something else?) Good luck, Walter From fomcl at yahoo.com Wed Mar 5 21:41:49 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 5 Mar 2014 12:41:49 -0800 (PST) Subject: [Tutor] reg: How to import dll in python In-Reply-To: <7955538EC35A414B9B0A5DDD7DA0404716BB0148@chn-hclt-mbs04.HCLT.CORP.HCL.IN> References: <7955538EC35A414B9B0A5DDD7DA0404716BB0148@chn-hclt-mbs04.HCLT.CORP.HCL.IN> Message-ID: <1394052109.63252.YahooMailNeo@web163804.mail.gq1.yahoo.com> >________________________________ > From: Shweta Kaushik >To: "tutor at python.org" >Sent: Wednesday, March 5, 2014 1:49 PM >Subject: [Tutor] reg: How to import dll in python >import ctypes >From ctypes import * >testDll = cdll.LoadLibrary("D:\Python Test Codes\DLL_Test\Addition.dll") >test1 = ctypes.WINFUNCTYPE(None) >test2 = test1 (("add", testDll)) >? >Error Displayed >Traceback (most recent call last): >? File "", line 1, in >AttributeError: function 'add' not found perhaps: from ctypes import * cppAdd = cdll.LoadLibrary(r"D:\Python Test Codes\DLL_Test\Addition.dll") # also note the r' add = cppAdd.add add.argtypes = [c_double, c_double] add(1.0, 2.0) From eryksun at gmail.com Thu Mar 6 03:52:14 2014 From: eryksun at gmail.com (eryksun) Date: Wed, 5 Mar 2014 21:52:14 -0500 Subject: [Tutor] reg: How to import dll in python In-Reply-To: <7955538EC35A414B9B0A5DDD7DA0404716BB0148@chn-hclt-mbs04.HCLT.CORP.HCL.IN> References: <7955538EC35A414B9B0A5DDD7DA0404716BB0148@chn-hclt-mbs04.HCLT.CORP.HCL.IN> Message-ID: On Wed, Mar 5, 2014 at 7:49 AM, Shweta Kaushik wrote: > > Please find code used to create dll: I hardly ever use C++, so C++ gurus feel free to correct any errors here. I just wanted a basic C API to work with ctypes -- since that's the Python aspect of this question. I've also only targeted Microsoft's compiler since the question is using a Windows DLL. First and foremost, in a C++ project you need to use `extern "C"` to get C linkage without C++ name mangling of exported symbols. My example uses the default __cdecl calling convention. You can switch to __stdcall if you wish. ctypes automatically handles stdcall name decoration. A C++ method uses the __thiscall convention that implicitly passes the `this` pointer (e.g. for x86 MSVC passes it in the ECX register). I handle this in the __cdecl C API by using stub functions and a pointer to an opaque structure. FYI, native x64 code only has one calling convention (for now). For an x64 target, MSVC ignores calling convention keywords such as __stdcall and __thiscall. Creating the stub functions manually is tedious, and prone to introducing bugs. Big projects automate this with SWIG, SIP, etc. You could also use Boost.Python or Cython. But probably all of the latter are off topic for python-tutor. If we're sticking with CPython's standard library, then ctypes is the only game in town. OK, enough blabber. mathematics.h: #ifndef MATHEMATICS_H #define MATHEMATICS_H #ifdef BUILD_MATHEMATICS #define DLLAPI __declspec(dllexport) #else #define DLLAPI __declspec(dllimport) #endif #ifdef __cplusplus class Mathematics { int x, y; public: void input(); int add(); }; #else /* !__cpluplus */ typedef struct _Mathematics Mathematics; #endif #ifdef __cplusplus extern "C" { #endif DLLAPI Mathematics *math_create(); DLLAPI void math_free(Mathematics *); DLLAPI void math_input(Mathematics *); DLLAPI int math_add(Mathematics *); #ifdef __cplusplus } #endif #endif /* !MATHEMATICS_H */ mathematics.cpp: #include #include #include "mathematics.h" using namespace std; void Mathematics::input() { cout << "Input two integers" << endl; cin >> x >> y; } int Mathematics::add() { return x + y; } Mathematics *math_create() { Mathematics *self = nullptr; try { self = new Mathematics; } catch(bad_alloc &ba) { cerr << "bad_alloc: " << ba.what() << endl; } return self; } void math_free(Mathematics *self) { delete self; } void math_input(Mathematics *self) { self->input(); } int math_add(Mathematics *self) { return self->add(); } mathematics.dll, mathematics.lib: cl mathematics.cpp /EHsc /MD /LD /DBUILD_MATHEMATICS mathtest.c: #include #include #include "mathematics.h" #pragma comment(lib, "mathematics.lib") int main() { Mathematics *m = math_create(); if (m == NULL) return EXIT_FAILURE; math_input(m); printf("Result = %d\n", math_add(m)); math_free(m); return EXIT_SUCCESS; } Test run: C:\>mathtest.exe Input two integers -10 15 Result = 5 mathematics.py: import os import ctypes libpath = os.path.join(os.path.dirname(__file__), 'mathematics.dll') lib = ctypes.CDLL(libpath) class _CMathematics(ctypes.Structure): pass CMathematics = ctypes.POINTER(_CMathematics) def check_alloc(result, func, args): if not result: raise MemoryError return args lib.math_create.restype = CMathematics lib.math_create.errcheck = check_alloc lib.math_free.restype = None lib.math_free.argtypes = [CMathematics] lib.math_input.restype = None lib.math_input.argtypes = [CMathematics] lib.math_add.restype = ctypes.c_int lib.math_add.argtypes = [CMathematics] class Mathematics(object): _lib = lib # for __del__ _handle = None def __init__(self): self._handle = lib.math_create() def __del__(self): if self._handle: self._lib.math_free(self._handle) def input(self): lib.math_input(self._handle) def add(self): return lib.math_add(self._handle) del os, ctypes if __name__ == '__main__': m = Mathematics() m.input() print("Result = %d" % m.add()) I cached lib in the class to enable Mathematics.__del__ to work during shutdown. Without that, the __del__ method might try to use lib after Python has already set it to None. This way avoids spurious errors. Generally avoid using global names in __del__. CDLL calls the platform loader, such as Windows LoadLibrary or POSIX dlopen. If the shared library is already mapped in the process, both LoadLibrary and dlopen will increment the reference count and return a handle to the already loaded library. Generally you don't have to worry about calling Windows FreeLibrary or POSIX dlclose to decrement the reference count. Just leave the library loaded for the life of the process. CDLL uses the cdecl calling convention. For stdcall, use the WinDLL subclass. There's also OleDLL for use with COM, but if you need COM you'll probably find it easier to use the comtypes package that's built on top of ctypes. If you're accessing a DLL that's in the system search path, you can also use cdll and windll, e.g. cdll.msvcrt or windll.kernel32. Windows LoadLibrary automatically appends the .dll extension. Note that cdll.LoadLibrary is pretty much pointless. It just returns a CDLL instance. Getting an attribute of a library will automatically create and cache a function pointer for the export with the given name. If a DLL exports a symbol by ordinal only, use subscription instead of attribute access, e.g. use `lib[10]` to get ordinal 10. The default result type (restype) is c_int, which AFAIK is 32-bit on all platforms supported by CPython. c_int is also the default when converting a Python integer as an argument. Keep that in mind when working with 64-bit pointers. You'll need to make sure argtypes and restype are set to use a pointer type. From jsutar at gmail.com Thu Mar 6 18:00:46 2014 From: jsutar at gmail.com (Jignesh Sutar) Date: Thu, 6 Mar 2014 17:00:46 +0000 Subject: [Tutor] How to determine which function code is being called from Message-ID: Hi I'm trying to exclude a certain line of code if the function is called by another function, see illustration below: def funcA(): print "running from funcA" # print only if running from funcA print "running from funcA or funcB" #print when running from either function print "running from funcB" # print only when running from funcB def funcB(): funcA() funcB() -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Thu Mar 6 18:33:52 2014 From: emile at fenx.com (Emile van Sebille) Date: Thu, 06 Mar 2014 09:33:52 -0800 Subject: [Tutor] How to determine which function code is being called from In-Reply-To: References: Message-ID: While there are ways of getting at the caller using introspection, there are no reliable ways of doing so and you would do well to rethink the need and take an alternate course such as passing a parameter in. Suppose the following: funcC=funcB what would you want to see? Emile On 3/6/2014 9:00 AM, Jignesh Sutar wrote: > Hi I'm trying to exclude a certain line of code if the function is > called by another function, see illustration below: > > > def funcA(): > print "running from funcA" # print only if running from funcA > print "running from funcA or funcB" #print when running from either > function > print "running from funcB" # print only when running from funcB > > def funcB(): > funcA() > > funcB() > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From denis.spir at gmail.com Thu Mar 6 19:51:47 2014 From: denis.spir at gmail.com (spir) Date: Thu, 06 Mar 2014 19:51:47 +0100 Subject: [Tutor] How to determine which function code is being called from In-Reply-To: References: Message-ID: <5318C3C3.908@gmail.com> On 03/06/2014 06:00 PM, Jignesh Sutar wrote: > Hi I'm trying to exclude a certain line of code if the function is called > by another function, see illustration below: > > > def funcA(): > print "running from funcA" # print only if running from funcA > print "running from funcA or funcB" #print when running from either > function > print "running from funcB" # print only when running from funcB > > def funcB(): > funcA() > > funcB() The simple way is to have a param telling about the caller. (But _probably_ you don't _really_ need that, it is instead an artifact of unproper design.) denis From davea at davea.name Thu Mar 6 20:14:12 2014 From: davea at davea.name (Dave Angel) Date: Thu, 6 Mar 2014 14:14:12 -0500 (EST) Subject: [Tutor] How to determine which function code is being called from References: Message-ID: Jignesh Sutar Wrote in message: > > Hi I'm trying to exclude a certain line of code if the function is called by another function, see illustration below: Your code example is all confused, so perhaps you are as well. Why should any of your code in function A care who calls it? The main point about making functions is to reuse code without caring who is calling it. If the function is going to have variable behavior, control that by passing parameters. Or perhaps this is testing code or debugging code. In that case, look at docs.python.org/2/library/inspect.org and look at function inspect.getouterframes () Can you give a nontrivial use example, and without using recursion? -- DaveA From dyoo at hashcollision.org Thu Mar 6 20:16:54 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 6 Mar 2014 11:16:54 -0800 Subject: [Tutor] How to determine which function code is being called from In-Reply-To: References: Message-ID: On Thu, Mar 6, 2014 at 9:00 AM, Jignesh Sutar wrote: > Hi I'm trying to exclude a certain line of code if the function is called by > another function, see illustration below: > > > def funcA(): > print "running from funcA" # print only if running from funcA > print "running from funcA or funcB" #print when running from either > function > print "running from funcB" # print only when running from funcB > > def funcB(): > funcA() > > funcB() Can you directly pass the state that funcA cares about as an explicit parameter? I think we need to understand what you're trying to do in context. Tell us more why you want to do what you're doing. Maybe the approach you're taking is correct, or maybe there's an easier way to accomplish what you're trying to do. From malaclypse2 at gmail.com Thu Mar 6 21:37:00 2014 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 6 Mar 2014 15:37:00 -0500 Subject: [Tutor] How to determine which function code is being called from In-Reply-To: References: Message-ID: On Thu, Mar 6, 2014 at 12:00 PM, Jignesh Sutar wrote: > Hi I'm trying to exclude a certain line of code if the function is called by > another function, see illustration below: As other have said, this is not often a good idea. That said, it is possible to inspect the call stack to see what called a particular function, like this (python 3.3): iimport inspect def funcA(): caller = inspect.stack()[1][3] print('funcA was called by ' + caller) if caller == '': print("running from funcA")# print only if running from funcA if caller in ('', 'funcB'): print("running from funcA or funcB") # print when running from either function if caller == 'funcB': print("running from funcB") # print only when running from funcB def funcB(): funcA() print('----- Calling funcA() directly -----') funcA() print('----- Calling funcB() -----') funcB() Output: >>> ----- Calling funcA() directly ----- funcA was called by running from funcA running from funcA or funcB ----- Calling funcB() ----- funcA was called by funcB running from funcA or funcB running from funcB >>> -- Jerry From jslozier at gmail.com Fri Mar 7 00:32:15 2014 From: jslozier at gmail.com (Jay Lozier) Date: Thu, 06 Mar 2014 18:32:15 -0500 Subject: [Tutor] Convert os.random output to a string Message-ID: <5319057F.60504@gmail.com> Hi, My first question I am try to generate random password strings of an arbitrary user selected length. I read to generate a random string of a user supplied length I can use os.urandom(n). I want to convert the output to a human readable string. I would like to store the string for later processing. Also, I would like to limit the characters to the US keyboard, so I might be using the wrong function. The following is the output from my terminal - Python 3.3.4 on Manjaro Linux shows the generation of a random : Python 3.3.4 (default, Feb 11 2014, 15:56:08) [GCC 4.8.2 20140206 (prerelease)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from os import urandom >>> a = urandom(16) >>> type(a) >>> a_str = a.decode() Traceback (most recent call last): File "", line 1, in UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb1 in position 0: invalid start byte >>> I am probably missing something very obvious. Thanks in advance! -- Jay Lozier jslozier at gmail.com From ben+python at benfinney.id.au Fri Mar 7 00:41:56 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 07 Mar 2014 10:41:56 +1100 Subject: [Tutor] Convert os.random output to a string References: <5319057F.60504@gmail.com> Message-ID: <85txbac2t7.fsf@benfinney.id.au> Jay Lozier writes: > I am try to generate random password strings of an arbitrary user > selected length. My first recommendation would be: Don't re-invent the wheel. Generating password strings is a complex request, not because it's particularly difficult but because the requirements are complex. Research what other solutions have been published and see whether you still need to write something different. -- \ ?Any intelligent fool can make things bigger and more complex? | `\ It takes a touch of genius ? and a lot of courage ? to move in | _o__) the opposite direction.? ?Albert Einstein | Ben Finney From alan.gauld at btinternet.com Fri Mar 7 01:34:39 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 07 Mar 2014 00:34:39 +0000 Subject: [Tutor] Convert os.random output to a string In-Reply-To: <5319057F.60504@gmail.com> References: <5319057F.60504@gmail.com> Message-ID: On 06/03/14 23:32, Jay Lozier wrote: > I am try to generate random password strings of an arbitrary user > selected length. I read to generate a random string of a user supplied > length I can use os.urandom(n). So far so good... > I want to convert the output to a human readable string. Define human readable? > I would like to store the string for later processing. Depending on the application there may be laws/rules/guidance prohibiting the storage of passwords. Best practice only ever stores the encrypted form not the original password (or more properly nowadays pass-phrase since phrases are more secure than words.) > Also, I would like to limit the characters to the US keyboard, so I > might be using the wrong function. Even in the US not everyone uses a "US keyboard" especially nowadays with various tablets/phablets/phones in use. but if you stick to the printable subset of the old ASCII set you should be close enough... But that probably means building your own random generator based on the subrange of characters. > I am probably missing something very obvious. Maybe, or you could be asking for more than the library gives? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From jslozier at gmail.com Fri Mar 7 01:43:37 2014 From: jslozier at gmail.com (Jay Lozier) Date: Thu, 06 Mar 2014 19:43:37 -0500 Subject: [Tutor] Convert os.random output to a string In-Reply-To: References: <5319057F.60504@gmail.com> Message-ID: <53191639.6070207@gmail.com> Alan I am planning to store the passwords encrypted. This part is allow a user to generate and view the generated password. Ben got me pointed to a snippet I can use. I was trying to do something the hard way. Jay On 03/06/2014 07:34 PM, Alan Gauld wrote: > On 06/03/14 23:32, Jay Lozier wrote: > >> I am try to generate random password strings of an arbitrary user >> selected length. I read to generate a random string of a user supplied >> length I can use os.urandom(n). > > So far so good... > > > I want to convert the output to a human readable string. > > Define human readable? > >> I would like to store the string for later processing. > > Depending on the application there may be laws/rules/guidance > prohibiting the storage of passwords. Best practice only ever > stores the encrypted form not the original password (or more > properly nowadays pass-phrase since phrases are more secure > than words.) > >> Also, I would like to limit the characters to the US keyboard, so I >> might be using the wrong function. > > Even in the US not everyone uses a "US keyboard" especially nowadays > with various tablets/phablets/phones in use. but if you stick to the > printable subset of the old ASCII set you should be close enough... > But that probably means building your own random generator based > on the subrange of characters. > >> I am probably missing something very obvious. > > Maybe, or you could be asking for more than the library gives? > -- Jay Lozier jslozier at gmail.com From swdunning at cox.net Fri Mar 7 06:30:31 2014 From: swdunning at cox.net (Scott W Dunning) Date: Thu, 6 Mar 2014 22:30:31 -0700 Subject: [Tutor] Help with Guess the number script Message-ID: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> I am trying to write a script for class for a game called guess the number. I?m almost done but, I?m having a hard time getting the hints to print correctly. I?ve tried ?if?? ?elif? nested, it seems like everything?.I?m posting my code for the hints below, any help is greatly appreciated! def print_hints(secret, guess): if guess < 1 or guess > 101: print print "Out of range!" print if guess < secret: print print "Too low!" elif guess < (secret - 10) or guess > (secret - 10): print "You are cold!" print print "Please play again!" elif guess < (secret - 5) or guess > (secret - 5): print "You are warmer!" print else: print "You're on fire!!" if guess > secret: print print "Too high!" print elif guess < (secret - 10) or guess > (secret - 10): print "You are cold!" print elif guess < (secret - 5)or guess > (secret - 5): print "You are warmer!" print print "Please play again!" else: print "You're on fire!!" Thanks again!! Scott From dyoo at hashcollision.org Fri Mar 7 10:05:42 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 7 Mar 2014 01:05:42 -0800 Subject: [Tutor] Help with Guess the number script In-Reply-To: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: Can you split the conditions so that they're not overlapping? One of the things that you learn about programming is that if the program is hard for humans to read, even if the program is computing something useful, you may want to work to make it humanly understandable, even if the human is having a bad day. :P That is, if you're doing something like: if A: ... if B: ... elif C: ... elif D: ... else: ... if E: ... elif F: ... elif G: ... else: H: ... which is, roughly, the control flow within your program, then it should not be too surprising that this is unexpectedly difficult to understand. I don't understand it. Can you try to rephrase what you're doing as a bunch of _nonoverlapping_ alternatives? That is, just look at the conditions your program has now. ############################################# if guess < secret: ... elif guess < (secret - 10) or guess > (secret - 10): ... elif guess < (secret - 5) or guess > (secret - 5): .... ############################################# I can't tell, from a glance, that these conditions aren't overlapping. Wait. In fact, I'm pretty sure they are overlapping. Concretely, if guess is 0 and secret is 11, then the first, second, and third cases are all true. This is a sign that the case analysis is fragile. To get it right: draw it out graphically. It will help. You are trying to break down the number line into sections. ---------------------------secret------------------------- where you want some condition to capture warmness: Case A: -----------------(--------)secret(--------)---------------- You want another to capture not-so-warmness Case B: --------(-------)----------secret----------(-------)------- one for the too-low case: Case C: -------)-------------------secret-------------------------- one for the too-high case: Case D: ---------------------------secret-------------------(------ What's case have we forgotten? The winning one: the one where the secret and the guess are the same! Call that Case E. Ok, that should cover it all, right? Notice that these are _five_ distinct, non-overlapping cases, and it should be exhaustive. For any guess and secret, exactly one of the cases above will apply. And because the conditions don't overlap, it won't even matter what order you check for A, B, C, D, or E. You might be able to break this down into a different case analysis. But try doing the non-overlapping approach. It should be clear that, if you express it well, it won't break on you. If you have more questions, please feel free to ask. Good luck! From ben+python at benfinney.id.au Fri Mar 7 10:08:21 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 07 Mar 2014 20:08:21 +1100 Subject: [Tutor] Help with Guess the number script References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: <85k3c6wf3u.fsf@benfinney.id.au> Scott W Dunning writes: > I am trying to write a script for class for a game called guess the > number. I?m almost done but, I?m having a hard time getting the hints > to print correctly. I?ve tried ?if?? ?elif? nested, it seems like > everything?. And, what happens? Please describe what you do (in enough detail so that we can try it too), what you're expecting to see, and what happens instead. -- \ ?It is the integrity of each individual human that is in final | `\ examination. On personal integrity hangs humanity's fate.? | _o__) ?Richard Buckminster Fuller, _Critical Path_, 1981 | Ben Finney From dyoo at hashcollision.org Fri Mar 7 10:18:25 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 7 Mar 2014 01:18:25 -0800 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: One more note: I used round parenthesis in the diagrams above to indicate intervals. If you think about it a bit, you'll realize I should be using square brackets in some places, or make some distinctive graphic. Open and closed circles, perhaps? Otherwise, there are tiny pinpoint gaps in the case analysis where things leak through. You want the case analysis to be watertight, not like a sieve. :P From __peter__ at web.de Fri Mar 7 10:32:15 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 07 Mar 2014 10:32:15 +0100 Subject: [Tutor] Help with Guess the number script References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: Scott W Dunning wrote: > I am trying to write a script for class for a game called guess the > number. I?m almost done but, I?m having a hard time getting the hints to > print correctly. I?ve tried ?if?? ?elif? nested, it seems like > everything?.I?m posting my code for the hints below, any help is greatly > appreciated! > > def print_hints(secret, guess): > if guess < 1 or guess > 101: > print > print "Out of range!" > print > if guess < secret: > print > print "Too low!" > elif guess < (secret - 10) or guess > (secret - 10): > print "You are cold!" > print > print "Please play again!" > elif guess < (secret - 5) or guess > (secret - 5): > print "You are warmer!" > print > else: > print "You're on fire!!" > > if guess > secret: > print > print "Too high!" > print > elif guess < (secret - 10) or guess > (secret - 10): > print "You are cold!" > print > elif guess < (secret - 5)or guess > (secret - 5): > print "You are warmer!" > print > print "Please play again!" > else: > print "You're on fire!!" You are trying too much at once. Start with a simple def get_high_low_hints(secret, guess): # buggy; I trust that you can fix it yourself. if guess < secret: return "too high" elif guess > secret: return "too low" else: assert secret == guess return "correct" You can then write simple tests like assert get_high_low_hints(secret=99, guess=99) == "correct" assert get_high_low_hints(secret=50, guess=51) == "too high" assert get_high_low_hints(secret=7, guess=6) == "too low" (which will fail btw, I added a bug to demonstrate the power of this approach) or have a look at the unittest module if you are ambitious. Once you have fixed the bugs in get_high_low_hints() you can take the next step def get_close_far_hints(secret, guess): ... # your code; have a look at the abs() function assert get_close_far_hints(50, 0) == "cold" assert get_close_far_hints(50, 90) == "cold" assert get_close_far_hints(50, 59) == "warm" assert get_close_far_hints(50, 41) == "warm" ... # similar tests for "hot"/"on fire" In short: break you problem in small sub-problems that you can easily test. It may look like it is more work at first, but you are more likely to reach a robust working result soon. Note that my functions do not print anything. This is be because functions that don't print are much easier to test: assert function_that_returns_something() == expected_result versus start_capturing_stdout() function_that_prints_something() stop_capturing_stdout() assert get_captured_stdout() == expected_result From jsutar at gmail.com Fri Mar 7 11:58:48 2014 From: jsutar at gmail.com (Jignesh Sutar) Date: Fri, 7 Mar 2014 10:58:48 +0000 Subject: [Tutor] How to determine which function code is being called from In-Reply-To: References: Message-ID: Hi All, thanks for the comments and yes I am a tad confused and a little out of my comfort zone with what I am trying to achieve here. Is this below any better way (or even worse?) of trying to achieve this. Though this doesn't actually achieve what I want it to, it may nonetheless highlight the concept in principle? def funcA(runfromB=False): if runfromB is False:"running from funcA" # print only if running from funcA print "running from funcA or funcB" #print when running from either function if runfromB is True: "running from funcB" # print only when running from funcB def funcB(runfromB): funcA(runfromB=runfromB) funcB(runfromB=True) On 6 March 2014 20:37, Jerry Hill wrote: > On Thu, Mar 6, 2014 at 12:00 PM, Jignesh Sutar wrote: > > Hi I'm trying to exclude a certain line of code if the function is > called by > > another function, see illustration below: > > As other have said, this is not often a good idea. That said, it is > possible to inspect the call stack to see what called a particular > function, like this (python 3.3): > > iimport inspect > > def funcA(): > caller = inspect.stack()[1][3] > print('funcA was called by ' + caller) > if caller == '': > print("running from funcA")# print only if running from funcA > if caller in ('', 'funcB'): > print("running from funcA or funcB") # print when running from > either function > if caller == 'funcB': > print("running from funcB") # print only when running from funcB > > def funcB(): > funcA() > > print('----- Calling funcA() directly -----') > funcA() > print('----- Calling funcB() -----') > funcB() > > Output: > > >>> > ----- Calling funcA() directly ----- > funcA was called by > running from funcA > running from funcA or funcB > ----- Calling funcB() ----- > funcA was called by funcB > running from funcA or funcB > running from funcB > >>> > > > -- > Jerry > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Fri Mar 7 12:45:12 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 7 Mar 2014 03:45:12 -0800 Subject: [Tutor] How to determine which function code is being called from In-Reply-To: References: Message-ID: > def funcB(runfromB): > funcA(runfromB=runfromB) > > funcB(runfromB=True) Yes, this is something that might be appropriate. But it really does depends on your context. Although many of the recommendations have been discouraging the stack inspection approach, even stack inspection might be appropriate, though it's certainly not a technique for beginners. That's why I think we need your context. Can you say more about why you're trying to do this? You must be thinking of something more than the funcA and funcB examples above. Can you give us a scenario where you want to do this? It's an unusual request, so we'd like to know more. Good luck! From eryksun at gmail.com Fri Mar 7 13:26:58 2014 From: eryksun at gmail.com (eryksun) Date: Fri, 7 Mar 2014 07:26:58 -0500 Subject: [Tutor] How to determine which function code is being called from In-Reply-To: References: Message-ID: On Fri, Mar 7, 2014 at 6:45 AM, Danny Yoo wrote: > > Although many of the recommendations have been discouraging the stack > inspection approach, even stack inspection might be appropriate, > though it's certainly not a technique for beginners. Stack inspection is really intended for debugging or logging. The stack frame functions in the inspect module really shouldn't be used for program logic. The warning in the docs about inspect.currentframe applies equally to inspect.stack. These functions rely on sys._getframe, which is a CPython implementation detail. PyPy and Jython do support sys._getframe. IronPython 2.6 added the command-line options -X:Frames and -X:FullFrames to support sys._getframe, but its design using the DLR doesn't require frame objects. Creating them is extra work and probably degrades performance (definitely for FullFrames). From denis.spir at gmail.com Fri Mar 7 13:26:07 2014 From: denis.spir at gmail.com (spir) Date: Fri, 07 Mar 2014 13:26:07 +0100 Subject: [Tutor] Help with Guess the number script In-Reply-To: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: <5319BADF.70305@gmail.com> On 03/07/2014 06:30 AM, Scott W Dunning wrote: > I am trying to write a script for class for a game called guess the number. I?m almost done but, I?m having a hard time getting the hints to print correctly. I?ve tried ?if?? ?elif? nested, it seems like everything?.I?m posting my code for the hints below, any help is greatly appreciated! > > def print_hints(secret, guess): > if guess < 1 or guess > 101: > print > print "Out of range!" > print > if guess < secret: > print > print "Too low!" > elif guess < (secret - 10) or guess > (secret - 10): > print "You are cold!" > print > print "Please play again!" > elif guess < (secret - 5) or guess > (secret - 5): > print "You are warmer!" > print > else: > print "You're on fire!!" > > if guess > secret: > print > print "Too high!" > print > elif guess < (secret - 10) or guess > (secret - 10): > print "You are cold!" > print > elif guess < (secret - 5)or guess > (secret - 5): > print "You are warmer!" > print > print "Please play again!" > else: > print "You're on fire!!" > > > Thanks again!! > > Scott You are providing 3 kinds of hints to the player, and trying to mix 2 of them _cleverly_ in code, which leads to confusion. Much more clever in fact, in 99% cases, not to try to clever, because programming is difficult enough; programming provides us with high challenges to your limited mind, whether or not we add to the difficulty with supposed clever tricks. clever programming is stupid stupid programming is clever The three kinds of hints are: * whether or not the guess is in interval; this must be done first, and apart, which you do well; but when it is not the case, you can quit the function immediately: the other tests & honts make no sense; right? challenge: update your design so that the program tells whether the guess is in _present_ interval, instead of the _initial_ one * too high, too low, or found (and "on fire"); in the latter case, you can quit the function * whether "cold", "warmer", or in-between; this only makes sense if guess is in interval, and not found; note that in fact depends on the _absolute_ difference Another logic is to reverse the last two hints: first deal with the "temperature" hints, including "on fire"; then only say high/low, when in interval and not found / not "on fire". I guess this more corresponds to what you were trying to express. d From gb.gabrielebrambilla at gmail.com Fri Mar 7 15:29:05 2014 From: gb.gabrielebrambilla at gmail.com (Gabriele Brambilla) Date: Fri, 7 Mar 2014 09:29:05 -0500 Subject: [Tutor] c++ on python Message-ID: Hi, in the next days I will receive a c++ code that I would like to run in python (http://docs.python.org/2/extending/index.html). It should be self consistent (no extraroutines). I want to be ready to use it... Has someone some C++ code examples available that I can try to run easily before getting that code? thanks Gabriele -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Fri Mar 7 16:00:26 2014 From: eryksun at gmail.com (eryksun) Date: Fri, 7 Mar 2014 10:00:26 -0500 Subject: [Tutor] c++ on python In-Reply-To: References: Message-ID: On Fri, Mar 7, 2014 at 9:29 AM, Gabriele Brambilla wrote: > > in the next days I will receive a c++ code that I would like to run in > python (http://docs.python.org/2/extending/index.html). > It should be self consistent (no extraroutines). > I want to be ready to use it... Has someone some C++ code examples available > that I can try to run easily before getting that code? Writing CPython extension modules is probably off topic for python-tutor. ctypes is on topic, but manually wrapping a C++ library with a C API that's accessible via ctypes is a lot of work. I recommend using SWIG or Cython instead. http://cython.readthedocs.org/en/latest/src/userguide/wrapping_CPlusPlus.html cython-users forum: http://groups.google.com/group/cython-users http://swig.org/Doc2.0/Python.html#Python From alan.gauld at btinternet.com Fri Mar 7 18:53:01 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 07 Mar 2014 17:53:01 +0000 Subject: [Tutor] c++ on python In-Reply-To: References: Message-ID: On 07/03/14 14:29, Gabriele Brambilla wrote: > in the next days I will receive a c++ code that I would like to run in > python (http://docs.python.org/2/extending/index.html). What do you mean? Are you receiving C++ source code? If so is it for an executable program, a library or just a single object file? When you say run it in python do you mean you want to launch the executable program from Python (see subprocess module) or call functions in the library (maybe ctypes) or do you want to to embed the C code as a Python module? If its an executable to be run via subprocess thats fine for this list. If its using ctypes to call functions in a library thats about the extreme edge of this list.But there is a ctypes list that is probably more appropriate. If its embedding the C library as a python module that is definitely off topic and you should probably try the main Python list > It should be self consistent (no extraroutines). Again I'm not sure what you mean by that. Do you mean it has no dependencies on other code - not even glibc? Or just that it is a standalone executable? > I want to be ready to use it... Has someone some C++ code examples > available that I can try to run easily before getting that code? You need to be a lot more specific about what you mean. What exactly are you trying to do? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Fri Mar 7 19:02:00 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 07 Mar 2014 18:02:00 +0000 Subject: [Tutor] Help with Guess the number script In-Reply-To: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: On 07/03/14 05:30, Scott W Dunning wrote: > I am trying to write a script for class for a game called guess the number. Others have given general hints here are a couple of specifics... > def print_hints(secret, guess): > if guess < 1 or guess > 101: As I recall the spec said guesses could be between 1 and 100? What happens above if the guess is 101? > elif guess < (secret - 10) or guess > (secret - 10): Do you really mean to test for secret minus 10 in both expressions? > elif guess < (secret - 5) or guess > (secret - 5): > print "You are warmer!" And similarly here, do you really want to test against (secret-5) in both cases? > elif guess < (secret - 10) or guess > (secret - 10): > print "You are cold!" And again... > elif guess < (secret - 5)or guess > (secret - 5): > print "You are warmer!" And again... HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From swdunning at cox.net Sat Mar 8 02:23:43 2014 From: swdunning at cox.net (Scott W Dunning) Date: Fri, 7 Mar 2014 18:23:43 -0700 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: On Mar 7, 2014, at 11:02 AM, Alan Gauld wrote: GOT IT!! Finally! Thanks for all of your help!! This is what I got, not sure if it?s correct but it?s working! def print_hints(secret, guess): if guess < 1 or guess > 100: print print "Out of range!" print if guess < secret: print print "Too low!" if guess < secret - 10: print "You are cold!" print print "Please play again!" elif guess < secret - 5: print "You are warmer!" print print "Please play again" else: print "You're on fire!!" print print "Please play again" if guess > secret: print print "Too high!" if guess > secret + 10: print "You are cold!" print print "Please play again!" elif guess > secret + 5: print "You are warmer!" print print "Please play again" else: print "You're on fire!!" print print "Please play again" From alan.gauld at btinternet.com Sat Mar 8 10:13:09 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 08 Mar 2014 09:13:09 +0000 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: On 08/03/14 01:23, Scott W Dunning wrote: > > On Mar 7, 2014, at 11:02 AM, Alan Gauld wrote: > > GOT IT!! Finally! Thanks for all of your help!! > > This is what I got, not sure if it?s correct but it?s working! Well done. And now that you have the right set of tests you can half the number of lines by combining your if conditions again, like you had in the original post. ie. Bring your hot/cold/warm tests together. > def print_hints(secret, guess): > if guess < 1 or guess > 100: > print > print "Out of range!" > print > if guess < secret: > print > print "Too low!" > if guess < secret - 10: > print "You are cold!" > print > print "Please play again!" > elif guess < secret - 5: > print "You are warmer!" > print > print "Please play again" > else: > print "You're on fire!!" > print > print "Please play again" > if guess > secret: > print > print "Too high!" > if guess > secret + 10: > print "You are cold!" > print > print "Please play again!" > elif guess > secret + 5: > print "You are warmer!" > print > print "Please play again" > else: > print "You're on fire!!" > print > print "Please play again" > HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From denis.spir at gmail.com Sat Mar 8 11:57:25 2014 From: denis.spir at gmail.com (spir) Date: Sat, 08 Mar 2014 11:57:25 +0100 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: <531AF795.9050507@gmail.com> On 03/08/2014 10:13 AM, Alan Gauld wrote: > On 08/03/14 01:23, Scott W Dunning wrote: >> >> On Mar 7, 2014, at 11:02 AM, Alan Gauld wrote: >> >> GOT IT!! Finally! Thanks for all of your help!! >> >> This is what I got, not sure if it?s correct but it?s working! > > Well done. > And now that you have the right set of tests you can > half the number of lines by combining your if > conditions again, like you had in the original > post. ie. Bring your hot/cold/warm tests together. Yes, and note the relevant piece of data is the absolute value: abs(secret-guess). This gives you at once on-fire / hot / warm / cold / icy ... whatever you like ;-) (pretty sexy game, guess-my-number!). d From breamoreboy at yahoo.co.uk Sat Mar 8 14:26:39 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 08 Mar 2014 13:26:39 +0000 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: On 08/03/2014 01:23, Scott W Dunning wrote: > > On Mar 7, 2014, at 11:02 AM, Alan Gauld wrote: > > GOT IT!! Finally! Thanks for all of your help!! If at first you don't succeed... :) > > This is what I got, not sure if it?s correct but it?s working! > > def print_hints(secret, guess): > if guess < 1 or guess > 100: Only now do I feel that it's time to point out that the above line would probably be written by an experienced Python programmer as:- if 1 > guess > 100: -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From davea at davea.name Sat Mar 8 14:36:39 2014 From: davea at davea.name (Dave Angel) Date: Sat, 8 Mar 2014 08:36:39 -0500 (EST) Subject: [Tutor] Help with Guess the number script References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: Mark Lawrence Wrote in message: > On 08/03/2014 01:23, Scott W Dunning wrote: > >> >> def print_hints(secret, guess): >> if guess < 1 or guess > 100: > > Only now do I feel that it's time to point out that the above line would > probably be written by an experienced Python programmer as:- > > if 1 > guess > 100: > With an appropriate 'not' or its equivalent, of course. -- DaveA From eryksun at gmail.com Sat Mar 8 15:29:36 2014 From: eryksun at gmail.com (eryksun) Date: Sat, 8 Mar 2014 09:29:36 -0500 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: On Sat, Mar 8, 2014 at 8:36 AM, Dave Angel wrote: > Mark Lawrence Wrote in message: >> On 08/03/2014 01:23, Scott W Dunning wrote: >> >>> def print_hints(secret, guess): >>> if guess < 1 or guess > 100: >> >> Only now do I feel that it's time to point out that the above line would >> probably be written by an experienced Python programmer as:- >> >> if 1 > guess > 100: >> > > With an appropriate 'not' or its equivalent, of course. i.e. guess < 1 or guess > 100 becomes not not (guess < 1 or guess > 100) distribute over the disjunction not (not (guess < 1) and not (guess > 100)) logically negate the comparisons not (1 <= guess and guess <= 100) finally, write the conjoined comparisons as a chained comparison: not (1 <= guess <= 100) i.e., guess isn't in the closed interval [1, 100]. Anyway, you needn't go out of your way to rewrite the expression using a chained comparison. The disjunctive expression is actually implemented more efficiently by CPython's compiler, which you can verify using the dis module to disassemble the bytecode. From breamoreboy at yahoo.co.uk Sat Mar 8 15:35:29 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 08 Mar 2014 14:35:29 +0000 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: On 08/03/2014 14:29, eryksun wrote: > > Anyway, you needn't go out of your way to rewrite the expression using > a chained comparison. The disjunctive expression is actually > implemented more efficiently by CPython's compiler, which you can > verify using the dis module to disassemble the bytecode. I have no interest in the efficiency, only what is easiest for me to read, which in this case is the chained comparison. As a rule of thumb I'd also prefer it to be logically correct :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From swdunning at cox.net Sat Mar 8 19:42:28 2014 From: swdunning at cox.net (Scott dunning) Date: Sat, 8 Mar 2014 11:42:28 -0700 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: > On Mar 8, 2014, at 6:36 AM, Dave Angel wrote: > > Mark Lawrence Wrote in message: >>> On 08/03/2014 01:23, Scott W Dunning wrote: >>> >>> >>> def print_hints(secret, guess): >>> if guess < 1 or guess > 100: >> >> Only now do I feel that it's time to point out that the above line would >> probably be written by an experienced Python programmer as:- >> >> if 1 > guess > 100: > > With an appropriate 'not' or its equivalent, of course. > This is how our teacher wanted it all written under the print_hints function. Besides if I was an experienced python programmer I wouldn't be asking such trivial stuff under the tutor forum lol. From swdunning at cox.net Sat Mar 8 19:44:13 2014 From: swdunning at cox.net (Scott dunning) Date: Sat, 8 Mar 2014 11:44:13 -0700 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: <1CA8F224-DC52-4F21-A701-838B15417501@cox.net> > On Mar 8, 2014, at 6:26 AM, Mark Lawrence wrote: > >> On 08/03/2014 01:23, Scott W Dunning wrote: >> >> On Mar 7, 2014, at 11:02 AM, Alan Gauld wrote: >> >> GOT IT!! Finally! Thanks for all of your help!! > > If at first you don't succeed... :) > >> >> This is what I got, not sure if it?s correct but it?s working! >> >> def print_hints(secret, guess): >> if guess < 1 or guess > 100: > > Only now do I feel that it's time to point out that the above line would probably be written by an experienced Python programmer as:- > > if 1 > guess > 100: > OH! I see what you're saying, ignore my last post. Yes that looks cleaner. From swdunning at cox.net Sat Mar 8 19:50:43 2014 From: swdunning at cox.net (Scott dunning) Date: Sat, 8 Mar 2014 11:50:43 -0700 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: <5A96D460-3538-48C9-BAD8-2A514BA78398@cox.net> > On Mar 8, 2014, at 3:57 AM, spir wrote: > >> On 03/08/2014 10:13 AM, Alan Gauld wrote: >>> On 08/03/14 01:23, Scott W Dunning wrote: >>> >>> On Mar 7, 2014, at 11:02 AM, Alan Gauld wrote: >>> >>> GOT IT!! Finally! Thanks for all of your help!! >>> >>> This is what I got, not sure if it?s correct but it?s working! >> >> Well done. >> And now that you have the right set of tests you can >> half the number of lines by combining your if >> conditions again, like you had in the original >> post. ie. Bring your hot/cold/warm tests together. Yeah I'm gonna try that. The reason I split it up in the first place is I couldn't get it to work properly being all together (ie Either too high or too low yet always either cold, warm, or on fire). > > Yes, and note the relevant piece of data is the absolute value: abs(secret-guess). This gives you at once on-fire / hot / warm / cold / icy ... whatever you like ;-) (pretty sexy game, guess-my-number!). > Hmm, not sure I understand. From eryksun at gmail.com Sun Mar 9 01:25:21 2014 From: eryksun at gmail.com (eryksun) Date: Sat, 8 Mar 2014 19:25:21 -0500 Subject: [Tutor] Help with Guess the number script In-Reply-To: <1CA8F224-DC52-4F21-A701-838B15417501@cox.net> References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> <1CA8F224-DC52-4F21-A701-838B15417501@cox.net> Message-ID: On Sat, Mar 8, 2014 at 1:44 PM, Scott dunning wrote: >> if 1 > guess > 100: >> > OH! I see what you're saying, ignore my last post. Yes that looks > cleaner. Please read section 6.9 of the language reference, which defines Python comparison expressions. http://docs.python.org/3/reference/expressions#not-in Here's the description of chained comparisons: Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false). Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once. Note that a op1 b op2 c doesn?t imply any kind of comparison between a and c, so that, e.g., x < y > z is perfectly legal (though perhaps not pretty). Thus `1 > guess > 100` is equivalent to `(guess < 1) and (guess > 100)`, which is always false. The correct chained comparison is `not (1 <= guess <= 100)`. Chaining is generally simpler, since all expressions are only evaluated once. In this particular case, with a local variable compared to constants, the chained form is slightly less efficient in CPython. Though if it "looks cleaner" to you, certainly use it. Readability takes precedence. From myakayebashagi at gmail.com Sun Mar 9 05:32:23 2014 From: myakayebashagi at gmail.com (MICHAEL BASHAGI) Date: Sun, 9 Mar 2014 07:32:23 +0300 Subject: [Tutor] educational Message-ID: i wanted to use a .jpeg image file on a label in a small program that am building in Python, i use Window 7 professional OS, and Python 3.4....here are my codes:- import sys from tkinter import * #Window mGui=Tk() mGui.geometry("1000x500") mGui.title("Kamusi") #Functions #Variables ment=StringVar() #Images image = Image.open("logo.jpg") photo = ImageTk.PhotoImage(image) #Widgets Logo=Label(mGui,image=photo,width=510,height=150) Logo.grid(row=0,column=3) when i run those codes i get this error message:- AttributeError: type object 'Image' has no attribute 'open' -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Sun Mar 9 09:57:05 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 09 Mar 2014 19:57:05 +1100 Subject: [Tutor] educational References: Message-ID: <85y50jvjfi.fsf@benfinney.id.au> Welcome, Michael! MICHAEL BASHAGI writes: > when i run those codes i get this error message:- When showing an error, please show the entire traceback; it usually contains information useful for diagnosing the problem. > AttributeError: type object 'Image' has no attribute 'open' In this case, I'm fairly sure the line producing this error is:: image = Image.open("logo.jpg") And Python is correct, the ?Image? type has no ?open? attribute. What leads you to think that would work? If there is some article online telling you to use that, it's incorrect; please help us to correct that. It's best not to guess what attributes are in a type (otherwise known as the ?API? for the type). Instead, consult the documentation. For Tkinter, that is . -- \ ?Most people, I think, don't even know what a rootkit is, so | `\ why should they care about it?? ?Thomas Hesse, Sony BMG, 2006 | _o__) | Ben Finney From ben+python at benfinney.id.au Sun Mar 9 09:59:39 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 09 Mar 2014 19:59:39 +1100 Subject: [Tutor] educational References: <85y50jvjfi.fsf@benfinney.id.au> Message-ID: <85txb7vjb8.fsf@benfinney.id.au> Ben Finney writes: > It's best not to guess what attributes are in a type (otherwise known as > the ?API? for the type). Instead, consult the documentation. For > Tkinter, that is . My apologies; there's a broken link in the documentation. Use this instead . -- \ ?I busted a mirror and got seven years bad luck, but my lawyer | `\ thinks he can get me five.? ?Steven Wright | _o__) | Ben Finney From __peter__ at web.de Sun Mar 9 11:37:50 2014 From: __peter__ at web.de (Peter Otten) Date: Sun, 09 Mar 2014 11:37:50 +0100 Subject: [Tutor] educational References: <85y50jvjfi.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Welcome, Michael! > > MICHAEL BASHAGI writes: > >> when i run those codes i get this error message:- > > When showing an error, please show the entire traceback; it usually > contains information useful for diagnosing the problem. > >> AttributeError: type object 'Image' has no attribute 'open' > > In this case, I'm fairly sure the line producing this error is:: > > image = Image.open("logo.jpg") > > And Python is correct, the ?Image? type has no ?open? attribute. What > leads you to think that would work? If there is some article online > telling you to use that, it's incorrect; please help us to correct that. There are a few things around called `Image`. The code the OP is trying to adapt probably uses the Image from the PIL: import tkinter from PIL import ImageTk from PIL import Image mGui = tkinter.Tk() image = Image.open("logo.jpg") photo = ImageTk.PhotoImage(image=image) Logo = tkinter.Label(mGui, image=photo) Logo.grid(row=0, column=3) mGui.mainloop() This can be simplified: import tkinter from PIL import ImageTk mGui = tkinter.Tk() photo = ImageTk.PhotoImage(file="logo.jpg") Logo = tkinter.Label(mGui, image=photo) Logo.grid(row=0, column=3) mGui.mainloop() From alan.gauld at btinternet.com Sun Mar 9 18:06:36 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 09 Mar 2014 17:06:36 +0000 Subject: [Tutor] educational In-Reply-To: References: <85y50jvjfi.fsf@benfinney.id.au> Message-ID: On 09/03/14 10:37, Peter Otten wrote: >> In this case, I'm fairly sure the line producing this error is:: >> >> image = Image.open("logo.jpg") >> >> And Python is correct, the ?Image? type has no ?open? attribute. What > > There are a few things around called `Image`. The code the OP is trying to > adapt probably uses the Image from the PIL: > Which may lead to another issue since the OP is using Python 3.4. Is PIL available for any Python 3.x yet? And especially for 3.4? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From mail at timgolden.me.uk Sun Mar 9 18:15:16 2014 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 09 Mar 2014 17:15:16 +0000 Subject: [Tutor] educational In-Reply-To: References: <85y50jvjfi.fsf@benfinney.id.au> Message-ID: <531CA1A4.2060400@timgolden.me.uk> On 09/03/2014 17:06, Alan Gauld wrote: > On 09/03/14 10:37, Peter Otten wrote: > >>> In this case, I'm fairly sure the line producing this error is:: >>> >>> image = Image.open("logo.jpg") >>> >>> And Python is correct, the ?Image? type has no ?open? attribute. What >> >> There are a few things around called `Image`. The code the OP is >> trying to >> adapt probably uses the Image from the PIL: >> > > Which may lead to another issue since the OP is using Python 3.4. > > Is PIL available for any Python 3.x yet? > And especially for 3.4? > Pillow does seem to (haven't used it myself): http://pillow.readthedocs.org/en/latest/installation.html TJG From ben+python at benfinney.id.au Sun Mar 9 20:56:40 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 10 Mar 2014 06:56:40 +1100 Subject: [Tutor] educational References: <85y50jvjfi.fsf@benfinney.id.au> Message-ID: <85pplvuow7.fsf@benfinney.id.au> Peter Otten <__peter__ at web.de> writes: > Ben Finney wrote: > > And Python is correct, the ?Image? type has no ?open? attribute. What > > leads you to think that would work? If there is some article online > > telling you to use that, it's incorrect; please help us to correct that. > > There are a few things around called `Image`. The code the OP is trying to > adapt probably uses the Image from the PIL: Then I'm further confirmed in my view that ?from tkinter import *? is dreadful practice, especially for a system we recommend to newcomers. If it were:: > import tkinter > from PIL import ImageTk > from PIL import Image then it would be clear which ?Image? is being used where. Now all I need is for the Tkinter-using community to change itself to fix this confusing practice. I won't hold my breath. -- \ Rommel: ?Don't move, or I'll turn the key on this can of Spam!? | `\ ?The Goon Show, _Rommel's Treasure_ | _o__) | Ben Finney From alan.gauld at btinternet.com Sun Mar 9 22:35:45 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 09 Mar 2014 21:35:45 +0000 Subject: [Tutor] educational In-Reply-To: <85pplvuow7.fsf@benfinney.id.au> References: <85y50jvjfi.fsf@benfinney.id.au> <85pplvuow7.fsf@benfinney.id.au> Message-ID: On 09/03/14 19:56, Ben Finney wrote: > Then I'm further confirmed in my view that ?from tkinter import *? is > dreadful practice, especially for a system we recommend to newcomers. Its always dreadful practice for production code regardless of the module. Its OK for playing at the >>> prompt but not much more. I usually import Tkinter as import tkinter as tk > Now all I need is for the Tkinter-using community to change itself to > fix this confusing practice. I won't hold my breath. I don't find everyone in the Tkinter community using from tkinter import *, quite a few use normal practice. But historically I agree it's been an unfortunate paradigm, Even the IDLE code uses import * :-( -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From breamoreboy at yahoo.co.uk Sun Mar 9 23:14:47 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 09 Mar 2014 22:14:47 +0000 Subject: [Tutor] educational In-Reply-To: References: <85y50jvjfi.fsf@benfinney.id.au> <85pplvuow7.fsf@benfinney.id.au> Message-ID: On 09/03/2014 21:35, Alan Gauld wrote: > On 09/03/14 19:56, Ben Finney wrote: > >> Then I'm further confirmed in my view that ?from tkinter import *? is >> dreadful practice, especially for a system we recommend to newcomers. > > Its always dreadful practice for production code regardless of the > module. Its OK for playing at the >>> prompt but not much more. > > I usually import Tkinter as > > import tkinter as tk > >> Now all I need is for the Tkinter-using community to change itself to >> fix this confusing practice. I won't hold my breath. > > I don't find everyone in the Tkinter community using from tkinter import > *, quite a few use normal practice. But historically I agree > it's been an unfortunate paradigm, Even the IDLE code uses > import * :-( > > I vaguely recall reading somewhere that IDLE is moving towards '?mport tkinter as tk', a process which would certainly be helped by the extremely sensible PEP 434 http://legacy.python.org/dev/peps/pep-0434/ -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From ben+python at benfinney.id.au Sun Mar 9 23:33:39 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 10 Mar 2014 09:33:39 +1100 Subject: [Tutor] educational References: <85y50jvjfi.fsf@benfinney.id.au> <85pplvuow7.fsf@benfinney.id.au> Message-ID: <85ha77uhmk.fsf@benfinney.id.au> Alan Gauld writes: > On 09/03/14 19:56, Ben Finney wrote: > > Now all I need is for the Tkinter-using community to change itself > > to fix this confusing practice [?from tkinter import *?]. I won't > > hold my breath. > > I don't find everyone in the Tkinter community using from tkinter > import *, quite a few use normal practice. Then they are not following the advice of the documentation , which explicitly recommends ?from tkinter import *?. It's also prevalent in third-party documents which are referenced from the official documentation. This one does at least get it right. If ?import tkinter as tk? were to become the norm in official and third-party documentation, I'd agree the problem would be solved at that point. -- \ ?One bad programmer can easily create two new jobs a year. | `\ Hiring more bad programmers will just increase our perceived | _o__) need for them.? ?David Lorge Parnas, 1999-03 | Ben Finney From street.sweeper at mailworks.org Sun Mar 9 20:22:35 2014 From: street.sweeper at mailworks.org (street.sweeper at mailworks.org) Date: Sun, 09 Mar 2014 15:22:35 -0400 Subject: [Tutor] improvements on a renaming script Message-ID: <1394392955.5102.92394069.67612DD0@webmail.messagingengine.com> Hello all, A bit of background, I had some slides scanned and a 3-character slice of the file name indicates what roll of film it was. This is recorded in a tab-separated file called fileNames.tab. Its content looks something like: p01 200511_autumn_leaves p02 200603_apple_plum_cherry_blossoms The original file names looked like: 1p01_abc_0001.jpg 1p02_abc_0005.jpg The renamed files are: 200511_autumn_leaves_-_001.jpeg 200603_apple_plum_cherry_blossoms_-_005.jpeg The script below works and has done what I wanted, but I have a few questions: - In the get_long_names() function, the for/if thing is reading the whole fileNames.tab file every time, isn't it? In reality, the file was only a few dozen lines long, so I suppose it doesn't matter, but is there a better way to do this? - Really, I wanted to create a new sequence number at the end of each file name, but I thought this would be difficult. In order for it to count from 01 to whatever the last file is per set p01, p02, etc, it would have to be aware of the set name and how many files are in it. So I settled for getting the last 3 digits of the original file name using splitext(). The strings were unique, so it worked out. However, I can see this being useful in other places, so I was wondering if there is a good way to do this. Is there a term or phrase I can search on? - I'd be interested to read any other comments on the code. I'm new to python and I have only a bit of computer science study, quite some time ago. #!/usr/bin/env python3 import os import csv # get longnames from fileNames.tab def get_long_name(glnAbbrev): with open( os.path.join(os.path.expanduser('~'),'temp2','fileNames.tab') ) as filenames: filenamesdata = csv.reader(filenames, delimiter='\t') for row in filenamesdata: if row[0] == glnAbbrev: return row[1] # find shortname from slice in picture filename def get_slice(fn): threeColSlice = fn[1:4] return threeColSlice # get 3-digit sequence number from basename def get_bn_seq(fn): seq = os.path.splitext(fn)[0][-3:] return seq # directory locations indir = os.path.join(os.path.expanduser('~'),'temp4') outdir = os.path.join(os.path.expanduser('~'),'temp5') # rename for f in os.listdir(indir): if f.endswith(".jpg"): os.rename( os.path.join(indir,f),os.path.join( outdir, get_long_name(get_slice(f))+"_-_"+get_bn_seq(f)+".jpeg") ) exit() Thanks! From bgailer at gmail.com Mon Mar 10 03:50:02 2014 From: bgailer at gmail.com (bob gailer) Date: Sun, 09 Mar 2014 22:50:02 -0400 Subject: [Tutor] improvements on a renaming script In-Reply-To: <1394392955.5102.92394069.67612DD0@webmail.messagingengine.com> References: <1394392955.5102.92394069.67612DD0@webmail.messagingengine.com> Message-ID: <531D285A.6070606@gmail.com> On 3/9/2014 3:22 PM, street.sweeper at mailworks.org wrote: > Hello all, > > A bit of background, I had some slides scanned and a 3-character > slice of the file name indicates what roll of film it was. > This is recorded in a tab-separated file called fileNames.tab. > Its content looks something like: > > p01 200511_autumn_leaves > p02 200603_apple_plum_cherry_blossoms > > The original file names looked like: > > 1p01_abc_0001.jpg > 1p02_abc_0005.jpg > > The renamed files are: > > 200511_autumn_leaves_-_001.jpeg > 200603_apple_plum_cherry_blossoms_-_005.jpeg > > The script below works and has done what I wanted, but I have a > few questions: > > - In the get_long_names() function, the for/if thing is reading > the whole fileNames.tab file every time, isn't it? In reality, > the file was only a few dozen lines long, so I suppose it doesn't > matter, but is there a better way to do this? The "usual" way is to create a dictionary with row[0] contents as keys and row[1] contents as values. Do this once per run. Then lookup each glnAbbrev in the dictionary and return the corresponding value. > - Really, I wanted to create a new sequence number at the end of > each file name, but I thought this would be difficult. In order > for it to count from 01 to whatever the last file is per set p01, > p02, etc, it would have to be aware of the set name and how many > files are in it. So I settled for getting the last 3 digits of > the original file name using splitext(). The strings were unique, > so it worked out. However, I can see this being useful in other > places, so I was wondering if there is a good way to do this. > Is there a term or phrase I can search on? I'm sorry but I don't fully understand that paragraph. And why would you need to know the number of files? > - I'd be interested to read any other comments on the code. > I'm new to python and I have only a bit of computer science study, > quite some time ago. Beware using tabs as indents. As rendered by Thunderbird they appear as 8 spaces which is IMHO overkill. It is much better to use spaces. Most Python IDEs have an option to convert tabs to spaces. The Python recommendation is 4; I use 2. > #!/usr/bin/env python3 > > import os > import csv > > # get longnames from fileNames.tab > def get_long_name(glnAbbrev): > with open( > os.path.join(os.path.expanduser('~'),'temp2','fileNames.tab') > ) as filenames: > filenamesdata = csv.reader(filenames, delimiter='\t') > for row in filenamesdata: > if row[0] == glnAbbrev: > return row[1] > > # find shortname from slice in picture filename > def get_slice(fn): > threeColSlice = fn[1:4] > return threeColSlice Writing a function to get a slice seems overkill also. Just slice in place. > # get 3-digit sequence number from basename > def get_bn_seq(fn): > seq = os.path.splitext(fn)[0][-3:] > return seq > > # directory locations > indir = os.path.join(os.path.expanduser('~'),'temp4') > outdir = os.path.join(os.path.expanduser('~'),'temp5') > > # rename > for f in os.listdir(indir): > if f.endswith(".jpg"): > os.rename( > os.path.join(indir,f),os.path.join( > outdir, > get_long_name(get_slice(f))+"_-_"+get_bn_seq(f)+".jpeg") > ) > > exit() > HTH - remember to reply-all so a copy goes to the list, place your comments in-line as I did, and delete irrelevant text. From eryksun at gmail.com Mon Mar 10 04:38:33 2014 From: eryksun at gmail.com (eryksun) Date: Sun, 9 Mar 2014 23:38:33 -0400 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: > On Mar 8, 2014, at 7:29 AM, eryksun wrote: >> >> not not (guess < 1 or guess > 100) > > Why a not not? Wouldn?t that just be saying do this because the > second not is undoing the first? In boolean algebra, `not (A or B)` is equivalent to `not A and not B` (De Morgan's law). I double negated in order to mechanically apply this rule, e.g. A or B = not not (A or B) = not (not A and not B) >> Anyway, you needn't go out of your way to rewrite the expression using >> a chained comparison. The disjunctive expression is actually >> implemented more efficiently by CPython's compiler, which you can >> verify using the dis module to disassemble the bytecode. > > I?m not sure what you?re talking about in the above paragraph. There's hardly any difference in how the interpreter evaluates the code in a simple case like this, and it's actually slightly more efficient (in CPython) without chaining. That said, chained comparisons are more efficient when the expressions being compared are computationally expensive, since each expression is only evaluated once. Regarding bytecode, CPython compiles Python source code to a sequence of bytecode operations that get interpreted at runtime. It's an implementation detail, but examining CPython bytecode is nonetheless informative. Here's a basic example: >>> def f(): ... x = 'abc' The function's code object contains the compiled code as a byte sting in its co_code attribute: >>> f.__code__.co_code b'd\x01\x00}\x00\x00d\x00\x00S' This assembled code isn't easy to read. Also, reading it requires referencing other fields of the code object such as co_consts and co_varnames. The dis module disassembles it to a form that's a bit easier to read: >>> dis.dis(f) 2 0 LOAD_CONST 1 ('abc') 3 STORE_FAST 0 (x) 6 LOAD_CONST 0 (None) 9 RETURN_VALUE The documentation for the dis module includes a basic description of each operation. http://docs.python.org/3/library/dis From cs at zip.com.au Mon Mar 10 02:08:00 2014 From: cs at zip.com.au (Cameron Simpson) Date: Mon, 10 Mar 2014 12:08:00 +1100 Subject: [Tutor] improvements on a renaming script In-Reply-To: <1394392955.5102.92394069.67612DD0@webmail.messagingengine.com> References: <1394392955.5102.92394069.67612DD0@webmail.messagingengine.com> Message-ID: <20140310010800.GA22042@cskk.homeip.net> On 09Mar2014 15:22, street.sweeper at mailworks.org wrote: > A bit of background, I had some slides scanned and a 3-character > slice of the file name indicates what roll of film it was. > This is recorded in a tab-separated file called fileNames.tab. > Its content looks something like: > > p01 200511_autumn_leaves > p02 200603_apple_plum_cherry_blossoms > > The original file names looked like: > > 1p01_abc_0001.jpg > 1p02_abc_0005.jpg > > The renamed files are: > > 200511_autumn_leaves_-_001.jpeg > 200603_apple_plum_cherry_blossoms_-_005.jpeg > > The script below works and has done what I wanted, but I have a > few questions: > > - In the get_long_names() function, the for/if thing is reading > the whole fileNames.tab file every time, isn't it? In reality, > the file was only a few dozen lines long, so I suppose it doesn't > matter, but is there a better way to do this? Read it once, into a dictionary. I'd rename "get_long_name" to "get_long_names", and have it create and return a dictionary with keys being the glnAbbrev value and values being the long name. So start with: long_names = {} Fill it out by saving the abbrev and long_name for each row, and return "long_names" at the end of the function. Then call it once at the start of your program, and then just look things up directly in the dictionary instead of calling "get_long_name()". > - Really, I wanted to create a new sequence number at the end of > each file name, but I thought this would be difficult. In order > for it to count from 01 to whatever the last file is per set p01, > p02, etc, it would have to be aware of the set name and how many > files are in it. So I settled for getting the last 3 digits of > the original file name using splitext(). The strings were unique, > so it worked out. However, I can see this being useful in other > places, so I was wondering if there is a good way to do this. > Is there a term or phrase I can search on? Nothing specific comes to mind. When I do this kind of thing I tend to make an opening pass over os.listdir() pulling out all the names and noting whatever is relevant. In your case you might maintain a dictionary of the "base" filename key (i.e. the filename without the trailing sequence number) and the maximum sequence number seen for that file. Then I'd have a short function which was passed this dictionary and a "base" filename, and returned a new sequence number, being the first sequence number after the current maximum from the dictionary for which the constructed new filename did not exist. Then update the number in the dictionary, probably inside that function. > - I'd be interested to read any other comments on the code. > I'm new to python and I have only a bit of computer science study, > quite some time ago. My personal habit is to put the main program logic at the top. I know you can't just move it because you rely on functions when must be defined first. However, you can do this: def main(argv): ... main program logic here ... return and put: sys.exit(main(sys.argv)) at the bottom of the program. This has the advantage of having the main program logic at the top where it is easy to find. > # rename > for f in os.listdir(indir): > if f.endswith(".jpg"): > os.rename( > os.path.join(indir,f),os.path.join( > outdir, > get_long_name(get_slice(f))+"_-_"+get_bn_seq(f)+".jpeg") > ) I'd preceed the rename() by computing: oldname = os.path.join(indir,f) newname = ( os.path.join(outdir, get_long_name(get_slice(f)) + "_-_" + get_bn_seq(f) + ".jpeg" ) and just pass oldname, newname to os.rename(). Easily to read and debug. Cheers, -- Cameron Simpson Patriotism means to stand by the country. It does not mean to stand by the President. - Theodore Roosevelt From cs at zip.com.au Mon Mar 10 04:11:10 2014 From: cs at zip.com.au (Cameron Simpson) Date: Mon, 10 Mar 2014 14:11:10 +1100 Subject: [Tutor] improvements on a renaming script In-Reply-To: <531D285A.6070606@gmail.com> References: <531D285A.6070606@gmail.com> Message-ID: <20140310031110.GA51895@cskk.homeip.net> On 09Mar2014 22:50, bob gailer wrote: > Beware using tabs as indents. As rendered by Thunderbird they appear > as 8 spaces which is IMHO overkill. > It is much better to use spaces. Most Python IDEs have an option to > convert tabs to spaces. Further to this remark, this isn't an instruction to not use the TAB key. It is advice to get your editor to fill in the program text with the necessary number of spaces instead of inserting a literal TAB character. (But if you can't tell your editor to do this, then avoid the TAB key; use the space bar.) > The Python recommendation is 4; I use 2. Me too. But not in code I give to other projects; there the rule is "use their coding standard", and that is usually 4 spaces per indent for Python projects. As an example, I use vi/vim and have this in my config: set expandtab set shiftwidth=2 set tabstop=8 The expandtab tells vim to insert spaces instead of a TAB character. The shiftwidth reflects my 2 space indent preference. The tabstop reflects the expectation that interpretation of the tab keystroke and of any literal TABs in the text expects them to indicate an 8-column TAB convention. Note that many users set their tabstop equivalent to 4 or whatever their preferrer indentation depth is. This is why it is some important and useful to get your editor to insert spaces: whatever your personal tabstop setting, the program text will be correctly rendered for others because it will not contain TAB character, it will contain spaces. Cheers, -- Cameron Simpson Wirth's Law: Software is getting slower more rapidly than hardware becomes faster. From swdunning at cox.net Mon Mar 10 03:03:33 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sun, 9 Mar 2014 19:03:33 -0700 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: On Mar 8, 2014, at 7:29 AM, eryksun wrote: > i.e. > > guess < 1 or guess > 100 > > becomes > > not not (guess < 1 or guess > 100) Why a not not? Wouldn?t that just be saying do this because the second not is undoing the first? > > distribute over the disjunction > > not (not (guess < 1) and not (guess > 100)) > > logically negate the comparisons > > not (1 <= guess and guess <= 100) > > finally, write the conjoined comparisons as a chained comparison: > > not (1 <= guess <= 100) > > i.e., guess isn't in the closed interval [1, 100]. > > Anyway, you needn't go out of your way to rewrite the expression using > a chained comparison. The disjunctive expression is actually > implemented more efficiently by CPython's compiler, which you can > verify using the dis module to disassemble the bytecode. I?m not sure what you?re talking about in the above paragraph. From swdunning at cox.net Mon Mar 10 03:05:58 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sun, 9 Mar 2014 19:05:58 -0700 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: <2A3FB6A5-020D-4DE9-8349-D4FCCC930691@cox.net> On Mar 8, 2014, at 7:35 AM, Mark Lawrence wrote: > > I have no interest in the efficiency, only what is easiest for me to read, which in this case is the chained comparison. As a rule of thumb I'd also prefer it to be logically correct :) > What exactly is ment by a chained comparison? Wouldn?t what I wrote be chained? From breamoreboy at yahoo.co.uk Mon Mar 10 10:25:46 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 10 Mar 2014 09:25:46 +0000 Subject: [Tutor] Help with Guess the number script In-Reply-To: <2A3FB6A5-020D-4DE9-8349-D4FCCC930691@cox.net> References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> <2A3FB6A5-020D-4DE9-8349-D4FCCC930691@cox.net> Message-ID: On 10/03/2014 02:05, Scott W Dunning wrote: > > On Mar 8, 2014, at 7:35 AM, Mark Lawrence wrote: >> >> I have no interest in the efficiency, only what is easiest for me to read, which in this case is the chained comparison. As a rule of thumb I'd also prefer it to be logically correct :) >> > What exactly is ment by a chained comparison? Wouldn?t what I wrote be chained? > A chained comparison refers to the fact that the comparison can be written without using and or or, see http://docs.python.org/3/reference/expressions.html, not the if/elif chain. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From breamoreboy at yahoo.co.uk Mon Mar 10 10:29:32 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 10 Mar 2014 09:29:32 +0000 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: On 10/03/2014 02:03, Scott W Dunning wrote: > > On Mar 8, 2014, at 7:29 AM, eryksun wrote: >> Anyway, you needn't go out of your way to rewrite the expression using >> a chained comparison. The disjunctive expression is actually >> implemented more efficiently by CPython's compiler, which you can >> verify using the dis module to disassemble the bytecode. > > I?m not sure what you?re talking about in the above paragraph. > As a newbie don't worry about it (yet). Personally I think it's plain daft to put such advanced language topics on a tutor mailing list. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From eryksun at gmail.com Mon Mar 10 12:15:48 2014 From: eryksun at gmail.com (eryksun) Date: Mon, 10 Mar 2014 07:15:48 -0400 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: On Mon, Mar 10, 2014 at 5:29 AM, Mark Lawrence wrote: > > As a newbie don't worry about it (yet). Personally I think it's plain daft > to put such advanced language topics on a tutor mailing list. Different strokes for different folks. I like to tinker with and disassemble things as I'm learning about them. I would have been ecstatic about open source as a kid. I learn simultaneously from the top down and bottom up -- outside to inside and inside to outside. I need an abstract overview (a map) combined with a concrete realization. Tell me and show me -- and let me tinker and experiment. If learning isn't fun, I'm not learning. The Python language reference, while being far more accessible than an ISO standard or technical report, is still an abstract, highly verbal specification. I understand it, but I don't truly 'grok' a lot of things until I see how it's implemented in bytecode, or even down to the C source level. Putting the two together, I meet in the middle with a better understanding of how it works. From pavan.rikhi at gmail.com Mon Mar 10 10:01:29 2014 From: pavan.rikhi at gmail.com (Pavan Rikhi) Date: Mon, 10 Mar 2014 05:01:29 -0400 Subject: [Tutor] improvements on a renaming script In-Reply-To: <1394392955.5102.92394069.67612DD0@webmail.messagingengine.com> References: <1394392955.5102.92394069.67612DD0@webmail.messagingengine.com> Message-ID: <20140310090129.GB1083@Lucy.acorn> On Sun, Mar 09, 2014 at 03:22:35PM -0400, street.sweeper at mailworks.org wrote: > - In the get_long_names() function, the for/if thing is reading > the whole fileNames.tab file every time, isn't it? In reality, > the file was only a few dozen lines long, so I suppose it doesn't > matter, but is there a better way to do this? Yes, read the file once and build a dictionary mapping the first column to the second column. > - Really, I wanted to create a new sequence number at the end of > each file name, but I thought this would be difficult. In order > for it to count from 01 to whatever the last file is per set p01, > p02, etc, it would have to be aware of the set name and how many > files are in it. So I settled for getting the last 3 digits of > the original file name using splitext(). The strings were unique, > so it worked out. However, I can see this being useful in other > places, so I was wondering if there is a good way to do this. > Is there a term or phrase I can search on? Buckets? You'll need a function to differentiate the files into the desired groups(buckets). You can use that function to generate a dictionary mapping a bucket name to a list of files(the bucket). Iterate over all the files, sorting them into buckets. Then iterate over the buckets, increasing the counter every file, and reseting the counter in between buckets. Here's how I'd do it for your script: def get_bucket_key(filename): prefix = filename.split('_')[0] return prefix def sort_files_into_buckets(file_list): buckets_to_files = {} for filename in file_list: key = get_bucket_key(filename) if key in buckets_to_files: buckets_to_files[key].append(filename) else: buckets_to_files[key] = [filename] return buckets_to_files file_list = os.listdir(...) buckets_to_files = sort_files_into_buckets(file_list) for (bucket_key, bucket_file_list) in buckets_to_files.items(): counter = 1 for file in bucket_file_list: print "{0}_{1}.jpg".format(bucket_key, counter) counter += 1 > - I'd be interested to read any other comments on the code. > I'm new to python and I have only a bit of computer science study, > quite some time ago. You should read PEP8[http://legacy.python.org/dev/peps/pep-0008/] for the basic Python style guide. If you'll be writing things to share or come back to after a while, it would be good to learn about documentation, start by reading PEP257[http://legacy.python.org/dev/peps/pep-0257/]. Note that I've written my own versions alongside my comments. I'm not sure if that's OK on this mailing list, and if you want a spoiler-free version with just the commentary and no code let me know and I'll resend it: > # get longnames from fileNames.tab > def get_long_name(glnAbbrev): Don't be afraid to use longer function/argument names and skip the comment, your code will end up much more readable. Does the "gln" in "glnAbbrev" stand for "get_long_name"? It seems repetitive to include the name of the function in the name of it's parameters. And I think we're passing the function a prefix, not an abbreviation: def get_long_names_from_file(prefix): > with open( > os.path.join(os.path.expanduser('~'),'temp2','fileNames.tab') > ) as filenames: Good, pythonic usage of context managers but it took a second longer to click than splitting it out into 2 lines. Also you should add spaces after each parameter in a function call: filenames_path = os.path.join(os.path.expanduser('~'), 'temp2', 'fileNames.tab') with open(filenames_path) as input_file: > filenamesdata = csv.reader(filenames, delimiter='\t') > for row in filenamesdata: > if row[0] == glnAbbrev: > return row[1] This is where you would build a dictionary. You could skip the csv module and just iterate through the file, splitting each line to get the prefix and long_name. The split() function splits a string into a list of strings. If every line in this file has only 2 columns, we can unpack the list directly into 2 variables. I usually name my dictionary variables "key_to_value": prefix_to_long_name = {} for line in input_file: prefix, long_name = line.split() prefix_to_long_name[prefix] = long_name return prefix_to_long_name This could also be done by dictionary comprehensions: return {prefix: long_name for (prefix, long_name) in (line.split() for line in input_file)} Then just return your finished dictionary. Note that since we return a dictionary instead of searching for a specific prefix, we do not need our "prefix" parameter: def get_long_names_from_file(): But this sounds like we are returning a list of long_names, not a dictionary so I would rename it again to: def get_prefix_to_long_name_from_file() > # find shortname from slice in picture filename > def get_slice(fn): > threeColSlice = fn[1:4] > return threeColSlice I agree that this is overkill but with the suggestions above we can at least make it nicer. Variables should be lower_case_with_underscores: def get_prefix_from_filename(filename): prefix = filename[1:4] return prefix I try to avoid hardcoded splices, so I would opt to split by underscores and keep the leading "p" (at least document the expected filenames somewhere in the script so people understand what those indexes represent): def get_prefix_from_filename(filename): prefix = filename.split('_')[0] return prefix > # get 3-digit sequence number from basename > def get_bn_seq(fn): > seq = os.path.splitext(fn)[0][-3:] > return seq Again you could use better names and a split instead of a splice. The fact that the function uses the basename instead of the full filename is not something that needs to be exposed in the function name: def get_number_from_filename(filename): base_filename = os.path.splitext(filename)[0] number = filename.split('_')[-1] return number I would also write 2 more functions. The first to get paths to the temp2/4/5 folders and prevent code repetition(Don't Repeat Yourself): def get_folder_in_home(folder): folder_path = os.path.join(os.path.expanduser('~'), folder) Then we can change the relevant line in get_long_names_from_file(): folder_path = get_folder_in_home('temp2') filenames_path = os.path.join(folder_path, 'fileNames.tab') The second function would return the new name of a file: def get_new_filename(filename, prefix_to_long_name): prefix = get_prefix_from_filename(filename) long_name = prefix_to_long_name[prefix] number = get_number_from_filename(filename) new_filename = long_name + "_-_" + number + ".jpeg" return new_filename Using String Formatting is safer than concatenation(which would fail if number was an int): new_filename = "{0}_-_{1}.jpeg".format(long_name, number) Now that we're past the definitions we should build our prefix->long_name dictionary: prefix_to_long_name = get_prefix_to_long_name_from_file() > # directory locations > indir = os.path.join(os.path.expanduser('~'),'temp4') > outdir = os.path.join(os.path.expanduser('~'),'temp5') The input and output directories are set and then never change. We can indicate this to the reader by writing the variable in ALL_CAPS: INPUT_DIRECTORY = get_folder_in_home('temp4') OUTPUT_DIRECTORY = get_folder_in_home('temp5') > # rename > for f in os.listdir(indir): > if f.endswith(".jpg"): > os.rename( > os.path.join(indir,f),os.path.join( > outdir, > get_long_name(get_slice(f))+"_-_"+get_bn_seq(f)+".jpeg") > ) I would at least rename "f" to "input_file". We could also use a list comprehension to generate the list and rename in one step: [os.rename(os.path.join(INPUT_DIRECTORY, image_file), os.path.join(OUTPUT_DIRECTORY, get_new_filename(image_file, prefix_to_long_name)) ) for image_file in os.listdir(INPUT_DIRECTORY) if image_file.endswith(".jpg")] Although that's a bit much: for input_file in os.listdir(INPUT_DIRECTORY): if input_file.endswith(".jpg"): input_path = os.path.join(INPUT_DIRECTORY, input_file) new_filename= get_new_filename(input_file, prefix_to_long_name) output_path = os.path.join(OUTPUT_DIRECTORY, new_filename) os.rename(input_path, output_path) Some would also stick all of the top-level scripting into a function called main. You set the main() function to run automatically only if the script is called as a file. It won't execute if imported as a module in another script: if __name__ == '__main__': main() Here's the fully revised script: import os from os.path import join def main(): INPUT_DIRECTORY = get_folder_in_home('temp4') OUTPUT_DIRECTORY = get_folder_in_home('temp5') prefix_to_long_name = get_prefix_to_long_name_from_file() for input_file in os.listdir(INPUT_DIRECTORY): if input_file.endswith(".jpg"): new_filename = get_new_filename(input_file, prefix_to_long_name) input_path = join(INPUT_DIRECTORY, input_file) output_path = join(OUTPUT_DIRECTORY, new_filename) os.rename(input_path, output_path) def get_folder_in_home(folder): folder_path = join(os.path.expanduser('~'), folder) return folder_path def get_prefix_to_long_name_from_file(): prefix_to_long_name = {} filenames_path = join(get_folder_in_home('temp2'), 'fileNames.tab') with open(filenames_path) as input_file: for line in input_file: prefix, long_name = line.split() prefix_to_long_name[prefix] = long_name return prefix_to_long_name def get_prefix_from_filename(filename): prefix = filename.split('_')[0] return prefix def get_number_from_filename(filename): base_filename = os.path.splitext(filename)[0] number = base_filename.split('_')[-1] return number def get_new_filename(filename, prefix_to_long_name): prefix = get_prefix_from_filename(filename) long_name = prefix_to_long_name[prefix] number = get_number_from_filename(filename) new_filename = "{0}_-_{1}.jpeg".format(long_name, number) return new_filename if __name__ == '__main__': main() -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 966 bytes Desc: GnuPG Digital Signature URL: From hind_fathallah at yahoo.com Mon Mar 10 23:25:44 2014 From: hind_fathallah at yahoo.com (hind fathallah) Date: Mon, 10 Mar 2014 15:25:44 -0700 (PDT) Subject: [Tutor] help me In-Reply-To: <1391298010.33542.YahooMailNeo@web162102.mail.bf1.yahoo.com> References: <1391230503.91752.YahooMailNeo@web162106.mail.bf1.yahoo.com> <1391298010.33542.YahooMailNeo@web162102.mail.bf1.yahoo.com> Message-ID: <1394490344.71858.YahooMailNeo@web162103.mail.bf1.yahoo.com> hi I need your help plz with this cods ( I want u to ?tell wht cod I miss to stop the while loop whene I get 3 stars)? rm = [] stars = 0 ##if stars == "3": ## ? ?print " You win" ##else: ## ? ?print "hh" def ask_yes_no(question): ? ? """Ask a yes or no question.""" ? ? answer = None ?? ? ? while answer not in ("y", "n"):? ? ? ? ? answer = raw_input(question).lower() ? ? return answer def congrate_winner(stars = "3"): ? ? print "congradulation you have.", stars, " stars you won!\n" ? ?? ? ? return stars ##def stars(): ## ? ?#stars = 0 ## ? ?global stars ## ? ?stars = stars + 1 ## ? ?print "stars:", stars, "\n" ## ? ## ? ?if stars == "3": ## ? ? ? ?print "congadulation you win" ## ? ?else: ## ? ? ? ?print "Go to the next room" ## ? ?return stars def rest_room(): ? ? restroom = ["shower", "sink"] ? ? print restroom ? ? global stars ? ? ans = ask_yes_no("It does star ther?: ") ? ? print "This is the value of ans.", ans ? ? if ans == "y": ? ? ? ?? ? ? ? ?? ? ? ? ? print "\nOK" ? ? ? ?? ? ? ? ? stars = stars + 1 ? ? ? ? print "Stars:", stars, "\n\n" ? ? ? ? ? ? else: ? ? ? ? print "hmm go to another room." ? ? ? ? print "Stars:", stars, "\n\n" ? ? return ans, restroom def living_room(): ? ? livingroom = ["uyyg", "hfgfd", "star"] ? ? print livingroom ? ? global stars ? ? ans = ask_yes_no("It does star ther?: ") ? ? print "Your answe is.", ans ? ? if ans == "y": ? ? ? ? ? ? ? ? ? print "\nOK" ? ? ? ? stars = stars + 1 ? ? ? ? print "Stars:", stars, "\n\n" ? ? ? ?? ? ? else: ? ? ? ? print "hmm go to another room." ? ? ? ? print "Stars:", stars, "\n\n" ? ? ?? ? ? return ans, livingroom def bed_room(): ? ? bedroom = ["iuyg", "star"] ? ?? ? ? print bedroom ? ? global stars ? ? ans = ask_yes_no("It does star ther?: ") ? ? print "Your answe is.", ans ? ? if ans == "y": ? ? ? ? ? ? ? ? ? print "\nOK" ? ? ? ? stars = stars + 1 ? ? ? ? print "Stars:", stars, "\n\n" ? ? else: ? ? ? ? print "hmm go to another room." ? ? ? ? print "Stars:", stars, "\n\n" ? ? return ans, bedroom def Kichen(): ? ? kichen = ["star", "jyhffd"] ? ? global stars? ? ? print kichen ? ? ans = ask_yes_no("It does star ther?: ") ? ? print "Your answe is.", ans ? ? if ans == "y": ? ? ? ? ? ? ? ? ? print "\nOK" ? ? ? ? stars = stars + 1 ? ? ? ? print "Stars:", stars, "\n\n" ? ? else: ? ? ? ? print "hmm go to another room." ? ? ? ? print "Stars:", stars, "\n\n" ? ? return ans, kichen ? ?? def main(): ? ?print "Wlecome to my house." ? ?rm = None ? ? ? ? ?while rm != stars: ? ? ? ? print\ ? ? ? ? """ ? ? ? ? 0 - Northe ? ? ? ? 1 - South ? ? ? ? 2 - East ? ? ? ? 3 - Weast ? ? ? ? """ ? ? ? ? rm = raw_input("What room you want to go?: ") ? ? ?? ? ?? ? ? ? ? if rm == "0": ? ? ? ? ? ? rest_room() ? ? ? ? elif rm == "1": ? ? ? ? ? ? living_room() ? ? ? ? elif rm == "2": ? ? ? ? ? ? bed_room() ? ? ? ? elif rm == "3": ? ? ? ? ? ?Kichen() ? ? ? ? ? ? ?? ##if stars == "3": ## ? ?congrate_winner() ? ? ? ? ? ?? main() raw_input("\nPress the enter key to exit.")? On Saturday, February 1, 2014 6:40 PM, hind fathallah wrote: thank you so much because I got it :)? On Saturday, February 1, 2014 1:28 PM, Danny Yoo wrote: On Fri, Jan 31, 2014 at 8:55 PM, hind fathallah wrote: > hi can you answer this question for me plz [question omitted] Many of us probably could answer this. But this is not a homework-answering mailing list.? The problem itself is not interesting to us.? What is interesting is why the problem is giving you trouble.? We'd rather focus on where you are having difficulty: we'd rather help *you*. Tell us what you've tried, where you're getting stuck, what other kinds of problems you've done that are similar to this one.? That is, show us what general problem solving strategies you're using now. Maybe some of those strategies are not working for you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Tue Mar 11 00:11:21 2014 From: davea at davea.name (Dave Angel) Date: Mon, 10 Mar 2014 19:11:21 -0400 (EDT) Subject: [Tutor] help me References: <1391230503.91752.YahooMailNeo@web162106.mail.bf1.yahoo.com> <1391298010.33542.YahooMailNeo@web162102.mail.bf1.yahoo.com> <1394490344.71858.YahooMailNeo@web162103.mail.bf1.yahoo.com> Message-ID: hind fathallah Wrote in message: > > > while rm != stars: ?? ?? ?? ?? print\ ?? ?? ?? ?? """ ?? ?? ?? ?? 0 - Northe ?? ?? ?? ?? 1 - South ?? ?? ?? ?? 2 - East ?? ?? ?? ?? 3 - Weast ?? ?? ?? ?? """ ?? ?? ?? ?? rm = raw_input("What room you want to go?: ") Why are you looping till he gets to the weast room? Why not loop till stars reaches 3? -- DaveA From __peter__ at web.de Tue Mar 11 00:45:56 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Mar 2014 00:45:56 +0100 Subject: [Tutor] help me References: <1391230503.91752.YahooMailNeo@web162106.mail.bf1.yahoo.com> <1391298010.33542.YahooMailNeo@web162102.mail.bf1.yahoo.com> <1394490344.71858.YahooMailNeo@web162103.mail.bf1.yahoo.com> Message-ID: hind fathallah wrote: > hi I need your help plz with this cods ( I want u to tell wht cod I miss > to stop the while loop whene I get 3 stars) rm = [] I think you are comparing a string and an integer. That gives False even if the values look the same: >>> i = 3 >>> s = "3" >>> print i, s 3 3 >>> i == s False Use repr() debug the problem: >>> print repr(i), repr(s) 3 '3' From swdunning at cox.net Tue Mar 11 03:01:42 2014 From: swdunning at cox.net (Scott W Dunning) Date: Mon, 10 Mar 2014 19:01:42 -0700 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: <2F34AA75-07F8-47EA-9777-5612A5CED70F@cox.net> On Mar 10, 2014, at 4:15 AM, eryksun wrote: > > Different strokes for different folks. I like to tinker with and > disassemble things as I'm learning about them. I would have been > ecstatic about open source as a kid. I learn simultaneously from the > top down and bottom up -- outside to inside and inside to outside. I > need an abstract overview (a map) combined with a concrete > realization. Tell me and show me -- and let me tinker and experiment. > If learning isn't fun, I'm not learning. I agree I learn the same way. I just didn?t understand what you were saying. What exactly is Cpython? Is it different from the python I?m using? Also, what did you mean by; >> The disjunctive expression is actually >> implemented more efficiently by CPython's compiler, which you can >> verify using the dis module to disassemble the bytecode. From ben+python at benfinney.id.au Tue Mar 11 04:52:14 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 11 Mar 2014 14:52:14 +1100 Subject: [Tutor] Python implementations (was: Help with Guess the number script) References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> <2F34AA75-07F8-47EA-9777-5612A5CED70F@cox.net> Message-ID: <85pplttms1.fsf_-_@benfinney.id.au> Scott W Dunning writes: > What exactly is Cpython? Python is a language, with numerous implementations. CPython is one of those implementations. See for an overview. > Is it different from the python I?m using? I don't know; how did you acquire the Python implementation you're using now? What does the Python interactive prompt display when you first launch an interactive Python shell? Note that the answer is likely to be ?Yes, you are using some version of CPython? since that is the most common implementation. -- \ ?There are no significant bugs in our released software that | `\ any significant number of users want fixed.? ?Bill Gates, | _o__) 1995-10-23 | Ben Finney From swdunning at cox.net Tue Mar 11 05:07:43 2014 From: swdunning at cox.net (Scott W Dunning) Date: Mon, 10 Mar 2014 21:07:43 -0700 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: >> On Mar 8, 2014, at 3:57 AM, spir wrote: >>> >>> Well done. >>> And now that you have the right set of tests you can >>> half the number of lines by combining your if >>> conditions again, like you had in the original >>> post. ie. Bring your hot/cold/warm tests together. So below is what I finally came up with that works. I?m trying to condense it to half the number of lines like Denis suggested. I was hoping to clarify a couple things if you guys don?t mind?. I wanna make sure I understand how this code is working. So, from what I gather it first checks to see if the ?guess? is out of range and if that is false it continues to the next ?if? statement checking wether it?s too low. Now this is where I?m not 100% sure if the too low ?if? statement is false does it skip everything that is nested below it (you are cold, warm, on fire) and go to the ?if statement checking if it?s too high? And now say the too low ?if? statement is true, because it?s an ?if? the code does not stop it continues but when it gets to the elif the code stops? def print_hints(secret, guess): if guess < 1 or guess > 100: print print "Out of range!" print if guess < secret: print print "Too low!" if guess < secret - 10: print "You are cold!" print print "Sorry please try again." print print elif guess < secret - 5: print "You are warmer!" print print "Sorry please try again." print print else: print "You're on fire!!" print print "Sorry please try again." print print if guess > secret: print print "Too high!" if guess > secret + 10: print "You are cold!" print print "Sorry please try again." print print elif guess > secret + 5: print "You are warmer!" print print "Sorry please try again." print print else: print "You're on fire!!" print print "Sorry please try again." print print This is what I have right now, obviously it?s not working. I?ve been playing around with it but I?m just not seeing where I?m going wrong. Any suggestions are greatly appreciated! def print_hints(secret, guess): if guess < 1 or guess > 100: print print "Out of range!" print if guess < secret: print print "Too low!" if guess > secret: print print "Too high!" if guess < secret - 10 or guess > secret - 10: print "You are cold!" print print "Sorry please try again." print print elif guess < secret - 5 or guess > secret - 5: print "You are warmer!" print print "Sorry please try again." print print else: print "You're on fire!!" print print "Sorry please try again." print print -------------- next part -------------- An HTML attachment was scrubbed... URL: From swdunning at cox.net Tue Mar 11 05:09:00 2014 From: swdunning at cox.net (Scott W Dunning) Date: Mon, 10 Mar 2014 21:09:00 -0700 Subject: [Tutor] Python implementations (was: Help with Guess the number script) In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> <2F34AA75-07F8-47EA-9777-5612A5CED70F@cox.net> Message-ID: <3727514F-096C-42B7-9E5E-6C2A550CCF7F@cox.net> On Mar 10, 2014, at 8:52 PM, Ben Finney wrote: > > What does the Python interactive prompt display when you first launch an > interactive Python shell? Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "copyright", "credits" or "license()" for more information. From swdunning at cox.net Tue Mar 11 05:09:00 2014 From: swdunning at cox.net (Scott W Dunning) Date: Mon, 10 Mar 2014 21:09:00 -0700 Subject: [Tutor] Python implementations (was: Help with Guess the number script) In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> <2F34AA75-07F8-47EA-9777-5612A5CED70F@cox.net> Message-ID: <3EFBF4A7-629A-4CAD-8CFA-112C628087DA@cox.net> On Mar 10, 2014, at 8:52 PM, Ben Finney wrote: > > What does the Python interactive prompt display when you first launch an > interactive Python shell? Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "copyright", "credits" or "license()" for more information. From ben+python at benfinney.id.au Tue Mar 11 05:16:01 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 11 Mar 2014 15:16:01 +1100 Subject: [Tutor] Python implementations References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> <2F34AA75-07F8-47EA-9777-5612A5CED70F@cox.net> <3727514F-096C-42B7-9E5E-6C2A550CCF7F@cox.net> Message-ID: <85ha75tloe.fsf@benfinney.id.au> Scott W Dunning writes: > On Mar 10, 2014, at 8:52 PM, Ben Finney wrote: > > > > What does the Python interactive prompt display when you first launch an > > interactive Python shell? > > Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54) > [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin > Type "copyright", "credits" or "license()" for more information. Thanks. Yes, the clue is in the ?[GCC ?]?, which tells us the program was built using that version of GCC, the GNU Compiler Collection. This means it is implemented in the C programming language and is thus CPython. Because Python implementations all follow the Python language specification, this doesn't imply anything much for you as a user. Regardless of which implementation you're using, you're still using Python and have access to everything the documentation describes. This is useful to know, though, when you learn about some of the more peripheral capabilities present in one but not other implementations. But all that can wait. -- \ ?I like my dental hygenist, I think she's very pretty; so when | `\ I go to have my teeth cleaned, while I'm in the waiting room I | _o__) eat an entire box of cookies.? ?Steven Wright | Ben Finney From swdunning at cox.net Tue Mar 11 04:32:46 2014 From: swdunning at cox.net (Scott W Dunning) Date: Mon, 10 Mar 2014 20:32:46 -0700 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: <34B77B35-D7A9-4488-BE68-0A23039E28C8@cox.net> On Mar 8, 2014, at 11:50 AM, Scott dunning wrote: >>> >>> And now that you have the right set of tests you can >>> half the number of lines by combining your if >>> conditions again, like you had in the original >>> post. ie. Bring your hot/cold/warm tests together. I?m having a hard time doing that because the guess can be either too low or too high but it is always either cold, warm, or on fire. I can?t figure out how to make it work with out splitting the cold, warm and on fire under two branches, one too low and one too high. Any suggestions? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Tue Mar 11 07:18:51 2014 From: davea at davea.name (Dave Angel) Date: Tue, 11 Mar 2014 02:18:51 -0400 (EDT) Subject: [Tutor] Help with Guess the number script References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: Scott W Dunning Wrote in message: > Would you please stop posting in html? > def print_hints(secret, guess): ?? ?? if guess < 1 or guess > 100: ?? ?? ?? ?? print ?? ?? ?? ?? print "Out of range!" ?? ?? ?? ?? print ?? ?? if guess < secret: ?? ?? ?? ?? print ?? ?? ?? ?? print "Too low!" ?? ?? if guess > secret: ?? ?? ?? ?? print ?? ?? ?? ?? print "Too high!" ?? ?? if guess < secret - 10 or guess > secret - 10: Think about that line. You might even want to put in a separate function to test what it does. HINT: it's wrong. ?? ?? ?? ?? print "You are cold!" ?? ?? ?? ?? print ?? ?? ?? ?? print "Sorry please try again." ?? ?? ?? ?? print ?? ?? ?? ?? print ?? ?? elif guess < secret - 5 or guess > secret - 5: Same mistake. ?? ?? ?? ?? print "You are warmer!" ?? ?? ?? ?? print ?? ?? ?? ?? print "Sorry please try again." ?? ?? ?? ?? print ?? ?? ?? ?? print ?? ?? else: ?? ?? ?? ?? print "You're on fire!!" ?? ?? ?? ?? print ?? ?? ?? ?? print "Sorry please try again." ?? ?? ?? ?? print ?? ?? ?? ?? print -- DaveA From swdunning at cox.net Tue Mar 11 08:34:23 2014 From: swdunning at cox.net (Scott W Dunning) Date: Tue, 11 Mar 2014 00:34:23 -0700 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: <71C28243-537A-488B-A1E3-1C7144146A46@cox.net> On Mar 10, 2014, at 11:18 PM, Dave Angel wrote: > Scott W Dunning Wrote in message: >> > > Would you please stop posting in html? I don?t know what you mean? I just use the text for my email provider. It?s not html? I types up the code I had in the script. -------------- next part -------------- An HTML attachment was scrubbed... URL: From swdunning at cox.net Tue Mar 11 08:42:19 2014 From: swdunning at cox.net (Scott W Dunning) Date: Tue, 11 Mar 2014 00:42:19 -0700 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: <1573BAF6-8102-4FD3-B667-A32519741EE2@cox.net> On Mar 10, 2014, at 11:18 PM, Dave Angel wrote: Where are you guys using the forum? Through google? I was using that at first but someone complained about something that google does and told me to get it through my email. That?s what I?m doing now and I get bombarded with about 500 emails a day but I?m still doing something wrong? I?d rather go though a site to view the forum anyways, it seems way easier then having to sort through hundreds of emails. I?m not trying to be rude I?m just wondering, I don?t want to be irritating people if by doing something wrong. Thanks again for all of your help! From alan.gauld at btinternet.com Tue Mar 11 09:49:47 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Mar 2014 08:49:47 +0000 Subject: [Tutor] Help with Guess the number script In-Reply-To: <1573BAF6-8102-4FD3-B667-A32519741EE2@cox.net> References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> <1573BAF6-8102-4FD3-B667-A32519741EE2@cox.net> Message-ID: On 11/03/14 07:42, Scott W Dunning wrote: > > On Mar 10, 2014, at 11:18 PM, Dave Angel wrote: > > Where are you guys using the forum? Personally I use the news feed from Gmane.org I read it in Thunderbird (or occasionally via a newsreader on my smartphone/tablet). You can also read it online in a browser if you must. > ...someone complained about something that google does > and told me to get it through my email. Its possible to get Google to behave properly but it seems like its usually easier to switch to a mail tool... :-( > That?s what I?m doing now and I get bombarded > with about 500 emails a day Not from the tutor list though. It only has a few mails normally - less than 50 most days. But you should be abler to set up auto filtering rules on your mail tool to route all the tutor mails into a separate folder for reading later. Also if you turn on threading in your mail tool for that folder you'll get them grouped by subject. > I?d rather go though a site to view the forum > anyways, I can never understand why people like web forums, they are so limited in functionality. But if you must go that way try the gmane feed. Tutor is in (with a zillion other Python lists) under comp.python.tutor. > it seems way easier then having to sort through > hundreds of emails. See the comments above, also consider digest mode. > I?m not trying to be rude I?m just wondering, It's ok, everyone is allowed preferences. :-) What tends to irritate folks is the HTML content which different readers display differently. Especially the indentation which often gets lost. You need to explicitly go into your mail tool options and select "plain text" rather than "rich text" or "HTML" which will likely be the default. You can often tell if you don't have plain text because you will have options to change font, size, colour etc. You can't do any of that with plain text. But modern mail tools often make it very difficult to set plain text, especially web based ones. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Tue Mar 11 09:57:08 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Mar 2014 08:57:08 +0000 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: On 11/03/14 04:07, Scott W Dunning wrote: >>> On Mar 8, 2014, at 3:57 AM, spir >> > wrote: >>>> And now that you have the right set of tests you can >>>> half the number of lines by combining your if >>>> conditions again, like you had in the original >>>> post. ie. Bring your hot/cold/warm tests together. I think that was me rather than Denis, but that's irrelevant... > This is what I have right now, obviously it?s not working. I?ve been > playing around with it but I?m just not seeing where I?m going wrong. > Any suggestions are greatly appreciated! > > def print_hints(secret, guess): > if guess < 1 or guess > 100: > print > print "Out of range!" > print > if guess < secret: > print > print "Too low!" > if guess > secret: > print > print "Too high!" OK so far, you don't need all the print statements but that's just a style issue. (You could just insert '\n' characters instead.) > if guess < secret - 10 or guess > secret - 10: This is the right idea for cutting the line count but you have the comparison values wrong. Look back to earlier emails, you are repeating the same error as before. Manually think through what happens in the line above if guess == secret. And then once you get that fixed you can rewrite using the chained comparison trick to tidy it up. ie if not (lower limit < guess > upper limit): HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Tue Mar 11 14:06:47 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Mar 2014 14:06:47 +0100 Subject: [Tutor] educational References: Message-ID: MICHAEL BASHAGI wrote: [Please send your posts to the mailing list, not individual posters. Thank you.] > But the PIL doesn't work in my version of Python, i use Python 3.4 If you are still working on this: as Tim hinted there is a fork of PIL called Pillow with installers for Python 3.4. See https://pypi.python.org/pypi/Pillow/2.3.0 From denis.spir at gmail.com Tue Mar 11 14:12:43 2014 From: denis.spir at gmail.com (spir) Date: Tue, 11 Mar 2014 14:12:43 +0100 Subject: [Tutor] Help with Guess the number script In-Reply-To: <34B77B35-D7A9-4488-BE68-0A23039E28C8@cox.net> References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> <34B77B35-D7A9-4488-BE68-0A23039E28C8@cox.net> Message-ID: <531F0BCB.8030509@gmail.com> On 03/11/2014 04:32 AM, Scott W Dunning wrote: > > On Mar 8, 2014, at 11:50 AM, Scott dunning wrote: >>>> >>>> And now that you have the right set of tests you can >>>> half the number of lines by combining your if >>>> conditions again, like you had in the original >>>> post. ie. Bring your hot/cold/warm tests together. > I?m having a hard time doing that because the guess can be either too low or too high but it is always either cold, warm, or on fire. I can?t figure out how to make it work with out splitting the cold, warm and on fire under two branches, one too low and one too high. Any suggestions? Well, what is the meaning of "absolute value"? Cold, warm, or on fire depend on the distance between both numbers, secret and guess, right? d From alan.gauld at btinternet.com Tue Mar 11 14:32:24 2014 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 11 Mar 2014 13:32:24 +0000 (GMT) Subject: [Tutor] c++ on python In-Reply-To: References: Message-ID: <1394544744.31838.YahooMailNeo@web186003.mail.ir2.yahoo.com> CC'ing the list Please use ReplyAll when responding. ? >________________________________ > From: Gabriele Brambilla >To: Alan Gauld >Sent: Tuesday, 11 March 2014, 12:54 >Subject: Re: [Tutor] c++ on python > > > >I think (because I've not received the code yet) I will receive the source code (.c or .cpp file)? >and I want to compile it in the way to use it and maybe make small changes. So I think I want? >to embed the code as a Python module (but it's not properly a library). > >What is your experience level with C/C++? Are you familiar with building C/C++ libraries or even object files? There are documents and tools to help you turn C code into Python libraries? but that's really outside the scope of the tutor list. About the dependencies I am not so sure as before. >So I mistaken the list? which one is the right one?? >I suspect you may want a different list. But you will need to be clear about what you are? trying to do. It's still not clear what exactly this source code will be.? Is it a library or a program? Do you think is it better that I install a C compiler and I don't use python? I use Anaconda... >You will need a C compiler regardless, if you receive C source code.? Python cannot work with C in source format, only after it is compiled. But that does not mean you can't use Python to work with it, and that is? probably easier than trying to write your whole application in? C++ - especially if you are not already fluent in C++. I've no experience of Anaconda but it looks like it might be hard to find an equivalent? in the C++ world, especially if you have already written a lot of Python/Anaconda code. Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at gmail.com Tue Mar 11 14:32:38 2014 From: denis.spir at gmail.com (spir) Date: Tue, 11 Mar 2014 14:32:38 +0100 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: <531F1076.6080805@gmail.com> On 03/11/2014 09:57 AM, Alan Gauld wrote: > On 11/03/14 04:07, Scott W Dunning wrote: >>>> On Mar 8, 2014, at 3:57 AM, spir >>> > wrote: >>>>> And now that you have the right set of tests you can >>>>> half the number of lines by combining your if >>>>> conditions again, like you had in the original >>>>> post. ie. Bring your hot/cold/warm tests together. > > I think that was me rather than Denis, but that's > irrelevant... You are right! d From denis.spir at gmail.com Tue Mar 11 14:31:54 2014 From: denis.spir at gmail.com (spir) Date: Tue, 11 Mar 2014 14:31:54 +0100 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: <531F104A.5090308@gmail.com> On 03/11/2014 05:07 AM, Scott W Dunning wrote: >>> On Mar 8, 2014, at 3:57 AM, spir wrote: >>>> >>>> Well done. >>>> And now that you have the right set of tests you can >>>> half the number of lines by combining your if >>>> conditions again, like you had in the original >>>> post. ie. Bring your hot/cold/warm tests together. > > So below is what I finally came up with that works. I?m trying to condense it to half the number of lines like Denis suggested. I was hoping to clarify a couple things if you guys don?t mind?. > > I wanna make sure I understand how this code is working. So, from what I gather it first checks to see if the ?guess? is out of range and if that is false it continues to the next ?if? statement checking wether it?s too low. Now this is where I?m not 100% sure if the too low ?if? statement is false does it skip everything that is nested below it (you are cold, warm, on fire) and go to the ?if statement checking if it?s too high? And now say the too low ?if? statement is true, because it?s an ?if? the code does not stop it continues but when it gets to the elif the code stops? > def print_hints(secret, guess): > if guess < 1 or guess > 100: > print > print "Out of range!" > print I think here if the condition is true, you could just quit the function (return), no? The rest does not make much sense, I guess... > if guess < secret: > print > print "Too low!" > if guess < secret - 10: > print "You are cold!" > print > print "Sorry please try again." > print > print > elif guess < secret - 5: > print "You are warmer!" > print > print "Sorry please try again." > print > print > else: > print "You're on fire!!" > print > print "Sorry please try again." > print > print > if guess > secret: > print > print "Too high!" > if guess > secret + 10: > print "You are cold!" > print > print "Sorry please try again." > print > print > elif guess > secret + 5: > print "You are warmer!" > print > print "Sorry please try again." > print > print > else: > print "You're on fire!!" > print > print "Sorry please try again." > print > print > > This is what I have right now, obviously it?s not working. I?ve been playing around with it but I?m just not seeing where I?m going wrong. Any suggestions are greatly appreciated! > > def print_hints(secret, guess): > if guess < 1 or guess > 100: > print > print "Out of range!" > print > if guess < secret: > print > print "Too low!" > if guess > secret: > print > print "Too high!" > if guess < secret - 10 or guess > secret - 10: > print "You are cold!" > print > print "Sorry please try again." > print > print > elif guess < secret - 5 or guess > secret - 5: > print "You are warmer!" > print > print "Sorry please try again." > print > print > else: > print "You're on fire!!" > print > print "Sorry please try again." > print > print Below, the "temperature" hint and low/high hint are logically independant. The first one depends on the distance between secret and guess numbers, the second one depends on their relative values (greater/smaller). And the second hint (low/high) only makes sense iff the player did not win, meaning iff not "on fire!". However, both are related to the difference. Conceptually, after having passed the test out-of-range, I would start with something like: diff = guess - secret # (we know guess is in range) # temperature hint dist = abs(diff) if dist == 0: ... on fire! return elif dist < 5: ... # (we know secret was not found) # high/low hint neg = diff < 0 ... As an exercise, you could write each kind of hint in a separate tool func, and call each one only when relevant. Denis From gb.gabrielebrambilla at gmail.com Tue Mar 11 15:27:57 2014 From: gb.gabrielebrambilla at gmail.com (Gabriele Brambilla) Date: Tue, 11 Mar 2014 10:27:57 -0400 Subject: [Tutor] c++ on python In-Reply-To: <1394544744.31838.YahooMailNeo@web186003.mail.ir2.yahoo.com> References: <1394544744.31838.YahooMailNeo@web186003.mail.ir2.yahoo.com> Message-ID: I answer in the text 2014-03-11 9:32 GMT-04:00 ALAN GAULD : > CC'ing the list > Please use ReplyAll when responding. > > > ------------------------------ > *From:* Gabriele Brambilla > *To:* Alan Gauld > *Sent:* Tuesday, 11 March 2014, 12:54 > *Subject:* Re: [Tutor] c++ on python > > I think (because I've not received the code yet) I will receive the source > code (.c or .cpp file) > and I want to compile it in the way to use it and maybe make small > changes. So I think I want > to embed the code as a Python module (but it's not properly a library). > > What is your experience level with C/C++? > Are you familiar with building C/C++ libraries or even object files? > I know C/C++, I am not able to do everything but I think that I can compile a simple programm with object files and libraries > There are documents and tools to help you turn C code into Python > libraries > but that's really outside the scope of the tutor list. > > About the dependencies I am not so sure as before. > So I mistaken the list? which one is the right one? > > I suspect you may want a different list. But you will need to be clear > about what you are > trying to do. It's still not clear what exactly this source code will be. > Is it a library or a program? > A program. it should use only standard C++ libraries. > Do you think is it better that I install a C compiler and I don't use > python? I use Anaconda... > > You will need a C compiler regardless, if you receive C source code. > Python cannot work with C in source format, only after it is compiled. > But that does not mean you can't use Python to work with it, and that is > probably easier than trying to write your whole application in > C++ - especially if you are not already fluent in C++. > Yes I would prefer to use Python as much as possible. What do you mean about using Python to work with it? How do you usually do? I've no experience of Anaconda but it looks like it might be hard to find > an equivalent > in the C++ world, especially if you have already written a lot of > Python/Anaconda code. > > Alan Gauld > Author of the Learn To Program website > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > Thanks Gabriele -------------- next part -------------- An HTML attachment was scrubbed... URL: From a.bull at pubdmgroup.com Tue Mar 11 19:39:59 2014 From: a.bull at pubdmgroup.com (Al Bull) Date: Tue, 11 Mar 2014 13:39:59 -0500 Subject: [Tutor] Trying to read dBase files Message-ID: <00ea01cf3d59$4fd2ea40$ef78bec0$@pubdmgroup.com> Greetings. I'm new to python and want to use it to create an application to read one or more dbase files, manipulate some data, and create a new file. I am using Python 3.3. I did some google searches and found something called dbfpy to read dbase, so I downloaded and installed it. The examples show..... >From dbfpy import dbf When I do this I get the following error: >>> from dbfpy import dbf Traceback (most recent call last): File "", line 1, in from dbfpy import dbf File "C:\Python33\lib\site-packages\dbfpy\dbf.py", line 260 print repr(_rec) ^ SyntaxError: invalid syntax My assumption is that this module is written for an earlier release of Python? Some other google searches suggested using microsofts ODBC drivers for dBase, so I downloaded and installed pyodbc and got this: Python 3.3.4 (v3.3.4:7ff62415e426, Feb 10 2014, 18:12:08) [MSC v.1600 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import pyodbc >>> cnxn = pyodbc.connect('DRIVER={Microsoft Access dBASE Driver};SERVER=localhost;DATABASE={Q:\TWS\MAILMERGE\BIL00008.DBF}') Traceback (most recent call last): File "", line 1, in cnxn = pyodbc.connect('DRIVER={Microsoft Access dBASE Driver};SERVER=localhost;DATABASE=Q:\TWS\MAILMERGE\BIL00008.DBF') pyodbc.Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') Do I have the driver name incorrect? Al Bull From alan.gauld at btinternet.com Tue Mar 11 20:18:54 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Mar 2014 19:18:54 +0000 Subject: [Tutor] Trying to read dBase files In-Reply-To: <00ea01cf3d59$4fd2ea40$ef78bec0$@pubdmgroup.com> References: <00ea01cf3d59$4fd2ea40$ef78bec0$@pubdmgroup.com> Message-ID: On 11/03/14 18:39, Al Bull wrote: > I'm new to python and want to use it to create an application to read one or > more dbase files, manipulate some data, and create a new file. You could also try the Dabo project, it is an IDE for building DBase like apps. I think it supports reading Foxpro(aka DBASE) files. > I am using Python 3.3. I did some google searches and found something > called dbfpy to read dbase, so I downloaded and installed it. > > File "C:\Python33\lib\site-packages\dbfpy\dbf.py", line 260 > print repr(_rec) > ^ > SyntaxError: invalid syntax You are using Python 3.3 so print is a function. You need to use print( repr(_rec) ) > My assumption is that this module is written for an earlier release of > Python? That may be true too, but your problem is in the print line. > Some other google searches suggested using microsofts ODBC drivers for > dBase, so I downloaded and installed pyodbc and got this: Yes thats possible too if you are on a Windows platform. > Python 3.3.4 (v3.3.4:7ff62415e426, Feb 10 2014, 18:12:08) [MSC v.1600 32 bit > (Intel)] on win32 > Type "copyright", "credits" or "license()" for more information. >>>> import pyodbc >>>> cnxn = pyodbc.connect('DRIVER={Microsoft Access dBASE > Driver};SERVER=localhost;DATABASE={Q:\TWS\MAILMERGE\BIL00008.DBF}') > Traceback (most recent call last): > ... > Do I have the driver name incorrect? Sorry can't help with that one! HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From davea at davea.name Tue Mar 11 21:09:21 2014 From: davea at davea.name (Dave Angel) Date: Tue, 11 Mar 2014 16:09:21 -0400 (EDT) Subject: [Tutor] Trying to read dBase files References: <00ea01cf3d59$4fd2ea40$ef78bec0$@pubdmgroup.com> Message-ID: Alan Gauld Wrote in message: > On 11/03/14 18:39, Al Bull wrote: > > > >> I am using Python 3.3. I did some google searches and found something >> called dbfpy to read dbase, so I downloaded and installed it. >> >> File "C:\Python33\lib\site-packages\dbfpy\dbf.py", line 260 >> print repr(_rec) >> ^ >> SyntaxError: invalid syntax > > You are using Python 3.3 so print is a function. > You need to use > > print( repr(_rec) ) > >> My assumption is that this module is written for an earlier release of >> Python? > > That may be true too, but your problem is in the print line. Which is in the dbfpy code. -- DaveA From swdunning at cox.net Wed Mar 12 01:06:51 2014 From: swdunning at cox.net (Scott W Dunning) Date: Tue, 11 Mar 2014 17:06:51 -0700 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> <1573BAF6-8102-4FD3-B667-A32519741EE2@cox.net> Message-ID: On Mar 11, 2014, at 1:49 AM, Alan Gauld wrote: > > Not from the tutor list though. It only has a few > mails normally - less than 50 most days. > Actually now that you say that most of the emails are coming through the reg python-lists, not the tutor section. I guess I should just unsubscribe from python-lists because my questions are going through the tutor section for awhile. >> I?m not trying to be rude I?m just wondering, > > What tends to irritate folks is the HTML content > which different readers display differently. > Especially the indentation which often gets lost. > You need to explicitly go into your mail tool > options and select "plain text" rather than > "rich text" or "HTML" which will likely be the > default. > > You can often tell if you don't have plain text > because you will have options to change font, > size, colour etc. You can't do any of that with > plain text. But modern mail tools often make it > very difficult to set plain text, especially > web based ones. > Yeah, I had no idea that my messages were coming through in HTML, nor what it looked like until someone sent me a section showing me what it looked like, I can see how that would be frustrating. I?m using the mail app on my macbook pro, any suggestions on how to stop it from going out as html? Do I need to change the font? Also, I think last time I sent a section of my code I copy and pasted it from my script, could that be the problem? Thanks again! From wrw at mac.com Wed Mar 12 03:50:24 2014 From: wrw at mac.com (William Ray Wing) Date: Tue, 11 Mar 2014 22:50:24 -0400 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> <1573BAF6-8102-4FD3-B667-A32519741EE2@cox.net> Message-ID: <1E27DC61-86B6-489E-961D-B89DBBF06B2A@mac.com> On Mar 11, 2014, at 8:06 PM, Scott W Dunning wrote: [mega byte] >> > Yeah, I had no idea that my messages were coming through in HTML, nor what it looked like until someone sent me a section showing me what it looked like, I can see how that would be frustrating. > > I?m using the mail app on my macbook pro, any suggestions on how to stop it from going out as html? Do I need to change the font? Also, I think last time I sent a section of my code I copy and pasted it from my script, could that be the problem? > > Thanks again! Simple. In Mail Preferences -> Composing -> Message Format -> Plain Text (Your setting is probably currently Rich Text.) -Bill From scott.w.d at cox.net Wed Mar 12 07:29:40 2014 From: scott.w.d at cox.net (Scott W Dunning) Date: Tue, 11 Mar 2014 23:29:40 -0700 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> <1573BAF6-8102-4FD3-B667-A32519741EE2@cox.net> Message-ID: On Mar 11, 2014, at 7:50 PM, William Ray Wing wrote: > > Simple. In Mail Preferences -> Composing -> Message Format -> Plain Text (Your setting is probably currently Rich Text.) > Got it, hopefully that helps. From swdunning at me.com Wed Mar 12 05:13:58 2014 From: swdunning at me.com (Scott Dunning) Date: Tue, 11 Mar 2014 21:13:58 -0700 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: On Mar 11, 2014, at 1:57 AM, Alan Gauld wrote: > OK so far, you don't need all the print statements > but that's just a style issue. (You could just > insert '\n' characters instead.) You?re right, I?m actually not sure why I did it that way. > >> if guess < secret - 10 or guess > secret - 10: > > This is the right idea for cutting the line count but you > have the comparison values wrong. Look back to earlier > emails, you are repeating the same error as before. > Manually think through what happens in the line above > if guess == secret. Oh, do you mean it should be <= and >=?? I?m not sure why that would work, because if guess==secret I have another statement in my code that takes care of that. I didn?t want to add my whole code because it?s too long but that is in there. > > And then once you get that fixed you can rewrite using > the chained comparison trick to tidy it up. > ie > if not (lower limit < guess > upper limit): I see what you?re saying about the chained comparison. What I?m having problems with is condensing it to half the lines of code so I don?t have to have the same conditionals under both ?too low? and ?to high?. If that makes sense. > > From swdunning at me.com Wed Mar 12 08:19:31 2014 From: swdunning at me.com (Scott Dunning) Date: Wed, 12 Mar 2014 00:19:31 -0700 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: On Mar 10, 2014, at 11:18 PM, Dave Angel wrote: > if guess < secret - 10 or guess > secret - 10: > > Think about that line. You might even want to put in a separate > function to test what it does. > HINT: it's wrong. > Got it! I realized what I was doing wrong. I needed that plus sign for the too high part of it and what you said helped me figure it out! Thanks Dave, all you actually! From yannisphone at gmail.com Tue Mar 11 14:53:48 2014 From: yannisphone at gmail.com (Yanni Phone) Date: Tue, 11 Mar 2014 08:53:48 -0500 Subject: [Tutor] Loop Issue Message-ID: Hello all, I was following along in a book called 'Python Programming for the Absolute Beginner' by Michael Dawson and I ran into an odd problem with a loop. Dawson has the following code in his book: health = 10 trolls = 0 damage = 3 while health != 0: trolls += 1 health -= damage This seems simple enough. (This is an example of a non-terminating loop, by the way, so it is not suppose to work correctly.) My problem is that when I enter this into IDLE, and hot enter a few times. I never get my prompt (>>>) back. It just lets me hot enter a bunch of time as though it is expecting more input from me. I tried making a similar loop and it gave me my prompt back just fine. Does anyone know what might be going on here? Thanks, Yanni -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Mar 12 10:11:03 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 12 Mar 2014 09:11:03 +0000 Subject: [Tutor] c++ on python In-Reply-To: References: <1394544744.31838.YahooMailNeo@web186003.mail.ir2.yahoo.com> Message-ID: On 11/03/14 14:27, Gabriele Brambilla wrote: > Is it a library or a program? > > A program. it should use only standard C++ libraries. OK, If it's a program, that is, it compiles into an executable that you can run then you can run it from within Python using the subprocess module. Do you know how you interact with it? Can you give it start up arguments? Does it read from stdin? Does it write to stdout? Does it read a data file? Does it write a file out? You will need to know that to be able to use the program from inside Python. > What do you mean about using Python to work with it? > How do you usually do? I mean running the C++ program and exchanging data with it. That's what subprocess allows you to do. If it were a library then you would have to call the individual C++ functions directly using something like ctypes, which is usually more complex. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Wed Mar 12 10:13:14 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 12 Mar 2014 09:13:14 +0000 Subject: [Tutor] Trying to read dBase files In-Reply-To: References: <00ea01cf3d59$4fd2ea40$ef78bec0$@pubdmgroup.com> Message-ID: On 11/03/14 20:09, Dave Angel wrote: > Alan Gauld Wrote in message: >>> I am using Python 3.3. I did some google searches and found something >>> called dbfpy to read dbase, so I downloaded and installed it. >>> >>> File "C:\Python33\lib\site-packages\dbfpy\dbf.py", line 260 >>> print repr(_rec) >>> ^ >>> SyntaxError: invalid syntax >> > > Which is in the dbfpy code. Oops, good catch Dave, I didn't notice the file name... So yes it looks like the OP needs a v3 version of the dbfpy package. Or a different approach. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Wed Mar 12 10:18:05 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 12 Mar 2014 09:18:05 +0000 Subject: [Tutor] Loop Issue In-Reply-To: References: Message-ID: On 11/03/14 13:53, Yanni Phone wrote: > health = 10 > trolls = 0 > damage = 3 > while health != 0: > trolls += 1 > health -= damage > This seems simple enough. (This is an example of a non-terminating loop, > by the way, so it is not suppose to work correctly.) > My problem is that when I enter this into IDLE, and hot enter a few times. > I never get my prompt (>>>) back. That's because, as you just said, its a non-terminating loop. The prompt only returns when the loop ends, which is currently never. You will need to interrupt the loop (using Ctrl-C?) and fix the bug. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From denis.spir at gmail.com Wed Mar 12 12:19:48 2014 From: denis.spir at gmail.com (spir) Date: Wed, 12 Mar 2014 12:19:48 +0100 Subject: [Tutor] Help with Guess the number script In-Reply-To: References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> Message-ID: <532042D4.6040403@gmail.com> On 03/12/2014 05:13 AM, Scott Dunning wrote: >>> >> if guess < secret - 10 or guess > secret - 10: >> > >> >This is the right idea for cutting the line count but you >> >have the comparison values wrong. Look back to earlier >> >emails, you are repeating the same error as before. >> >Manually think through what happens in the line above >> >if guess == secret. > Oh, do you mean it should be <= and >=?? I?m not sure why that would work, because if guess==secret I have another statement in my code that takes care of that. I didn?t want to add my whole code because it?s too long but that is in there. Such errors are either obvious or invisible. A remedy is often to figure the problem on paper (or in your head if you're good at thinking visually). Here, just draw a line segment with secret in the middle and the interval borders around. Then, write there on the drawing the _values_ of the borders, as arithmetic expressions. d From davea at davea.name Wed Mar 12 13:19:29 2014 From: davea at davea.name (Dave Angel) Date: Wed, 12 Mar 2014 08:19:29 -0400 (EDT) Subject: [Tutor] Help with Guess the number script References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> <1573BAF6-8102-4FD3-B667-A32519741EE2@cox.net> Message-ID: Scott W Dunning Wrote in message: > > On Mar 11, 2014, at 7:50 PM, William Ray Wing wrote: >> >> Simple. In Mail Preferences -> Composing -> Message Format -> Plain Text (Your setting is probably currently Rich Text.) >> > Got it, hopefully that helps. Perfect, thanks. -- DaveA From breamoreboy at yahoo.co.uk Wed Mar 12 14:54:26 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Mar 2014 13:54:26 +0000 Subject: [Tutor] Trying to read dBase files In-Reply-To: References: <00ea01cf3d59$4fd2ea40$ef78bec0$@pubdmgroup.com> Message-ID: On 12/03/2014 09:13, Alan Gauld wrote: > On 11/03/14 20:09, Dave Angel wrote: >> Alan Gauld Wrote in message: > >>>> I am using Python 3.3. I did some google searches and found something >>>> called dbfpy to read dbase, so I downloaded and installed it. >>>> >>>> File "C:\Python33\lib\site-packages\dbfpy\dbf.py", line 260 >>>> print repr(_rec) >>>> ^ >>>> SyntaxError: invalid syntax >>> >> >> Which is in the dbfpy code. > > Oops, good catch Dave, I didn't notice the file name... > > So yes it looks like the OP needs a v3 version of > the dbfpy package. Or a different approach. > Or run 2to3 against dbfpy. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From stefan_ml at behnel.de Wed Mar 12 17:49:14 2014 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 12 Mar 2014 17:49:14 +0100 Subject: [Tutor] c++ on python In-Reply-To: References: <1394544744.31838.YahooMailNeo@web186003.mail.ir2.yahoo.com> Message-ID: Alan Gauld, 12.03.2014 10:11: > If it were a library then you would have to call > the individual C++ functions directly using > something like ctypes, which is usually more > complex. ctypes won't talk to C++, but Cython can do it quite easily. Stefan From stareq13 at yahoo.com Wed Mar 12 18:46:01 2014 From: stareq13 at yahoo.com (S Tareq) Date: Wed, 12 Mar 2014 17:46:01 +0000 (GMT) Subject: [Tutor] how do i delete the questions that i asked and it has been shared in web Message-ID: <1394646361.84880.YahooMailNeo@web133103.mail.ir2.yahoo.com> this one ?http://code.activestate.com/lists/python-tutor/99408/ ? and there are other ones as well? -------------- next part -------------- An HTML attachment was scrubbed... URL: From zachary.ware+pytut at gmail.com Wed Mar 12 19:03:23 2014 From: zachary.ware+pytut at gmail.com (Zachary Ware) Date: Wed, 12 Mar 2014 13:03:23 -0500 Subject: [Tutor] how do i delete the questions that i asked and it has been shared in web In-Reply-To: <1394646361.84880.YahooMailNeo@web133103.mail.ir2.yahoo.com> References: <1394646361.84880.YahooMailNeo@web133103.mail.ir2.yahoo.com> Message-ID: On Wed, Mar 12, 2014 at 12:46 PM, S Tareq wrote: > this one http://code.activestate.com/lists/python-tutor/99408/ > > and there are other ones as well This is a mailing list. Once an email is sent, you can't unsend it. -- Zach From stareq13 at yahoo.com Wed Mar 12 19:33:30 2014 From: stareq13 at yahoo.com (S Tareq) Date: Wed, 12 Mar 2014 18:33:30 +0000 (GMT) Subject: [Tutor] how do i delete the questions that i asked and it has been shared in web In-Reply-To: References: <1394646361.84880.YahooMailNeo@web133103.mail.ir2.yahoo.com> Message-ID: <1394649210.72213.YahooMailNeo@web133106.mail.ir2.yahoo.com> so you can't delete the question that i have asked long time ago? On Wednesday, 12 March 2014, 18:03, Zachary Ware wrote: On Wed, Mar 12, 2014 at 12:46 PM, S Tareq wrote: > this one? http://code.activestate.com/lists/python-tutor/99408/ > > and there are other ones as well This is a mailing list.? Once an email is sent, you can't unsend it. -- Zach _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From tdkrupinski at gmail.com Wed Mar 12 19:38:05 2014 From: tdkrupinski at gmail.com (Tim Krupinski) Date: Wed, 12 Mar 2014 13:38:05 -0500 Subject: [Tutor] how do i delete the questions that i asked and it has been shared in web In-Reply-To: <1394649210.72213.YahooMailNeo@web133106.mail.ir2.yahoo.com> References: <1394646361.84880.YahooMailNeo@web133103.mail.ir2.yahoo.com> <1394649210.72213.YahooMailNeo@web133106.mail.ir2.yahoo.com> Message-ID: No. On Wed, Mar 12, 2014 at 1:33 PM, S Tareq wrote: > so you can't delete the question that i have asked long time ago > > > On Wednesday, 12 March 2014, 18:03, Zachary Ware > wrote: > On Wed, Mar 12, 2014 at 12:46 PM, S Tareq wrote: > >> this one http://code.activestate.com/lists/python-tutor/99408/ >> >> and there are other ones as well > > > This is a mailing list. Once an email is sent, you can't unsend it. > > -- > Zach > _______________________________________________ > 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 kfiresmith at gmail.com Wed Mar 12 20:06:23 2014 From: kfiresmith at gmail.com (Kodiak Firesmith) Date: Wed, 12 Mar 2014 15:06:23 -0400 Subject: [Tutor] how do i delete the questions that i asked and it has been shared in web In-Reply-To: References: <1394646361.84880.YahooMailNeo@web133103.mail.ir2.yahoo.com> <1394649210.72213.YahooMailNeo@web133106.mail.ir2.yahoo.com> Message-ID: In fact all of these messages are being distributed and saved to various mailing list web mirrors as we send them. Your requests to delete the message will also appear pretty soon after you send them. On Wed, Mar 12, 2014 at 2:38 PM, Tim Krupinski wrote: > No. > > On Wed, Mar 12, 2014 at 1:33 PM, S Tareq wrote: > > so you can't delete the question that i have asked long time ago > > > > > > On Wednesday, 12 March 2014, 18:03, Zachary Ware > > wrote: > > On Wed, Mar 12, 2014 at 12:46 PM, S Tareq wrote: > > > >> this one http://code.activestate.com/lists/python-tutor/99408/ > >> > >> and there are other ones as well > > > > > > This is a mailing list. Once an email is sent, you can't unsend it. > > > > -- > > Zach > > _______________________________________________ > > 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 > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Mar 12 23:03:53 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 12 Mar 2014 22:03:53 +0000 Subject: [Tutor] how do i delete the questions that i asked and it has been shared in web In-Reply-To: <1394646361.84880.YahooMailNeo@web133103.mail.ir2.yahoo.com> References: <1394646361.84880.YahooMailNeo@web133103.mail.ir2.yahoo.com> Message-ID: On 12/03/14 17:46, S Tareq wrote: > this one http://code.activestate.com/lists/python-tutor/99408/ > > and there are other ones as well As others have said you can't delete them One of the features of a mailing list is that everyone on the list has a copy of the email and can keep that for as long as they wish. The point of the web mirrors is to provide an archive so you can search to see if anyone else has already asked the same question. If it were possible to delete old mails that knowledge would be lost. Anything you post to a public mailing list in effect becomes public property -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Wed Mar 12 23:05:53 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 12 Mar 2014 22:05:53 +0000 Subject: [Tutor] c++ on python In-Reply-To: References: <1394544744.31838.YahooMailNeo@web186003.mail.ir2.yahoo.com> Message-ID: On 12/03/14 16:49, Stefan Behnel wrote: > Alan Gauld, 12.03.2014 10:11: >> If it were a library then you would have to call >> the individual C++ functions directly using >> something like ctypes, which is usually more >> complex. > > ctypes won't talk to C++, but Cython can do it quite easily. I thought it would work provided the interface functions were declared as C functions? That might involve writing a wrapper around it but that is usually trivial if you have to compile the source anyway. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From dyoo at hashcollision.org Thu Mar 13 00:12:00 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 12 Mar 2014 16:12:00 -0700 Subject: [Tutor] Help with Guess the number script In-Reply-To: <532042D4.6040403@gmail.com> References: <9D518C41-5012-47AD-AD83-C0E8B5A24248@cox.net> <532042D4.6040403@gmail.com> Message-ID: > > Such errors are either obvious or invisible. A remedy is often to figure the > problem on paper (or in your head if you're good at thinking visually). > Here, just draw a line segment with secret in the middle and the interval > borders around. Then, write there on the drawing the _values_ of the > borders, as arithmetic expressions. Very much so. Diagrams are important. Not everything is textual. (Which you might consider with some irony based on some of the meta-discussion on this thread.) See some of the problem-solving heuristics described in: http://en.wikipedia.org/wiki/How_to_Solve_It "Can you think of a picture or a diagram that might help you understand the problem?" From dyoo at hashcollision.org Thu Mar 13 00:18:51 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 12 Mar 2014 16:18:51 -0700 Subject: [Tutor] Loop Issue In-Reply-To: References: Message-ID: This particular loop condition looks very suspicious. I would look at it more closely. When is it false? When is it true? From breamoreboy at yahoo.co.uk Thu Mar 13 00:37:04 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Mar 2014 23:37:04 +0000 Subject: [Tutor] Loop Issue In-Reply-To: References: Message-ID: On 12/03/2014 23:18, Danny Yoo wrote: > This particular loop condition looks very suspicious. I would look at > it more closely. When is it false? When is it true? Context please Danny, we're not all mind readers and we don't all have photographic memories :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From dyoo at hashcollision.org Thu Mar 13 00:40:19 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 12 Mar 2014 16:40:19 -0700 Subject: [Tutor] Loop Issue In-Reply-To: References: Message-ID: The context is the beginning of the thread: https://mail.python.org/pipermail/tutor/2014-March/100543.html with the loop: ### while health != 0: ... ### From scott.w.d at cox.net Thu Mar 13 03:29:50 2014 From: scott.w.d at cox.net (Scott W Dunning) Date: Wed, 12 Mar 2014 19:29:50 -0700 Subject: [Tutor] Project suggestions Message-ID: Hey Everyone, I just got through doing a Guess-the-number script and was looking for something else to practice on. Do any of you have any suggestions on some things I could work on? Keep in mind I am not only extremely new to python I am new to programming. Thanks for any suggestions!!! Scott From ben+python at benfinney.id.au Thu Mar 13 07:17:23 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 13 Mar 2014 17:17:23 +1100 Subject: [Tutor] Project suggestions References: Message-ID: <85vbvisjv0.fsf@benfinney.id.au> Scott W Dunning writes: > I just got through doing a Guess-the-number script and was looking for > something else to practice on. Do any of you have any suggestions on > some things I could work on? Keep in mind I am not only extremely new > to python I am new to programming. Thanks for any suggestions!!! You've received the suggestion, but I'll recommend it again: Newcomers to Python should work through the Python Tutorial . Run each example yourself, experiment at the interactive Python prompt to understand it, before continuing through the tutorial. -- \ ?Humanity has advanced, when it has advanced, not because it | `\ has been sober, responsible, and cautious, but because it has | _o__) been playful, rebellious, and immature.? ?Tom Robbins | Ben Finney From bodsda at googlemail.com Thu Mar 13 10:02:03 2014 From: bodsda at googlemail.com (Bod Soutar) Date: Thu, 13 Mar 2014 09:02:03 +0000 Subject: [Tutor] Project suggestions In-Reply-To: References: Message-ID: On 13 March 2014 02:29, Scott W Dunning wrote: > Hey Everyone, > > I just got through doing a Guess-the-number script and was looking for > something else to practice on. Do any of you have any suggestions on some > things I could work on? Keep in mind I am not only extremely new to python > I am new to programming. Thanks for any suggestions!!! > > Scott > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > There's a great list of Beginner Programming Challenges on Ubuntuforums that are a good way to get you thinking. http://ubuntuforums.org/showthread.php?t=1714324 -------------- next part -------------- An HTML attachment was scrubbed... URL: From paradox at pobox.com Thu Mar 13 10:48:21 2014 From: paradox at pobox.com (Paradox) Date: Thu, 13 Mar 2014 05:48:21 -0400 Subject: [Tutor] Project suggestions :p: In-Reply-To: References: Message-ID: <53217EE5.1040405@pobox.com> On 03/12/2014 10:29 PM, Scott W Dunning wrote: > Hey Everyone, > > I just got through doing a Guess-the-number script and was looking for something else to practice on. Do any of you have any suggestions on some things I could work on? Keep in mind I am not only extremely new to python I am new to programming. Thanks for any suggestions!!! > > Scott > _______________________________________________ I find that in conjunction with a good tutorial I like to have some problems to solve. I have been enjoying the puzzles on the checkio.org site recently. There is a great beginners area called "The Library" with very simple tasks, then other more challenging tasks in other levels. As you solve problems you gain points which unlock more challenging levels. thomas From russel at winder.org.uk Thu Mar 13 12:36:47 2014 From: russel at winder.org.uk (Russel Winder) Date: Thu, 13 Mar 2014 11:36:47 +0000 Subject: [Tutor] c++ on python In-Reply-To: References: <1394544744.31838.YahooMailNeo@web186003.mail.ir2.yahoo.com> Message-ID: <1394710607.8092.97.camel@launcelot.winder.org.uk> On Wed, 2014-03-12 at 22:05 +0000, Alan Gauld wrote: > On 12/03/14 16:49, Stefan Behnel wrote: > > Alan Gauld, 12.03.2014 10:11: > >> If it were a library then you would have to call > >> the individual C++ functions directly using > >> something like ctypes, which is usually more > >> complex. > > > > ctypes won't talk to C++, but Cython can do it quite easily. > > I thought it would work provided the interface functions > were declared as C functions? That might involve > writing a wrapper around it but that is usually > trivial if you have to compile the source anyway. ctypes (and CFFI) talks quite happily to C++ functions as long as they are declared with C linkage (so as to avoid any "name mangling"): export "C" x f(?){?} makes f accessible via ctypes if f is in a shared object/dynamic link library. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 181 bytes Desc: This is a digitally signed message part URL: From oscar.j.benjamin at gmail.com Thu Mar 13 13:55:16 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 13 Mar 2014 12:55:16 +0000 Subject: [Tutor] c++ on python In-Reply-To: References: Message-ID: On 7 March 2014 14:29, Gabriele Brambilla wrote: > Hi, > in the next days I will receive a c++ code that I would like to run in > python (http://docs.python.org/2/extending/index.html). > It should be self consistent (no extraroutines). > I want to be ready to use it... Has someone some C++ code examples available > that I can try to run easily before getting that code? Hi Gabriele, I recommend either Alan's suggestion of running the C++ code as an external application (with e.g. subprocess) or using cython to connect the C++ code to Python. Which is appropriate depends on what you need to do and how much flexibility you need from within the Python code. I learned C and C++ before Python and consider myself reasonably proficient in all 3 languages and capable of understanding (dis-)assembly and linkage and so on and I still find ctypes to be a bit of handful (I have less experience of cffi). Using Cython or just compiling the C++ code with an external compiler is much better for the error checking and so on. Using ctypes you get very little error-checking, just seg faults and corruption. Oscar From denis.spir at gmail.com Thu Mar 13 15:38:05 2014 From: denis.spir at gmail.com (spir) Date: Thu, 13 Mar 2014 15:38:05 +0100 Subject: [Tutor] Loop Issue In-Reply-To: References: Message-ID: <5321C2CD.6070606@gmail.com> On 03/13/2014 12:40 AM, Danny Yoo wrote: > The context is the beginning of the thread: > > https://mail.python.org/pipermail/tutor/2014-March/100543.html > > with the loop: > > > ### > while health != 0: > ... > ### The point, and reason why this loop was (potentially) infinite, is that the condition was false. Should be <0 instead ('cause health points are not removed one by one, so that a health value of 0 exactly can be jumped over). d From denis.spir at gmail.com Thu Mar 13 15:50:52 2014 From: denis.spir at gmail.com (spir) Date: Thu, 13 Mar 2014 15:50:52 +0100 Subject: [Tutor] Project suggestions In-Reply-To: References: Message-ID: <5321C5CC.4000204@gmail.com> On 03/13/2014 03:29 AM, Scott W Dunning wrote: > Hey Everyone, > > I just got through doing a Guess-the-number script and was looking for something else to practice on. Do any of you have any suggestions on some things I could work on? Keep in mind I am not only extremely new to python I am new to programming. Thanks for any suggestions!!! > > Scott There are many variants you can introduce in this game, small or big, that may drive to learn or practice notions of python and programming: * have the out-of-interval hint depend on actual present interval (rather than initial) * have the player choose the initial interval; or have random, in a sensible way * reverse the game: the human choose the secret number, and the machine plays * have both the 'chooser' and the 'guesser' be played by the computer * make the game (the game logic and rule) defined in code, instead of spread as a number of apparently unrelated data (the interval, the secret number...) and functions (the guesser guesses, the whole playing loop...) Technically, the latter point is sometimes called "reification" (literally thingification). We constantly do that in programming, especially (OO) object-oriented. It is argually the core of preperly structuring an app. In this case, it is not necessary, since the game (the gaming machine) is the whole app. However, you can do it as if it where a component or dimension of a bigger software system. As if your whole present code were embedded in: guess_the_number = { ... } and all top elements defined in your code are defining properties of the game. (Am I clear?) d From denis.spir at gmail.com Thu Mar 13 15:55:09 2014 From: denis.spir at gmail.com (spir) Date: Thu, 13 Mar 2014 15:55:09 +0100 Subject: [Tutor] Project suggestions In-Reply-To: <85vbvisjv0.fsf@benfinney.id.au> References: <85vbvisjv0.fsf@benfinney.id.au> Message-ID: <5321C6CD.809@gmail.com> On 03/13/2014 07:17 AM, Ben Finney wrote: > Scott W Dunning writes: > >> I just got through doing a Guess-the-number script and was looking for >> something else to practice on. Do any of you have any suggestions on >> some things I could work on? Keep in mind I am not only extremely new >> to python I am new to programming. Thanks for any suggestions!!! > > You've received the suggestion, but I'll recommend it again: > > Newcomers to Python should work through the Python Tutorial > . Run each example yourself, > experiment at the interactive Python prompt to understand it, before > continuing through the tutorial. Personly, I don't find this tutorial good at all. It is good enough for already programmers, especially ones knowing which share many *implicit* principles and notions with python; it was certainly firstly made for C/Unix hackers, and AFAIK hasn't much changed. d From denis.spir at gmail.com Thu Mar 13 15:52:31 2014 From: denis.spir at gmail.com (spir) Date: Thu, 13 Mar 2014 15:52:31 +0100 Subject: [Tutor] Project suggestions In-Reply-To: References: Message-ID: <5321C62F.7050709@gmail.com> On 03/13/2014 03:29 AM, Scott W Dunning wrote: > Hey Everyone, > > I just got through doing a Guess-the-number script and was looking for something else to practice on. Do any of you have any suggestions on some things I could work on? Keep in mind I am not only extremely new to python I am new to programming. Thanks for any suggestions!!! > > Scott Look at all games in the online tutrial "invent with python" (which I already mentionned): http://inventwithpython.com/ From davea at davea.name Thu Mar 13 16:42:51 2014 From: davea at davea.name (Dave Angel) Date: Thu, 13 Mar 2014 11:42:51 -0400 (EDT) Subject: [Tutor] Loop Issue References: <5321C2CD.6070606@gmail.com> Message-ID: spir Wrote in message: > On 03/13/2014 12:40 AM, Danny Yoo wrote: >> The context is the beginning of the thread: >> >> https://mail.python.org/pipermail/tutor/2014-March/100543.html >> >> with the loop: >> >> >> ### >> while health != 0: >> ... >> ### > > The point, and reason why this loop was (potentially) infinite, is that the > condition was false. Should be <0 instead ('cause health points are not removed > one by one, so that a health value of 0 exactly can be jumped over). > Well unless I misremember, the value of health goes down. So you'd want while health > 0 -- DaveA From stefan_ml at behnel.de Thu Mar 13 16:57:05 2014 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 13 Mar 2014 16:57:05 +0100 Subject: [Tutor] c++ on python In-Reply-To: References: <1394544744.31838.YahooMailNeo@web186003.mail.ir2.yahoo.com> Message-ID: Alan Gauld, 12.03.2014 23:05: > On 12/03/14 16:49, Stefan Behnel wrote: >> Alan Gauld, 12.03.2014 10:11: >>> If it were a library then you would have to call >>> the individual C++ functions directly using >>> something like ctypes, which is usually more >>> complex. >> >> ctypes won't talk to C++, but Cython can do it quite easily. > > I thought it would work provided the interface functions > were declared as C functions? That might involve > writing a wrapper around it but that is usually > trivial if you have to compile the source anyway. The thing is: if you have to write your own wrapper anyway (trivial or not), then why not write it in Cython right away and avoid the intermediate plain C level? It's usually much nicer to work with object oriented code on both sides (assuming you understand the languages on both sides), than to try to squeeze them through a C-ish API bottleneck in the middle. Stefan From russel at winder.org.uk Thu Mar 13 17:29:57 2014 From: russel at winder.org.uk (Russel Winder) Date: Thu, 13 Mar 2014 16:29:57 +0000 Subject: [Tutor] c++ on python In-Reply-To: References: <1394544744.31838.YahooMailNeo@web186003.mail.ir2.yahoo.com> Message-ID: <1394728197.27158.4.camel@launcelot.winder.org.uk> On Thu, 2014-03-13 at 16:57 +0100, Stefan Behnel wrote: [?] > The thing is: if you have to write your own wrapper anyway (trivial or > not), then why not write it in Cython right away and avoid the intermediate > plain C level? If the task is two write an adapter (aka wrapper) then perhaps use SWIG whcih is easier for this task than writing Cython code. > It's usually much nicer to work with object oriented code on both sides > (assuming you understand the languages on both sides), than to try to > squeeze them through a C-ish API bottleneck in the middle. It could be that "object oriented" is a red herring. Without details (*) of what it is about the C++ code that is the connection between Python and C++, it is difficult to generalize. ctypes can be a real pain when trying to call C++ from Python using argument values that are not primitive types. CFFI solves (currently much, soon most) of this problem by addressing the adapter between Python and C++ in a different way to that employed by ctypes. In both cases, both are a lot easier than writing Cython code. (*) I may have just missed this detail in which case apologies. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 181 bytes Desc: This is a digitally signed message part URL: From james at uplinkzero.com Thu Mar 13 17:35:17 2014 From: james at uplinkzero.com (James Chapman) Date: Thu, 13 Mar 2014 16:35:17 +0000 Subject: [Tutor] c++ on python In-Reply-To: References: <1394544744.31838.YahooMailNeo@web186003.mail.ir2.yahoo.com> Message-ID: Perhaps I should look into Cython as I'm currently working on a project that utilises a C API. I've been finding that getting the data types to be exactly what the C API is expecting to be the hardest part. With the original question in mind, here's an example calling into a C++ external C API: (Works if compiled is VisualStudio. The DLL produced by MinGW-G++ didn't work). ------------------------------- // main.h #ifndef __MAIN_H__ #define __MAIN_H__ #include #define DLL_EXPORT __declspec(dllexport) #ifdef __cplusplus extern "C" { #endif int DLL_EXPORT add(int a, int b); #ifdef __cplusplus } #endif #endif // __MAIN_H__ ------------------------------- ------------------------------- //main.cpp #include "main.h" // a sample exported function int DLL_EXPORT add(int a, int b) { return(a + b); } extern "C" DLL_EXPORT BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { switch (fdwReason) { case DLL_PROCESS_ATTACH: // attach to process // return FALSE to fail DLL load break; case DLL_PROCESS_DETACH: // detach from process break; case DLL_THREAD_ATTACH: // attach to thread break; case DLL_THREAD_DETACH: // detach from thread break; } return TRUE; // succesful } ------------------------------- ------------------------------- # -*- coding: utf-8 -*- # dll.py import ctypes class DllInterface(object): dll_handle = None def __init__(self, dll_file): self.dll_handle = ctypes.WinDLL(dll_file) def add_a_and_b(self, a=0, b=0): return self.dll_handle.add(a, b) if __name__ == '__main__': dll_file = 'PythonDLL.dll' external_lib = DllInterface(dll_file) int_a = ctypes.c_int(1) int_b = ctypes.c_int(2) result = external_lib.add_a_and_b(int_a, int_b) print(result) ------------------------------- -- James -- James On 13 March 2014 15:57, Stefan Behnel wrote: > Alan Gauld, 12.03.2014 23:05: >> On 12/03/14 16:49, Stefan Behnel wrote: >>> Alan Gauld, 12.03.2014 10:11: >>>> If it were a library then you would have to call >>>> the individual C++ functions directly using >>>> something like ctypes, which is usually more >>>> complex. >>> >>> ctypes won't talk to C++, but Cython can do it quite easily. >> >> I thought it would work provided the interface functions >> were declared as C functions? That might involve >> writing a wrapper around it but that is usually >> trivial if you have to compile the source anyway. > > The thing is: if you have to write your own wrapper anyway (trivial or > not), then why not write it in Cython right away and avoid the intermediate > plain C level? > > It's usually much nicer to work with object oriented code on both sides > (assuming you understand the languages on both sides), than to try to > squeeze them through a C-ish API bottleneck in the middle. > > Stefan > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From stefan_ml at behnel.de Thu Mar 13 18:15:50 2014 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 13 Mar 2014 18:15:50 +0100 Subject: [Tutor] c++ on python In-Reply-To: References: <1394544744.31838.YahooMailNeo@web186003.mail.ir2.yahoo.com> Message-ID: James Chapman, 13.03.2014 17:35: > Perhaps I should look into Cython as I'm currently working on a > project that utilises a C API. > > I've been finding that getting the data types to be exactly what the C > API is expecting to be the hardest part. > > With the original question in mind, here's an example calling into a > C++ external C API: > > (Works if compiled is VisualStudio. The DLL produced by MinGW-G++ didn't work). > > ------------------------------- > // main.h > > #ifndef __MAIN_H__ > #define __MAIN_H__ > > #include > > #define DLL_EXPORT __declspec(dllexport) > > #ifdef __cplusplus > extern "C" > { > #endif > > int DLL_EXPORT add(int a, int b); > > #ifdef __cplusplus > } > #endif > > #endif // __MAIN_H__ > ------------------------------- > > ------------------------------- > //main.cpp > > #include "main.h" > > // a sample exported function > int DLL_EXPORT add(int a, int b) > { > return(a + b); > } > > extern "C" DLL_EXPORT BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD > fdwReason, LPVOID lpvReserved) > { > switch (fdwReason) > { > case DLL_PROCESS_ATTACH: > // attach to process > // return FALSE to fail DLL load > break; > > case DLL_PROCESS_DETACH: > // detach from process > break; > > case DLL_THREAD_ATTACH: > // attach to thread > break; > > case DLL_THREAD_DETACH: > // detach from thread > break; > } > return TRUE; // succesful > } > ------------------------------- > > ------------------------------- > # -*- coding: utf-8 -*- > # dll.py > > import ctypes > > > class DllInterface(object): > > dll_handle = None > > def __init__(self, dll_file): > self.dll_handle = ctypes.WinDLL(dll_file) > > def add_a_and_b(self, a=0, b=0): > return self.dll_handle.add(a, b) > > > if __name__ == '__main__': > dll_file = 'PythonDLL.dll' > external_lib = DllInterface(dll_file) > int_a = ctypes.c_int(1) > int_b = ctypes.c_int(2) > result = external_lib.add_a_and_b(int_a, int_b) > print(result) In Cython, that would essentially be cdef extern from "main.h": int add(int a, int b) print(add(1, 2)) It compiles down to C(++), i.e. it interfaces at the API level, not the ABI level, as ctypes would. Stefan From stefan_ml at behnel.de Thu Mar 13 19:03:01 2014 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 13 Mar 2014 19:03:01 +0100 Subject: [Tutor] c++ on python In-Reply-To: <1394728197.27158.4.camel@launcelot.winder.org.uk> References: <1394544744.31838.YahooMailNeo@web186003.mail.ir2.yahoo.com> <1394728197.27158.4.camel@launcelot.winder.org.uk> Message-ID: Russel Winder, 13.03.2014 17:29: > On Thu, 2014-03-13 at 16:57 +0100, Stefan Behnel wrote: > [?] >> The thing is: if you have to write your own wrapper anyway (trivial or >> not), then why not write it in Cython right away and avoid the intermediate >> plain C level? > > If the task is two write an adapter (aka wrapper) then perhaps use SWIG > whcih is easier for this task than writing Cython code. Depends. SWIG is nice if you have a large API that a) you want to wrap quickly all at once and b) that matches the tool well. Once you're beyond the "matches the tool well" spot, however, you'll start having an increasingly hard time pushing the tool into matching your API. Cython has a higher learning curve to get started (it's a programming language, not a wrapper generator by itself, use something like XDress for that), but is unlimited in what it allows you to do (because it's a programming language). So things won't suddenly become harder (let alone impossible) afterwards. >> It's usually much nicer to work with object oriented code on both sides >> (assuming you understand the languages on both sides), than to try to >> squeeze them through a C-ish API bottleneck in the middle. > > It could be that "object oriented" is a red herring. Without details (*) > of what it is about the C++ code that is the connection between Python > and C++, it is difficult to generalize. Sure. I've seen both good and bad API designs in C++, as in any other language. > ctypes can be a real pain when trying to call C++ from Python using > argument values that are not primitive types. CFFI solves (currently > much, soon most) of this problem by addressing the adapter between > Python and C++ in a different way to that employed by ctypes. In both > cases, both are a lot easier than writing Cython code. Now, that's a bit overly generalising, wouldn't you say? Even in the cases where cffi is as simple as Cython, I'd still prefer the portability and simplicity advantage of having statically compiled (and tested) wrapper code over a mix of a hand written C++-to-C wrapper and some dynamically generated glue code with its own set of runtime dependencies. But I can certainly accept that tools like ctypes and cffi have their niche, too. If you're comfortable with them, and they fit your needs, then sure, use them. There isn't one tool that caters for everyone. Stefan From marc_eymard at hotmail.com Thu Mar 13 17:12:28 2014 From: marc_eymard at hotmail.com (Marc Eymard) Date: Thu, 13 Mar 2014 16:12:28 +0000 Subject: [Tutor] Beginner - list not returning correct variable value Message-ID: Hello Tutor, I am a self-taught Python script beginner and I do it from the Michael Dawson Book. In attached script, can somebody tell me why the values of the variables strenght_points, health_points, wisdom_points and dexterity_points stay at 0 value when 'printing' their value from the list attributes[] when the 'for' loop at the bottom of the script runs. I have commented out the script to highlight what causes me problem. I hope this is clear enough a question. Thanks for your help, Marc -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: Nested_tuple.py Type: text/x-script.phyton Size: 2689 bytes Desc: not available URL: From yannisphone at gmail.com Thu Mar 13 16:22:56 2014 From: yannisphone at gmail.com (Yanni Phone) Date: Thu, 13 Mar 2014 10:22:56 -0500 Subject: [Tutor] Loop Issue In-Reply-To: <5321C2CD.6070606@gmail.com> References: <5321C2CD.6070606@gmail.com> Message-ID: OK, thank you. I knew the loop was infinite but usuyally when I did infinite loops before, I had them print out a message, so it was obvious. Thanks for the clarification. On Thu, Mar 13, 2014 at 9:38 AM, spir wrote: > On 03/13/2014 12:40 AM, Danny Yoo wrote: > >> The context is the beginning of the thread: >> >> https://mail.python.org/pipermail/tutor/2014-March/100543.html >> >> with the loop: >> >> >> ### >> while health != 0: >> ... >> ### >> > > The point, and reason why this loop was (potentially) infinite, is that > the condition was false. Should be <0 instead ('cause health points are not > removed one by one, so that a health value of 0 exactly can be jumped over). > > d > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Mar 13 19:34:30 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 13 Mar 2014 18:34:30 +0000 Subject: [Tutor] Beginner - list not returning correct variable value In-Reply-To: References: Message-ID: On 13/03/14 16:12, Marc Eymard wrote: > In attached script, can somebody tell me why the values of the variables > strenght_points, health_points, wisdom_points and dexterity_points stay > at 0 value when 'printing' their value from the list attributes[] Because when you create the list you use the *values* of those variables at the time you created the list. They do not track the values of the variables after that so changing the variables has no effect on the list. But, looking at your list, it is a name and corresponding value. That is the definition of a dictionary so, rather than having a set of variables and trying to maintain a list reflecting those, you should just use a dictionary. So your code would start with: #set variables pool = 30 att_choice = None attributes = { 'strength':0, 'health':0, 'wisdom':0, 'dexterity',0 } Then instead of using the variables use: while att_choice != '0': print('here proof that variables values are changing as expected:') print(attributes['strength'],attributes['health'], attributes['wisdom'], attributes['dexterity'],pool) and if att_choice == '1': print('\nHow many strength points to add or remove?') points = int(input('Enter points here: ')) attributes['strength'] += points pool -= points and so on. Then finally to output the values: print('\nYou have now the following attributes and points:\n') for i in attributes: print(i,'\t',attributes[i]) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From denis.spir at gmail.com Fri Mar 14 11:22:46 2014 From: denis.spir at gmail.com (spir) Date: Fri, 14 Mar 2014 11:22:46 +0100 Subject: [Tutor] Loop Issue In-Reply-To: References: <5321C2CD.6070606@gmail.com> Message-ID: <5322D876.9050701@gmail.com> On 03/13/2014 04:42 PM, Dave Angel wrote: > spir Wrote in message: >> On 03/13/2014 12:40 AM, Danny Yoo wrote: >>> The context is the beginning of the thread: >>> >>> https://mail.python.org/pipermail/tutor/2014-March/100543.html >>> >>> with the loop: >>> >>> >>> ### >>> while health != 0: >>> ... >>> ### >> >> The point, and reason why this loop was (potentially) infinite, is that the >> condition was false. Should be <0 instead ('cause health points are not removed >> one by one, so that a health value of 0 exactly can be jumped over). >> > > Well unless I misremember, the value of health goes down. So > you'd want > > while health > 0 oops! and "the condition was false" --> "wrong" d From ml at fam-goebel.de Fri Mar 14 11:40:59 2014 From: ml at fam-goebel.de (Ulrich Goebel) Date: Fri, 14 Mar 2014 11:40:59 +0100 Subject: [Tutor] Printing from python Message-ID: <5322DCBB.5020401@fam-goebel.de> Hallo, is there another way to pritt a PDF form python? My problem is a PDF which is printed well by evince, but not with lp, even not out of python using os.system("lp some_options file.pdf") Later on I have to build the PDF in a python program (using reportlab) and then print it, even from the python program. So I look for a (nice documented) library which give access to the CUPS API or something else to print the PDF from python. Any help is welcome! Ulrich -- Ulrich Goebel Paracelsusstr. 120, 53177 Bonn From ml at fam-goebel.de Fri Mar 14 12:14:26 2014 From: ml at fam-goebel.de (Ulrich Goebel) Date: Fri, 14 Mar 2014 12:14:26 +0100 Subject: [Tutor] Printing from python In-Reply-To: <5322DCBB.5020401@fam-goebel.de> References: <5322DCBB.5020401@fam-goebel.de> Message-ID: <5322E492.2050005@fam-goebel.de> I just found a hint, the Qt QPrinter Class. I use Qt, so that could be a solution? Am 14.03.2014 11:40, schrieb Ulrich Goebel: > Hallo, > > is there another way to pritt a PDF form python? > > My problem is a PDF which is printed well by evince, but not with lp, > even not out of python using > > os.system("lp some_options file.pdf") > > Later on I have to build the PDF in a python program (using reportlab) > and then print it, even from the python program. > > So I look for a (nice documented) library which give access to the CUPS > API or something else to print the PDF from python. > > Any help is welcome! > > Ulrich > > -- Ulrich Goebel Paracelsusstr. 120, 53177 Bonn From ml at fam-goebel.de Fri Mar 14 12:21:09 2014 From: ml at fam-goebel.de (Ulrich Goebel) Date: Fri, 14 Mar 2014 12:21:09 +0100 Subject: [Tutor] Printing from python In-Reply-To: <5322DCBB.5020401@fam-goebel.de> References: <5322DCBB.5020401@fam-goebel.de> Message-ID: <5322E625.30600@fam-goebel.de> Am 14.03.2014 11:40, schrieb Ulrich Goebel: > is there another way to pritt a PDF form python? sorry, that doesn't make sense. I should say: is there another way ... besides os.system()? -- Ulrich Goebel Paracelsusstr. 120, 53177 Bonn From russel at winder.org.uk Fri Mar 14 19:19:13 2014 From: russel at winder.org.uk (Russel Winder) Date: Fri, 14 Mar 2014 18:19:13 +0000 Subject: [Tutor] Printing from python In-Reply-To: <5322DCBB.5020401@fam-goebel.de> References: <5322DCBB.5020401@fam-goebel.de> Message-ID: <1394821153.4526.10.camel@launcelot.winder.org.uk> On Fri, 2014-03-14 at 11:40 +0100, Ulrich Goebel wrote: > Hallo, > > is there another way to pritt a PDF form python? > > My problem is a PDF which is printed well by evince, but not with lp, > even not out of python using > > os.system("lp some_options file.pdf") Python is deprecating os.system in favour of using the subprocess package. subprocess.call('lp some_options file.pdf', shell=True) or subprocess.call(['lp', *some_options, 'file.pdf') assuming some_options is a sequence of strings, on option per string. > Later on I have to build the PDF in a python program (using reportlab) > and then print it, even from the python program. > > So I look for a (nice documented) library which give access to the CUPS > API or something else to print the PDF from python. > > Any help is welcome! Debian Sid has packages python-cups and python-cupshelpers which are Python 2 APIs for working with CUPS. Sadly there do not seem to be Python 3 versions of these In Debian, but the package in PyPI is pycups so can be made available to Pytho 3. Also: http://cyberelk.net/tim/software/pycups/ I have not used these yet myself, but I have trying them out on my agenda for later in the spring. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 181 bytes Desc: This is a digitally signed message part URL: From timomlists at gmail.com Fri Mar 14 19:07:53 2014 From: timomlists at gmail.com (Timo) Date: Fri, 14 Mar 2014 19:07:53 +0100 Subject: [Tutor] Printing from python In-Reply-To: <5322E492.2050005@fam-goebel.de> References: <5322DCBB.5020401@fam-goebel.de> <5322E492.2050005@fam-goebel.de> Message-ID: <53234579.3070109@gmail.com> op 14-03-14 12:14, Ulrich Goebel schreef: > I just found a hint, the Qt QPrinter Class. I use Qt, so that could be > a solution? This would be your best bet, use the tools which are provided. I'm a GTK user and use the GTK printing API to both create and print reports. If you want to use cups, this is a project with Python bindings for cups: https://pypi.python.org/pypi/pycups/1.9.66 Timo > > > Am 14.03.2014 11:40, schrieb Ulrich Goebel: >> Hallo, >> >> is there another way to pritt a PDF form python? >> >> My problem is a PDF which is printed well by evince, but not with lp, >> even not out of python using >> >> os.system("lp some_options file.pdf") >> >> Later on I have to build the PDF in a python program (using reportlab) >> and then print it, even from the python program. >> >> So I look for a (nice documented) library which give access to the CUPS >> API or something else to print the PDF from python. >> >> Any help is welcome! >> >> Ulrich >> >> > From alan.gauld at btinternet.com Fri Mar 14 20:55:14 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Mar 2014 19:55:14 +0000 Subject: [Tutor] Printing from python In-Reply-To: <5322DCBB.5020401@fam-goebel.de> References: <5322DCBB.5020401@fam-goebel.de> Message-ID: On 14/03/14 10:40, Ulrich Goebel wrote: > Later on I have to build the PDF in a python program (using reportlab) > and then print it, even from the python program. > > So I look for a (nice documented) library which give access to the CUPS > API or something else to print the PDF from python. I may be mistaken but I don't think CUPS will help you. PDF documents are effectively programs that have to be interpreted by a PDF reader of some sort. Some printers have that capability built in, most require a program such as Acrobat or ghostscript to do the formatting for them. I don't think CUPS has an API for rendering PDF directly it will simply send the PDF direct to a PDF aware printer or take the image out from a PDF reader and send it to a standard print driver. Your Qt solution may support PDF rendering, I don't know Qt, but its definitely worth pursuing. Failing that you probably do need to use subprocess to launch ghostscript or similar. But there is no shame in that, chaining programs together is standard Unix practice and a sign of good design - one program does one job. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From ben+python at benfinney.id.au Fri Mar 14 22:25:17 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 15 Mar 2014 08:25:17 +1100 Subject: [Tutor] Printing from python References: <5322DCBB.5020401@fam-goebel.de> Message-ID: <85a9csscaq.fsf@benfinney.id.au> Ulrich Goebel writes: > So I look for a (nice documented) library which give access to the > CUPS API or something else to print the PDF from python. > > Any help is welcome! The problem isn't really one to be solved within your program, IMO. Printing is implemented as a service at the operating system (OS) level. Once you have a document in a form suitable for sending to a printer (such as a PDF), the OS is where any problems with the actual printing need to be addressed. Also, since it is implemented at the OS level, you're not going to find a solution in a platform-agnostic programming language like Python. The solution, whatever it is, will be highly dependent on the services presented by your specific OS. Of course, once you have a suitable OS service for printing the document, Python can send the document to that service. But at that point, the Python code will be trivially easy: probably invoking an external command via ?subprocess.call? or ?subprocess.check_call?. In short: printing is a problem to be solved via the OS, not via Python. -- \ ?We are not gonna be great; we are not gonna be amazing; we are | `\ gonna be *amazingly* amazing!? ?Zaphod Beeblebrox, _The | _o__) Hitch-Hiker's Guide To The Galaxy_, Douglas Adams | Ben Finney From shyamk.py at gmail.com Sun Mar 16 18:42:25 2014 From: shyamk.py at gmail.com (shyam kankala) Date: Sun, 16 Mar 2014 23:12:25 +0530 Subject: [Tutor] Tutor Digest, Vol 121, Issue 3 In-Reply-To: References: Message-ID: hi, Here you have the Answer. Plz go through it.... 1. # This is a guess the number game. 2. import random 3. 4. guessesTaken = 0 5. 6. print('Hello! What is your name?') 7. myName = input() 8. 9. number = random.randint(1, 20) 10. print('Well, ' + myName + ', I am thinking of a number between 1 and 20.') 11. 12. while guessesTaken < 6: 13. print('Take a guess.') # There are four spaces in front of print. 14. guess = input() 15. guess = int(guess) 16. 17. guessesTaken = guessesTaken + 1 18. 19. if guess < number: 20. print('Your guess is too low.') # There are eight spaces in front of print. 21. 22. if guess > number: 23. print('Your guess is too high.') 24. 25. if guess == number: 26. break 27. 28. if guess == number: 29. guessesTaken = str(guessesTaken) 30. print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!') 31. 32. if guess != number: 33. number = str(number) 34. print('Nope. The number I was thinking of was ' + number) On Sun, Mar 2, 2014 at 1:03 PM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Help with "Guess the number" script (spir) > 2. Re: Help with "Guess the Number" script (Mark Lawrence) > 3. Re: When to use multiprocessing Managers? (eryksun) > 4. Re: Help with "Guess the number" script (Alan Gauld) > 5. Re: Help with "Guess the number" script (Alan Gauld) > 6. Re: Help with "Guess the number" script (Scott W Dunning) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sat, 01 Mar 2014 14:53:57 +0100 > From: spir > To: tutor at python.org > Subject: Re: [Tutor] Help with "Guess the number" script > Message-ID: <5311E675.9020102 at gmail.com> > Content-Type: text/plain; charset=UTF-8; format=flowed > > On 03/01/2014 07:46 AM, Scott W Dunning wrote: > > Hello, i am working on a project for learning python and I?m stuck. The > directions are confusing me. Please keep in mind I?m very ne to this. The > directions are long so I?ll just add the paragraphs I?m confused about and > my code if someone could help me out I?d greatly appreciate it! Also, we > haven?t learned loops yet so just conditional operators and for some reason > we can?t use global variables. > > > > > > from random import randrange > > randrange(1, 101) > > > > from random import seed > > seed(129) > > > > def print_description(): > > print """Welcome to Guess the Number. > > I have seleted a secret number in the range 1 ... 100. > > You must guess the number within 10 tries. > > I will tell you if you ar high or low, and > > I will tell you if you are hot or cold.\n""" > > > > def get_guess(guess_number): > > print "(",guess_number,")""Plese enter a guess:" > > current_guess = raw_input() > > return int(guess_number) > > > > def main(): > > print_description() > > secret = 50 > > current_guess = 1 > > get_guess(1) > > if current_guess != secret(): > > print "Congratulations you win!!" > > > > main() > > > > > > Here are the instructions I?m having a hard time with and just not sure > I?m doing it correctly. I?m not sure the get_guess function is correct and > I?m a little lost with the secret and current_guess variable. > > > > From within the body of the main function, immediately after the call > to print description, create variable secret and assign it a random number > between 1 and 100, generated using the randrange function. You will need to > pass two argument to randrange, what do you think they should be? You > should be able to use the python help system or online python documentation > to make sure you understand the arguments to randrange. > > > > After the end of the body of the print description function, define a > new global function named get guess that takes a single parameter. Name the > parameter guess number, because it will hold the index (1, 2, 3, ..., 10) > of current guess attempt. Make the function ask the user to enter guess > using the raw input function. The function will return the number entered > by the user, after it has been converted to an integer. > > > > Return to the main function after the statement that assigned a value to > the secret variable. In a new variable named current guess store the result > of calling the get guess function with an argument of 1. Run your program > to make sure it works correctly. > > > > At the end of the main function, check if the current guess matches the > secret. If it matches, print ?Congratulations, you win!?. If it does not, > print ?Please play again!? > > I find directions very confusing. Also, they completely control you while > explaining about nothing, like a user manual saying "press this, turn > that". > This is inappropriate for programming (and anything else): you need to > understand! You need the why's and the how's, not only the what's. > > If not enough, they seem to teach you pretty weird practices: what is the > point > of the parameter guess_number? It is not a parameter, less so of this > function, > but a counter proper to the game control, possibly used at the end to > write "You > won in [counter] trials." But it is not and cannot be used as a parameter > to > get_guess. Also, what is the point of requiring you to write this game > without a > loop? You need a loop. If they want to teach you other notions first, they > must > find another sample program. > > If the rest of the book is similar, I would encourage you to change. Maybe > try > one of those (or why not both in //): > > * Alan Gauld's "Learning to Program": a very good point is this guide > teaches to > program, in general, *using* Python, mainly: > http://www.alan-g.me.uk/l2p/index.htm > > * Al sweigart's "invent with python": this one teaches python & > programming, > using games as learning material: > http://inventwithpython.com/ > > The first example in the latter book is precisely "guess my number". So, > you can > find correct code for it there. > > d > > > > ------------------------------ > > Message: 2 > Date: Sat, 01 Mar 2014 15:57:22 +0000 > From: Mark Lawrence > To: tutor at python.org > Subject: Re: [Tutor] Help with "Guess the Number" script > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 01/03/2014 06:05, Scott Dunning wrote: > > In addition to the answers you've already had, I suggest that you learn > to run code at the interactive prompt, it's a great way of seeing > precisely what snippets of code actually do. Also use the print > statement in Python 2 or print function in Python 3, again a great way > to observe what your code is doing. > > -- > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > > Mark Lawrence > > --- > This email is free from viruses and malware because avast! Antivirus > protection is active. > http://www.avast.com > > > > > ------------------------------ > > Message: 3 > Date: Sat, 1 Mar 2014 11:48:25 -0500 > From: eryksun > To: James Chapman > Cc: tutor at python.org > Subject: Re: [Tutor] When to use multiprocessing Managers? > Message-ID: > LMuN9YLYzuphVJmPTQcAeUA at mail.gmail.com> > Content-Type: text/plain; charset=UTF-8 > > On Fri, Feb 28, 2014 at 6:31 AM, James Chapman > wrote: > > > > log_Q = multiprocessing.Queue() > > This is a Queue from multiprocessing.queues. It uses system resources > (e.g. a semaphore for the queue capacity) that can be shared with > processes on the same machine. > > A value `put` in a queue.Queue is available immediately: > > >>> import queue > >>> q1 = queue.Queue() > >>> try: q1.put('value'); q1.get_nowait() > ... except queue.Empty: 'empty' > ... > 'value' > > On the other hand, a Queue from multiprocessing.queues writes to a > pipe using a background thread, so there can be a small delay: > > >>> import multiprocessing as mp > >>> q2 = mp.Queue() > >>> try: q2.put('value'); q2.get_nowait() > ... except queue.Empty: 'empty' > ... > 'empty' > >>> q2.get_nowait() > 'value' > > > or whether I create it like this: > > > > multimanager = multiprocessing.Manager() > > log_Q = multimanager.Queue() > > This is a queue.Queue wrapped by an AutoProxy. For example, its `get` > method calls _callmethod('get', *args, **kwds), which connects to the > manager, sends the request, and receives the result. > > The docs demonstrate using a manager with remote processes: > > http://docs.python.org/3/library/multiprocessing#using-a-remote-manager > > You can also proxy the Queue type from multiprocessing.queues. In that > case, remote processes use a proxy, but local processes can use the > queue directly. > > > Perhaps the manager would be important if I was writing to a Queue and > > expecting all threads to see that message? > > Only 1 thread will `get` the message. > > > ------------------------------ > > Message: 4 > Date: Sat, 01 Mar 2014 17:16:02 +0000 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Help with "Guess the number" script > Message-ID: > Content-Type: text/plain; charset=UTF-8; format=flowed > > > Scott W Dunning writes: > > > def get_guess(guess_number): > > print "(",guess_number,")""Plese enter a guess:" > > Aren't you missing a comma before the last string? > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > > > ------------------------------ > > Message: 5 > Date: Sat, 01 Mar 2014 17:29:46 +0000 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Help with "Guess the number" script > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 01/03/14 17:16, Alan Gauld wrote: > > > > Scott W Dunning writes: > > > >> def get_guess(guess_number): > >> print "(",guess_number,")""Plese enter a guess:" > > > > Aren't you missing a comma before the last string? > > > I just realized it will work because Python auto joins adjacent > string literals. But in this case you should probably just > remove both quotes and make it more readable. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > > > ------------------------------ > > Message: 6 > Date: Sat, 1 Mar 2014 17:43:57 -0700 > From: Scott W Dunning > To: Ben Finney > Cc: tutor at python.org > Subject: Re: [Tutor] Help with "Guess the number" script > Message-ID: > Content-Type: text/plain; charset=windows-1252 > > > On Mar 1, 2014, at 12:47 AM, Ben Finney > wrote: > > > You've bound the name ?current_guess? to the user's input, but then do > > nothing with it for the rest of the function; it will be discarded > > without being used. > Hmm, I?m not quite sure I understand. I got somewhat confused because the > directions were changed a little and current_guess was removed from the > get_guess function. Is this more like what I should be doing? > > def get_guess(guess_number): > raw_input(?Please enter a guess?) > guess_number = int(guess_number) > return (guess_number) > get_guess(1) > > > > > Then, you use the parameter ?guess_number?, create a new integer from > > it, and return that integer. I think you've used the wrong name for the > > ?int()? parameter. > Well, since there are no loops allowed I?m guessing get_guess will be > called 9 times. I believe guess_number is the number of tries the user has > used. > So; > (1) Please enter a guess: > (2) Please enter a guess: > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 121, Issue 3 > ************************************* > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jsutar at gmail.com Mon Mar 17 11:22:33 2014 From: jsutar at gmail.com (Jignesh Sutar) Date: Mon, 17 Mar 2014 10:22:33 +0000 Subject: [Tutor] Multiple for and if/else statements into a single list comprehension Message-ID: Is it possible to get two nested for statements followed by a nested if/else statement all into a single list comprehension ie. the equivalent of the below: for i in xrange(1,20): for j in xrange(1,10): if j<6: j=int("8"+str(j)) else: j=int("9"+str(j)) print "%(i)02d_%(j)02d" % locals() # double for statement without if/else works print "\n".join(["%(i)02d_%(j)02d" % locals() for i in xrange(1,20) for j in xrange(1,10)]) #now try to incorporate if/else part #failed attempt 1 print "\n".join(["%(i)02d_%(j)02d" % locals() for i in xrange(1,20) for j in xrange(1,10) j=int("8"+str(j)) if j<6 else int("9"+str(j))]) #failed attempt 2 print "\n".join(["%(i)02d_%(j)02d" % locals() for i in xrange(1,20) j=int("8"+str(j)) if j<6 else int("9"+str(j)) for j in xrange(1,10)]) #failed attempt 3 print "\n".join(["%(i)02d_%(j)02d" % locals() j=int("8"+str(j)) if j<6 else int("9"+str(j)) for i in xrange(1,20) for j in xrange(1,10)]) Many thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Mar 17 12:18:52 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 17 Mar 2014 12:18:52 +0100 Subject: [Tutor] Multiple for and if/else statements into a single list comprehension References: Message-ID: Jignesh Sutar wrote: > Is it possible to get two nested for statements followed by a nested > if/else statement all into a single list comprehension ie. the equivalent > of the below: > > > for i in xrange(1,20): > for j in xrange(1,10): > if j<6: > j=int("8"+str(j)) > else: > j=int("9"+str(j)) > print "%(i)02d_%(j)02d" % locals() > Many thanks in advance. Need I say that it is a bad idea to build overly complex list comprehensions? Under that proviso: The first step is always to ensure that there is a single expression in the inner loop. I'm keeping as similar as possible to your loops: for i in xrange(1, 20): for j in xrange(1, 10): print "%02d_%02d" % (i, int(("8" if j < 6 else "9") + str(j))) Now the translation is mechanical for x in a: for y in b: expr becomes [expr for x in a for y in b] or (using a genexp rather than a listcomp as you are going to print it anyway) print "\n".join( "%02d_%02d" % (i, int(("8" if j < 6 else "9") + str(j))) for i in xrange(1, 20) for j in xrange(1, 10)) But again: don't do that ;) By the way, using locals() is another bad idea, plus it does not capture the loop vars of genexps (all pythons) and listcomps (python3). PS: a simple alternative: print "\n".join( "%02d_%02d" % (i, k) for i in range(1, 20) for k in range(81, 86) + range(96, 100)) From __peter__ at web.de Mon Mar 17 12:22:55 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 17 Mar 2014 12:22:55 +0100 Subject: [Tutor] Multiple for and if/else statements into a single list comprehension References: Message-ID: Peter Otten wrote: > [locals()] does not capture > the loop vars of genexps (all pythons) and listcomps (python3). Sorry, I was totally wrong on that one. From denis.spir at gmail.com Mon Mar 17 13:36:01 2014 From: denis.spir at gmail.com (spir) Date: Mon, 17 Mar 2014 13:36:01 +0100 Subject: [Tutor] Multiple for and if/else statements into a single list comprehension In-Reply-To: References: Message-ID: <5326EC31.4070306@gmail.com> On 03/17/2014 11:22 AM, Jignesh Sutar wrote: > Is it possible to get two nested for statements followed by a nested > if/else statement all into a single list comprehension ie. the equivalent > of the below: > > > for i in xrange(1,20): > for j in xrange(1,10): > if j<6: > j=int("8"+str(j)) > else: > j=int("9"+str(j)) > print "%(i)02d_%(j)02d" % locals() You can do it by reformulating your inner block into an expression (here, using a ternary if expression), which will then become the expression part of the comprehension. However, a few remarks: * don't do that: the only advantage is to make your code unreadable * you may reformulate using 2 comprehensions; if you don't want intermediate lists, use a generator expression for the inner one * above, the inner j is a new variable with a distinct meaning: why do you call it j? * do you really need string concat to perform arithmetic? d From jignesh.sutar at gmail.com Mon Mar 17 11:19:40 2014 From: jignesh.sutar at gmail.com (Jignesh Sutar) Date: Mon, 17 Mar 2014 10:19:40 +0000 Subject: [Tutor] Multiple for and if/else statements into a single list comprehension Message-ID: Is it possible to get two nested for statements followed by a nested if/else statement all into a single list comprehension ie. the equivalent of the below: for i in xrange(1,20): for j in xrange(1,10): if j<6: j=int("8"+str(j)) else: j=int("9"+str(j)) print "%(i)02d_%(j)02d" % locals() # double for statement without if/else works print "\n".join(["%(i)02d_%(j)02d" % locals() for i in xrange(1,20) for j in xrange(1,10)]) #now try to incorporate if/else part #failed attempt 1 print "\n".join(["%(i)02d_%(j)02d" % locals() for i in xrange(1,20) for j in xrange(1,10) j=int("8"+str(j)) if j<6 else int("9"+str(j))]) #failed attempt 2 print "\n".join(["%(i)02d_%(j)02d" % locals() for i in xrange(1,20) j=int("8"+str(j)) if j<6 else int("9"+str(j)) for j in xrange(1,10)]) #failed attempt 3 print "\n".join(["%(i)02d_%(j)02d" % locals() j=int("8"+str(j)) if j<6 else int("9"+str(j)) for i in xrange(1,20) for j in xrange(1,10)]) Many thanks in advance. Jignesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From mydayfabu at gmail.com Mon Mar 17 14:11:57 2014 From: mydayfabu at gmail.com (fabu desay) Date: Mon, 17 Mar 2014 14:11:57 +0100 Subject: [Tutor] Tutor Digest, Vol 121, Issue 42 nested "for" Message-ID: python executes the first "for" and its condititions then the next "for". What i'm saying is that you should first deal with one as nested block codes From jsutar at gmail.com Mon Mar 17 23:35:48 2014 From: jsutar at gmail.com (Jignesh Sutar) Date: Mon, 17 Mar 2014 22:35:48 +0000 Subject: [Tutor] Multiple for and if/else statements into a single list comprehension In-Reply-To: <5326EC31.4070306@gmail.com> References: <5326EC31.4070306@gmail.com> Message-ID: Thanks Peter/Denis. I wasn't aware of genexp. I see how you have adapted the code to make it work, I'll adapt the same in my program. Good point about duplicating j , Denis, I guess I was happy to override the outer j as it was intermediate. On 17 March 2014 12:36, spir wrote: > On 03/17/2014 11:22 AM, Jignesh Sutar wrote: > >> Is it possible to get two nested for statements followed by a nested >> if/else statement all into a single list comprehension ie. the equivalent >> of the below: >> >> >> for i in xrange(1,20): >> for j in xrange(1,10): >> if j<6: >> j=int("8"+str(j)) >> else: >> j=int("9"+str(j)) >> print "%(i)02d_%(j)02d" % locals() >> > > You can do it by reformulating your inner block into an expression (here, > using a ternary if expression), which will then become the expression part > of the comprehension. However, a few remarks: > > * don't do that: the only advantage is to make your code unreadable > * you may reformulate using 2 comprehensions; if you don't want > intermediate lists, use a generator expression for the inner one > * above, the inner j is a new variable with a distinct meaning: why do you > call it j? > * do you really need string concat to perform arithmetic? > > > d > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From yashpanv at gmail.com Tue Mar 18 12:11:45 2014 From: yashpanv at gmail.com (y j) Date: Tue, 18 Mar 2014 16:41:45 +0530 Subject: [Tutor] help Message-ID: how can i split a word into letters in python 2.7.6? -- Y D Jain -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at graniteweb.com Tue Mar 18 16:34:47 2014 From: david at graniteweb.com (David Rock) Date: Tue, 18 Mar 2014 10:34:47 -0500 Subject: [Tutor] help (Splitting a word into letters) In-Reply-To: References: Message-ID: <20140318153447.GB22760@wdfs.graniteweb.com> * y j [2014-03-18 16:41]: > how can i split a word into letters in python 2.7.6? Strings can already be accessed as arrays: >>> s='foobar' >>> print s[2] o >>> print s[4] a >>> print s[7] Traceback (most recent call last): File "", line 1, in IndexError: string index out of range >>> Can you be a little clearer what you need? Are you looking to store them in variables, an array, print them? If printing them, are you looking to output one per line, or spaced out? -- David Rock david at graniteweb.com From joel.goldstick at gmail.com Tue Mar 18 19:21:00 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 18 Mar 2014 14:21:00 -0400 Subject: [Tutor] help In-Reply-To: References: Message-ID: List On Mar 18, 2014 11:08 AM, "y j" wrote: > how can i split a word into letters in python 2.7.6? > > -- > Y D Jain > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Mar 18 19:37:26 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 18 Mar 2014 18:37:26 +0000 Subject: [Tutor] help In-Reply-To: References: Message-ID: On 18/03/14 18:21, Joel Goldstick wrote: > List > > On Mar 18, 2014 11:08 AM, "y j" > wrote: > > how can i split a word into letters in python 2.7.6? or more specifically list(aString) - lowercase and with params. That will give you a list of the individual letters. Assuming that's what you mean. As David says there are several other options depending on what exactly you want. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From questions.anon at gmail.com Wed Mar 19 06:12:06 2014 From: questions.anon at gmail.com (questions anon) Date: Wed, 19 Mar 2014 16:12:06 +1100 Subject: [Tutor] loop through hours to calc max and plot Message-ID: Hi All, I have monthly netcdf files containing hourly temperature data. I would like to loop through all of the hours and calculate the max for each hour (00 - 23) and then make a plot. I have found a way for this to work for a couple of the hours (see below) but it requires a lot of set up to do each hour and I am sure there must be a simpler way using loops? I also need to find a simpler way as I would like to eventually do daily for 1st jan to 31st Dec Any feedback will be greatly appreciated from netCDF4 import Dataset import numpy as N import matplotlib.pyplot as plt from numpy import ma as ma from mpl_toolkits.basemap import Basemap from netcdftime import utime from datetime import datetime import os from matplotlib.collections import LineCollection shapefile1="---" OutputFolder=r"/---/" fileforlatlon=Dataset("---.nc", 'r+', 'NETCDF4') LAT=fileforlatlon.variables['latitude'][:] LON=fileforlatlon.variables['longitude'][:] #Set up basemap using mercator projection http://matplotlib.sourceforge.net/basemap/doc/html/users/merc.html map = Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33,llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i') x,y=map(*N.meshgrid(LON,LAT)) map.readshapefile(shapefile1, '-REGIONS') ncvariablename='T_SFC' MainFolder=r"/---/" ticks=[-5,0,5,10,15,20,25,30,35,40,45,50] Title='Surface Temperature (degrees celsius)' cmap=plt.cm.jet all_variabledata=[] time00=[] time12=[] for (path, dirs, files) in os.walk(MainFolder): for dir in dirs: print "the dirs are:", dir path=path+'/' for ncfile in files: fileext=ncvariablename+'.nc' if ncfile.endswith(fileext): print "dealing with ncfiles:", path+ncfile ncfile=os.path.join(path,ncfile) ncfile=Dataset(ncfile, 'r+', 'NETCDF4') TIME=ncfile.variables['time'][1::] #variable=ncfile.variables[ncvariablename][:,:,:] TSFC00=ncfile.variables[ncvariablename][00:01:,:,:] TSFC12=ncfile.variables[ncvariablename][12:13:,:,:] fillvalue=ncfile.variables[ncvariablename]._FillValue ncfile.close() #combine all data from the chosen variable to make one array for analyses cdftime=utime('seconds since 1970-01-01 00:00:00') ncfiletime=cdftime.num2date(TIME) for i in ncfiletime[:]: ncfiletime=i timestr=str(ncfiletime) d = datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S') date_string = d.strftime('%H')#combine by same hour print "the ncfiletime is:", ncfiletime print "the date_string is:", date_string if date_string=='00': time00.append(TSFC00) elif date_string=='12': time12.append(TSFC12) else: pass big_arraytime00=N.ma.concatenate(time00) big_arraytime12=N.ma.concatenate(time12) MAX00=big_arraytime00.max(axis=0) MAX12=big_arraytime12.max(axis=0) #plot output summary stats map = Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33, llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i') map.drawcoastlines() map.drawstates() map.readshapefile(shapefile1, 'REGIONS') x,y=map(*N.meshgrid(LON,LAT)) plottitle='TSFCmax00' plt.title(plottitle) CS = map.contourf(x,y,MAX00, ticks, cmap=cmap) l,b,w,h =0.1,0.1,0.8,0.8 cax = plt.axes([l+w+0.025, b, 0.025, h]) plt.colorbar(CS,cax=cax, drawedges=True) plt.savefig((os.path.join(OutputFolder, plottitle+'.png'))) plt.show() plt.close() map = Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33, llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i') map.drawcoastlines() map.drawstates() map.readshapefile(shapefile1, 'REGIONS') x,y=map(*N.meshgrid(LON,LAT)) plottitle='TSFCmax12' plt.title(plottitle) CS = map.contourf(x,y,MAX12, ticks, cmap=cmap) l,b,w,h =0.1,0.1,0.8,0.8 cax = plt.axes([l+w+0.025, b, 0.025, h]) plt.colorbar(CS,cax=cax, drawedges=True) plt.savefig((os.path.join(OutputFolder, plottitle+'.png'))) plt.show() plt.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: From Robert.Gutmann at dlr.de Wed Mar 19 09:27:05 2014 From: Robert.Gutmann at dlr.de (Robert.Gutmann at dlr.de) Date: Wed, 19 Mar 2014 08:27:05 +0000 Subject: [Tutor] apihelper in dive into python Message-ID: Hi guys, I've got the following problem: I tried to run the example-program apihelper.py in chapter IV of "Dive into Python" and got the following error message: Define the builtin 'help'. This is a wrapper around pydoc.help (with a twist). This is not the Output I expected, however I have no idea how to fix this. Anyone an idea? I am running a Win7 and Python(x,y) 2.7.5.1 Thanks for your help! Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Mar 19 10:16:34 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Mar 2014 09:16:34 +0000 Subject: [Tutor] loop through hours to calc max and plot In-Reply-To: References: Message-ID: On 19/03/14 05:12, questions anon wrote: > I have monthly netcdf files containing hourly temperature data. > I would like to loop through all of the hours and calculate the max for > each hour (00 - 23) and then make a plot. Its hard to give specific help since I don't know the file format and most of your code is using non standard-library modules. A couple of suggestions would be to 1) convert the code into a few functions each doing one specific job. For example the plotting code and the reading code could be separated out. That makes it easier to read the overall program flow and easier to test those individual functions if you change them. 2) You have quite a few redundant or misplaced assignments going on, or things happening inside loops that shouldn't be. Again removing the surplus just makes the rest of the code easier to grasp. > I have found a way for this to work for a couple of the hours (see > below) but it requires a lot of set up to do each hour and I am sure > there must be a simpler way using loops? I also need to find a simpler > way as I would like to eventually do daily for 1st jan to 31st Dec If you put the code into smaller functions that will simplify the design of your bigger program. Each function should have one clear purpose and be as standalone as possible. It should take in the date it needs as parameters and pass back a value. > from netCDF4 import Dataset > import numpy as N > import matplotlib.pyplot as plt > from numpy import ma as ma > from mpl_toolkits.basemap import Basemap > from netcdftime import utime > from datetime import datetime > import os > from matplotlib.collections import LineCollection > > shapefile1="---" > OutputFolder=r"/---/" > fileforlatlon=Dataset("---.nc", 'r+', 'NETCDF4') > LAT=fileforlatlon.variables['latitude'][:] > LON=fileforlatlon.variables['longitude'][:] > > #Set up basemap using mercator projection > map = > Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33,llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i') > x,y=map(*N.meshgrid(LON,LAT)) > map.readshapefile(shapefile1, '-REGIONS') > ncvariablename='T_SFC' > MainFolder=r"/---/" > ticks=[-5,0,5,10,15,20,25,30,35,40,45,50] > Title='Surface Temperature (degrees celsius)' Why aren't these with the other initialization code above? > cmap=plt.cm.jet > all_variabledata=[] > time00=[] > time12=[] Why aren't these with the other initialization code above? > for (path, dirs, files) in os.walk(MainFolder): > for dir in dirs: > print "the dirs are:", dir > path=path+'/' this appears to be in the loop but its the same value each time so you repeat the same assignment over and over. > for ncfile in files: > fileext=ncvariablename+'.nc' > if ncfile.endswith(fileext): > print "dealing with ncfiles:", path+ncfile > ncfile=os.path.join(path,ncfile) > ncfile=Dataset(ncfile, 'r+', 'NETCDF4') > TIME=ncfile.variables['time'][1::] > #variable=ncfile.variables[ncvariablename][:,:,:] > TSFC00=ncfile.variables[ncvariablename][00:01:,:,:] > TSFC12=ncfile.variables[ncvariablename][12:13:,:,:] > fillvalue=ncfile.variables[ncvariablename]._FillValue > ncfile.close() Indentation seems to have gotten lost in email transit. Maybe you didn't post in plain text? > #combine all data from the chosen variable to make one array for analyses > cdftime=utime('seconds since 1970-01-01 00:00:00') > ncfiletime=cdftime.num2date(TIME) > for i in ncfiletime[:]: > ncfiletime=i This is a really bad idea. You are using the same variabvle name to hold the collection you iterate over then reassigning it to the items within the loop. Why not just use i (but use a better name!) within the loop body rather than reassign it? And if you must reassign it use a name other than the one you already used for the collection. Using the same name in two different ways is a recipe for confusion. > timestr=str(ncfiletime) > d = datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S') > date_string = d.strftime('%H')#combine by same hour > print "the ncfiletime is:", ncfiletime > > print "the date_string is:", date_string > if date_string=='00': > time00.append(TSFC00) > elif date_string=='12': > time12.append(TSFC12) > else: > pass > > big_arraytime00=N.ma.concatenate(time00) > big_arraytime12=N.ma.concatenate(time12) > MAX00=big_arraytime00.max(axis=0) > MAX12=big_arraytime12.max(axis=0) > > #plot output summary stats > map = Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33, > llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i') > map.drawcoastlines() > map.drawstates() > map.readshapefile(shapefile1, 'REGIONS') > x,y=map(*N.meshgrid(LON,LAT)) > plottitle='TSFCmax00' another constant assignment that could be in the initialization code section > plt.title(plottitle) > CS = map.contourf(x,y,MAX00, ticks, cmap=cmap) > l,b,w,h =0.1,0.1,0.8,0.8 > cax = plt.axes([l+w+0.025, b, 0.025, h]) > plt.colorbar(CS,cax=cax, drawedges=True) > plt.savefig((os.path.join(OutputFolder, plottitle+'.png'))) > plt.show() > plt.close() > > > map = Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33, > llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i') > map.drawcoastlines() > map.drawstates() > map.readshapefile(shapefile1, 'REGIONS') > > > x,y=map(*N.meshgrid(LON,LAT)) > plottitle='TSFCmax12' > plt.title(plottitle) > CS = map.contourf(x,y,MAX12, ticks, cmap=cmap) > l,b,w,h =0.1,0.1,0.8,0.8 why repeat the previous assignment? > > cax = plt.axes([l+w+0.025, b, 0.025, h]) > plt.colorbar(CS,cax=cax, drawedges=True) > plt.savefig((os.path.join(OutputFolder, plottitle+'.png'))) > plt.show() > plt.close() Note the repetition of the code. Make these lines into a function. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Wed Mar 19 10:28:23 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 19 Mar 2014 10:28:23 +0100 Subject: [Tutor] apihelper in dive into python References: Message-ID: Robert.Gutmann at dlr.de wrote: > Hi guys, > > I've got the following problem: I tried to run the example-program > apihelper.py in chapter IV of "Dive into Python" and got the following > error message: > > Define the builtin 'help'. > This is a wrapper around pydoc.help (with a twist). > > This is not the Output I expected, however I have no idea how to fix this. > Anyone an idea? > > I am running a Win7 and Python(x,y) 2.7.5.1 > > Thanks for your help! > Robert Do you mean the apihelper.py module from http://www.diveintopython.net/download/diveintopython-examples-5.4.zip (comments etc. omitted)? def info(object, spacing=10, collapse=1): """Print methods and doc strings. Takes module, class, list, dictionary, or string.""" methodList = [e for e in dir(object) if callable(getattr(object, e))] processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s) print "\n".join(["%s %s" % (method.ljust(spacing), processFunc(str(getattr(object, method).__doc__))) for method in methodList]) if __name__ == "__main__": print help.__doc__ When you run that as a script it does not invoke the info() function, it just prints help.__doc__ which is what you see. However the code on http://www.diveintopython.net/power_of_introspection/ differs from the above as it prints info.__doc__ instead of help.__doc__. If that's what you expected just change the last line in apihelper.py from print help.__doc__ to print info.__doc__ With this change the script will print the docstring of the info() function: $ python apihelper.py Print methods and doc strings. Takes module, class, list, dictionary, or string. But what apihelper is really meant for is interactive interpreter sessions: >>> import apihelper >>> apihelper.info(42) __abs__ x.__abs__() <==> abs(x) __add__ x.__add__(y) <==> x+y __and__ x.__and__(y) <==> x&y [snip a lot more methods] From tonifuente at yahoo.co.uk Wed Mar 19 13:19:53 2014 From: tonifuente at yahoo.co.uk (Toni Fuente) Date: Wed, 19 Mar 2014 12:19:53 +0000 Subject: [Tutor] How to create a sqlite table schema dynamically Message-ID: <20140319121953.GA9878@macarra> Hello everyone, I am stack with a problem that I can't find a solution: I need to create a sqlite schema dynamically, I've got a dictionary with text keys: "RedHat", "CentOS", "SLES9",..., "etc", "etc" My intention was at the time of creating the table schema run a loop through the dictionary keys and incorporate them to the schema: for os in osDict.items(): cur.execute('''CREATE TABLE mytable(week INTEGER NOT NULL, os TEXT NOT NULL, number INTEGER NOT NULL)''') But I don't know how to pass the os key to the sqlite command. Thank you in advance for any help, Kind regards, -- Toni T?mido Busca..., Bueno No..., Es Igual... Nada. From breamoreboy at yahoo.co.uk Wed Mar 19 16:54:27 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 19 Mar 2014 15:54:27 +0000 Subject: [Tutor] How to create a sqlite table schema dynamically In-Reply-To: <20140319121953.GA9878@macarra> References: <20140319121953.GA9878@macarra> Message-ID: On 19/03/2014 12:19, Toni Fuente wrote: > Hello everyone, > > I am stack with a problem that I can't find a solution: > > I need to create a sqlite schema dynamically, I've got a dictionary with > text keys: "RedHat", "CentOS", "SLES9",..., "etc", "etc" > > My intention was at the time of creating the table schema run a loop > through the dictionary keys and incorporate them to the schema: > > for os in osDict.items(): > cur.execute('''CREATE TABLE mytable(week INTEGER NOT NULL, os TEXT NOT NULL, number INTEGER NOT NULL)''') > > But I don't know how to pass the os key to the sqlite command. > > Thank you in advance for any help, > Kind regards, > > http://docs.python.org/3/library/sqlite3.html#module-sqlite3 the 7th paragraph describes 'parameter substitution' -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From leamhall at gmail.com Wed Mar 19 17:48:00 2014 From: leamhall at gmail.com (leam hall) Date: Wed, 19 Mar 2014 12:48:00 -0400 Subject: [Tutor] How to get file permissions (Python 2.4)? Message-ID: I can use os.chmod('/usr/local/somefile') to change permissions but I haven't been able to find a way to test for file modes. >>> stat.S_IRWXU('/usr/bin/python') Traceback (most recent call last): File "", line 1, in ? TypeError: 'int' object is not callable What should I be looking for? Python 2.4.3 (RHEL 5) Thanks! Leam -- Mind on a Mission From martin at linux-ip.net Wed Mar 19 18:29:30 2014 From: martin at linux-ip.net (Martin A. Brown) Date: Wed, 19 Mar 2014 13:29:30 -0400 Subject: [Tutor] How to get file permissions (Python 2.4)? In-Reply-To: References: Message-ID: Hi there, : I can use os.chmod('/usr/local/somefile') to change permissions : but I haven't been able to find a way to test for file modes. : : >>> stat.S_IRWXU('/usr/bin/python') : Traceback (most recent call last): : File "", line 1, in ? : TypeError: 'int' object is not callable : : What should I be looking for? Python 2.4.3 (RHEL 5) You are using the stat module [0]. You need to get the stat info separately. Here's the first paragraph from the stat module docs: The stat module defines constants and functions for interpreting the results of os.stat(), os.fstat() and os.lstat() (if they exist). For complete details about the stat(), fstat() and lstat() calls, consult the documentation for your system. This looks a bit ugly and error-prone to me, but you could do something like this: stat.S_IRWXU & os.stat('/usr/bin/python').st_mode Better yet? Let os.access() [1] do the bitmath for you: os.access('/usr/bin/python', os.X_OK) Good luck, -Martin [0] http://docs.python.org/2/library/stat.html [1] http://docs.python.org/2/library/os.html#os.access -- Martin A. Brown http://linux-ip.net/ From wprins at gmail.com Wed Mar 19 18:46:25 2014 From: wprins at gmail.com (Walter Prins) Date: Wed, 19 Mar 2014 19:46:25 +0200 Subject: [Tutor] How to get file permissions (Python 2.4)? In-Reply-To: References: Message-ID: Hi On 19 March 2014 18:48, leam hall wrote: > I can use os.chmod('/usr/local/somefile') to change permissions but I > haven't been able to find a way to test for file modes. > >>>> stat.S_IRWXU('/usr/bin/python') > Traceback (most recent call last): > File "", line 1, in ? > TypeError: 'int' object is not callable > > What should I be looking for? Python 2.4.3 (RHEL 5) You're using the stat module as described here: http://docs.python.org/2/library/stat.html The constant stat.S_IRWXU is listed under a section that just to defining the constant, reads: "The following flags can also be used in the mode argument of os.chmod():" Which means, that you can do, for something like: >>> import os >>> import stat >>> os.chmod('/some/file/some/where', stat.S_IRWXU) This has the effect of changing the file mode for the specified file to "read, write, execute" for the user only and is the equivalent of executing 'chmod u+rwx /some/file' or 'chmod 700 /some/file' from the command line. HTH, Walter From johnf at jfcomputer.com Wed Mar 19 18:49:09 2014 From: johnf at jfcomputer.com (John Fabiani) Date: Wed, 19 Mar 2014 10:49:09 -0700 Subject: [Tutor] mixing 64 bit and 32 bit Message-ID: <5329D895.9080902@jfcomputer.com> Hi, At my office we have a mix of XP (32bit) and Window 7 (64 bit). I installed python 64 bit on the windows 7 machines and 32 bit on the XP machines. The question is can the different version run the same code without causing issues. Can the 64 bit use the same byte code as the 32 bit? It seems to be working but I thought best to check. Johnf From reuben.dlink at gmail.com Wed Mar 19 19:01:01 2014 From: reuben.dlink at gmail.com (Reuben) Date: Wed, 19 Mar 2014 23:31:01 +0530 Subject: [Tutor] mixing 64 bit and 32 bit In-Reply-To: <5329D895.9080902@jfcomputer.com> References: <5329D895.9080902@jfcomputer.com> Message-ID: Hi John, The generated bytecodes will be different - but both version can run same code without issues Regards, Reuben On 19-Mar-2014 11:28 PM, "John Fabiani" wrote: > Hi, > > At my office we have a mix of XP (32bit) and Window 7 (64 bit). I > installed python 64 bit on the windows 7 machines and 32 bit on the XP > machines. The question is can the different version run the same code > without causing issues. Can the 64 bit use the same byte code as the 32 > bit? It seems to be working but I thought best to check. > > Johnf > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From johnf at jfcomputer.com Wed Mar 19 20:53:51 2014 From: johnf at jfcomputer.com (John Fabiani) Date: Wed, 19 Mar 2014 12:53:51 -0700 Subject: [Tutor] mixing 64 bit and 32 bit In-Reply-To: References: <5329D895.9080902@jfcomputer.com> Message-ID: <5329F5CF.6090405@jfcomputer.com> Thanks Johnf On 03/19/2014 11:01 AM, Reuben wrote: > > Hi John, > > The generated bytecodes will be different - but both version can run > same code without issues > > Regards, > Reuben > > On 19-Mar-2014 11:28 PM, "John Fabiani" > wrote: > > Hi, > > At my office we have a mix of XP (32bit) and Window 7 (64 bit). I > installed python 64 bit on the windows 7 machines and 32 bit on > the XP machines. The question is can the different version run > the same code without causing issues. Can the 64 bit use the same > byte code as the 32 bit? It seems to be working but I thought > best to check. > > Johnf > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Wed Mar 19 21:32:43 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 19 Mar 2014 13:32:43 -0700 (PDT) Subject: [Tutor] is set/getlocale buggy in OS X? Message-ID: <1395261163.27259.YahooMailNeo@web163802.mail.gq1.yahoo.com> I got several unexpected results using locale.getlocale under OS X. On one computer (not mine) it returned (None, None), even though I used setlocale. Now I am getting the result below on my own computer. Is there a good workaround for this?? Albert-Jans-Mac-Pro:macos albertjan$ uname -a Darwin Albert-Jans-Mac-Pro.local 12.2.0 Darwin Kernel Version 12.2.0: Sat Aug 25 00:48:52 PDT 2012; root:xnu-2050.18.24~1/RELEASE_X86_64 x86_64 Albert-Jans-Mac-Pro:macos albertjan$ python Python 2.7.2 (default, Jun 20 2012, 16:23:33)? [GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import locale >>> locale.setlocale(locale.LC_ALL, "") 'C/UTF-8/C/C/C/C' >>> locale.getlocale() Traceback (most recent call last): ? File "", line 1, in ? File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/locale.py", line 515, in getlocale ? ? return _parse_localename(localename) ? File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/locale.py", line 428, in _parse_localename ? ? raise ValueError, 'unknown locale: %s' % localename ValueError: unknown locale: UTF-8? Thank you! Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc_eymard at hotmail.com Wed Mar 19 21:41:01 2014 From: marc_eymard at hotmail.com (Marc Eymard) Date: Wed, 19 Mar 2014 20:41:01 +0000 Subject: [Tutor] FW: Beginner - list not returning correct variable value In-Reply-To: References: Message-ID: Hello Tutor, Could somebody help me with below query? Thanks Marc From: marc_eymard at hotmail.com To: tutor at python.org Subject: Beginner - list not returning correct variable value Date: Thu, 13 Mar 2014 16:12:28 +0000 Hello Tutor, I am a self-taught Python script beginner and I do it from the Michael Dawson Book. In attached script, can somebody tell me why the values of the variables strenght_points, health_points, wisdom_points and dexterity_points stay at 0 value when 'printing' their value from the list attributes[] when the 'for' loop at the bottom of the script runs. I have commented out the script to highlight what causes me problem. I hope this is clear enough a question. Thanks for your help, Marc -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: Nested_tuple.py Type: text/x-script.phyton Size: 2689 bytes Desc: not available URL: From dyoo at hashcollision.org Wed Mar 19 23:13:44 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 19 Mar 2014 15:13:44 -0700 Subject: [Tutor] FW: Beginner - list not returning correct variable value In-Reply-To: References: Message-ID: Hmm. Did you get Alan's reply six days ago? Here's a link to his reply, just in case you've missed it: https://mail.python.org/pipermail/tutor/2014-March/100580.html From breamoreboy at yahoo.co.uk Wed Mar 19 23:18:26 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 19 Mar 2014 22:18:26 +0000 Subject: [Tutor] FW: Beginner - list not returning correct variable value In-Reply-To: References: Message-ID: On 19/03/2014 20:41, Marc Eymard wrote: > Hello Tutor, > > Could somebody help me with below query? > > Thanks > Marc > > ------------------------------------------------------------------------ > From: marc_eymard at hotmail.com > To: tutor at python.org > Subject: Beginner - list not returning correct variable value > Date: Thu, 13 Mar 2014 16:12:28 +0000 > > Hello Tutor, > > I am a self-taught Python script beginner and I do it from the Michael > Dawson Book. > > In attached script, can somebody tell me why the values of the variables > strenght_points, health_points, wisdom_points and dexterity_points stay > at 0 value when 'printing' their value from the list attributes[] when > the 'for' loop at the bottom of the script runs. > > I have commented out the script to highlight what causes me problem. > > I hope this is clear enough a question. > > Thanks for your help, > Marc > What was wrong with Alan Gauld's reply that was posted on the same day as your original query? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From alan.gauld at btinternet.com Thu Mar 20 02:13:28 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Mar 2014 01:13:28 +0000 Subject: [Tutor] How to get file permissions (Python 2.4)? In-Reply-To: References: Message-ID: On 19/03/14 16:48, leam hall wrote: > I can use os.chmod('/usr/local/somefile') to change permissions but I > haven't been able to find a way to test for file modes. > >>>> stat.S_IRWXU('/usr/bin/python') > Traceback (most recent call last): > File "", line 1, in ? > TypeError: 'int' object is not callable > > What should I be looking for? Python 2.4.3 (RHEL 5) v2.4? Hmm, old. I think this is still valid tho'.... Look in the os.path module for a bunch of mode/access test functions for common tests. Or os.access() takes a filename and flag variable (one of os.F_OK, os.R_OK, os.W_OK, and os.X_OK) which returns a Boolean result depending on whether the file exists, is readable, writable or executable respectively. Alternatively use os.stat() and treat the mode attribute result as a bitmask using the stat flags HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Thu Mar 20 02:15:21 2014 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 20 Mar 2014 01:15:21 +0000 (GMT) Subject: [Tutor] loop through hours to calc max and plot In-Reply-To: References: Message-ID: <1395278121.42947.YahooMailNeo@web186003.mail.ir2.yahoo.com> Forwarding to the list. Use ReplyAll when responding to ensure maximum responses. ? Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos >________________________________ > From: questions anon >To: Alan Gauld >Sent: Wednesday, 19 March 2014, 22:30 >Subject: Re: [Tutor] loop through hours to calc max and plot > > > >Could you please give an example of how to put these into a loop in a function and create the matching naming conventions? > > > > >On Thu, Mar 20, 2014 at 8:07 AM, questions anon wrote: > >Thank you for your response it is very helpful. >> >> >> >> >> >>On Wed, Mar 19, 2014 at 8:16 PM, Alan Gauld wrote: >> >>On 19/03/14 05:12, questions anon wrote: >>> >>> >>>I have monthly netcdf files containing hourly temperature data. >>>>I would like to loop through all of the hours and calculate the max for >>>>each hour (00 - 23) and then make a plot. >>>> >>> Its hard to give specific help since I don't know the file format >>>and most of your code is using non standard-library modules. >>> >>>A couple of suggestions would be to >>>1) convert the code into a few functions each doing one >>>? ?specific job. For example the plotting code and the >>>? ?reading code could be separated out. That makes it >>>? ?easier to read the overall program flow and easier >>>? ?to test those individual functions if you change them. >>>2) You have quite a few redundant or misplaced assignments >>>? ?going on, or things happening inside loops that >>>? ?shouldn't be. Again removing the surplus just makes >>>? ?the rest of the code easier to grasp. >>> >>> >>> >>>I have found a way for this to work for a couple of the hours (see >>>>below) but it requires a lot of set up to do each hour and I am sure >>>>there must be a simpler way using loops? I also need to find a simpler >>>>way as I would like to eventually do daily for 1st jan to 31st Dec >>>> >>> If you put the code into smaller functions that will simplify the design of your bigger program. Each function should have one clear purpose and be as standalone as possible. It should take in the >>>date it needs as parameters and pass back a value. >>> >>> >>> >>> >>>from netCDF4 import Dataset >>>>import numpy as N >>>>import matplotlib.pyplot as plt >>>>from numpy import ma as ma >>>>from mpl_toolkits.basemap import Basemap >>>>from netcdftime import utime >>>>from datetime import datetime >>>>import os >>>>from matplotlib.collections import LineCollection >>>> >>>>shapefile1="---" >>>>OutputFolder=r"/---/" >>>>fileforlatlon=Dataset("---.nc", 'r+', 'NETCDF4') >>>>LAT=fileforlatlon.variables['latitude'][:] >>>>LON=fileforlatlon.variables['longitude'][:] >>>> >>>>#Set up basemap using mercator projection >>>> >>> >>>map = >>>>Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33,llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i') >>>>x,y=map(*N.meshgrid(LON,LAT)) >>>>map.readshapefile(shapefile1, '-REGIONS') >>>> >>> >>>ncvariablename='T_SFC' >>>>MainFolder=r"/---/" >>>>ticks=[-5,0,5,10,15,20,25,30,35,40,45,50] >>>>Title='Surface Temperature (degrees celsius)' >>>> >>> Why aren't these with the other initialization code above? >>> >>> >>>cmap=plt.cm.jet >>>> >>> >>> >>>all_variabledata=[] >>>>time00=[] >>>>time12=[] >>>> >>>Why aren't these with the other initialization code above? >>> >>> >>> >>>for (path, dirs, files) in os.walk(MainFolder): >>>>for dir in dirs: >>>>print "the dirs are:", dir >>>>path=path+'/' >>>> >>> this appears to be in the loop but its the same >>>value each time so you repeat the same assignment >>>over and over. >>> >>> >>> >>> >>>for ncfile in files: >>>>fileext=ncvariablename+'.nc' >>>>if ncfile.endswith(fileext): >>>>print "dealing with ncfiles:", path+ncfile >>>>ncfile=os.path.join(path,ncfile) >>>>ncfile=Dataset(ncfile, 'r+', 'NETCDF4') >>>>TIME=ncfile.variables['time'][1::] >>>>#variable=ncfile.variables[ncvariablename][:,:,:] >>>>TSFC00=ncfile.variables[ncvariablename][00:01:,:,:] >>>>TSFC12=ncfile.variables[ncvariablename][12:13:,:,:] >>>>fillvalue=ncfile.variables[ncvariablename]._FillValue >>>>ncfile.close() >>>> >>> Indentation seems to have gotten lost in email transit. >>>Maybe you didn't post in plain text? >>> >>> >>> >>> >>>#combine all data from the chosen variable to make one array for analyses >>>>cdftime=utime('seconds since 1970-01-01 00:00:00') >>>>ncfiletime=cdftime.num2date(TIME) >>>>for i in ncfiletime[:]: >>>>ncfiletime=i >>>> >>> This is a really bad idea. You are using the same variabvle name to hold the collection you iterate over then reassigning it to the items within the loop. Why not just use i (but use a better name!) within >>>the loop body rather than reassign it? >>> >>>And if you must reassign it use a name other than the one you already used for the collection. Using the same name in two different ways >>>is a recipe for confusion. >>> >>> >>> >>>timestr=str(ncfiletime) >>>>d = datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S') >>>>date_string = d.strftime('%H')#combine by same hour >>>>print "the ncfiletime is:", ncfiletime >>>> >>>>print "the date_string is:", date_string >>>>if date_string=='00': >>>>time00.append(TSFC00) >>>>elif date_string=='12': >>>>time12.append(TSFC12) >>>>else: >>>>pass >>>> >>>>big_arraytime00=N.ma.concatenate(time00) >>>>big_arraytime12=N.ma.concatenate(time12) >>>>MAX00=big_arraytime00.max(axis=0) >>>>MAX12=big_arraytime12.max(axis=0) >>>> >>>>#plot output summary stats >>>>map = Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33, >>>>llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i') >>>>map.drawcoastlines() >>>>map.drawstates() >>>>map.readshapefile(shapefile1, 'REGIONS') >>>>x,y=map(*N.meshgrid(LON,LAT)) >>>>plottitle='TSFCmax00' >>>> >>> another constant assignment that could be in the >>>initialization code section >>> >>> >>> >>>plt.title(plottitle) >>>>CS = map.contourf(x,y,MAX00, ticks, cmap=cmap) >>>> >>> >>>l,b,w,h =0.1,0.1,0.8,0.8 >>>>cax = plt.axes([l+w+0.025, b, 0.025, h]) >>>>plt.colorbar(CS,cax=cax, drawedges=True) >>>>plt.savefig((os.path.join(OutputFolder, plottitle+'.png'))) >>>>plt.show() >>>>plt.close() >>>> >>>> >>>>map = Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33, >>>>llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i') >>>>map.drawcoastlines() >>>>map.drawstates() >>>>map.readshapefile(shapefile1, 'REGIONS') >>>> >>>> >>>>x,y=map(*N.meshgrid(LON,LAT)) >>>>plottitle='TSFCmax12' >>>>plt.title(plottitle) >>>>CS = map.contourf(x,y,MAX12, ticks, cmap=cmap) >>>>l,b,w,h =0.1,0.1,0.8,0.8 >>>> >>> why repeat the previous assignment? >>> >>> >>> >>> >>>>cax = plt.axes([l+w+0.025, b, 0.025, h]) >>>>plt.colorbar(CS,cax=cax, drawedges=True) >>>>plt.savefig((os.path.join(OutputFolder, plottitle+'.png'))) >>>>plt.show() >>>>plt.close() >>>> >>> Note the repetition of the code. Make these lines >>>into a function. >>> >>> >>>HTH >>>-- >>>Alan G >>>Author of the Learn to Program web site >>>http://www.alan-g.me.uk/ >>>http://www.flickr.com/photos/alangauldphotos >>> >>>_______________________________________________ >>>Tutor maillist ?- ?Tutor at python.org >>>To unsubscribe or change subscription options: >>>https://mail.python.org/mailman/listinfo/tutor >>> >> > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Mar 20 02:33:20 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 20 Mar 2014 12:33:20 +1100 Subject: [Tutor] How to get file permissions (Python 2.4)? In-Reply-To: References: Message-ID: <20140320013320.GR16526@ando> On Thu, Mar 20, 2014 at 01:13:28AM +0000, Alan Gauld wrote: > On 19/03/14 16:48, leam hall wrote: > >I can use os.chmod('/usr/local/somefile') to change permissions but I > >haven't been able to find a way to test for file modes. > > > >>>>stat.S_IRWXU('/usr/bin/python') > >Traceback (most recent call last): > > File "", line 1, in ? > >TypeError: 'int' object is not callable > > > >What should I be looking for? Python 2.4.3 (RHEL 5) > > v2.4? Hmm, old. I think this is still valid tho'.... 2.4 is old, but it's still supported by Red Hat Enterprise Linux, so it will be around for a few more years. -- Steven From tonifuente at yahoo.co.uk Thu Mar 20 15:19:41 2014 From: tonifuente at yahoo.co.uk (Toni Fuente) Date: Thu, 20 Mar 2014 14:19:41 +0000 Subject: [Tutor] How to create a sqlite table schema dynamically In-Reply-To: References: <20140319121953.GA9878@macarra> Message-ID: <20140320141941.GA3111@macarra> * Mark Lawrence [2014-03-19 15:54:27 +0000]: > On 19/03/2014 12:19, Toni Fuente wrote: > >Hello everyone, > > > >I am stack with a problem that I can't find a solution: > > > >I need to create a sqlite schema dynamically, I've got a dictionary with > >text keys: "RedHat", "CentOS", "SLES9",..., "etc", "etc" > > > >My intention was at the time of creating the table schema run a loop > >through the dictionary keys and incorporate them to the schema: > > > >for os in osDict.items(): > > cur.execute('''CREATE TABLE mytable(week INTEGER NOT NULL, os TEXT NOT NULL, number INTEGER NOT NULL)''') > > > >But I don't know how to pass the os key to the sqlite command. > > > >Thank you in advance for any help, > >Kind regards, > > > > > > http://docs.python.org/3/library/sqlite3.html#module-sqlite3 the 7th > paragraph describes 'parameter substitution' > > -- > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > > Mark Lawrence > Thank you Mark. I forgot to say that I am using python 2.4.3, but that helped me. -- Toni Por los defectos de los dem?s el sabio corrige los propios. -- Publio Siro. From tonifuente at yahoo.co.uk Thu Mar 20 15:46:53 2014 From: tonifuente at yahoo.co.uk (Toni Fuente) Date: Thu, 20 Mar 2014 14:46:53 +0000 Subject: [Tutor] String with literal %s Message-ID: <20140320144653.GB3111@macarra> Hi again, I am trying to create a string this way: insertion = "INSERT INTO mytable(week %s) VALUES (\%s, \%s)" % osStringI not enough arguments for format string Where the first %s is going to be substitute by the variable osStringI, but the other two VALUES (\%s, \%s), should be created as literals '%s'. How can I do that? Regards, -- Toni When your work speaks for itself, don't interrupt. -- Henry J. Kaiser From bgailer at gmail.com Thu Mar 20 16:38:47 2014 From: bgailer at gmail.com (bob gailer) Date: Thu, 20 Mar 2014 11:38:47 -0400 Subject: [Tutor] How to create a sqlite table schema dynamically In-Reply-To: <20140319121953.GA9878@macarra> References: <20140319121953.GA9878@macarra> Message-ID: <532B0B87.5020405@gmail.com> On 3/19/2014 8:19 AM, Toni Fuente wrote: > Hello everyone, > > I am stack with a problem that I can't find a solution: > > I need to create a sqlite schema dynamically, I've got a dictionary with > text keys: "RedHat", "CentOS", "SLES9",..., "etc", "etc" > > My intention was at the time of creating the table schema run a loop > through the dictionary keys and incorporate them to the schema: > > for os in osDict.items(): > cur.execute('''CREATE TABLE mytable(week INTEGER NOT NULL, os TEXT NOT NULL, number INTEGER NOT NULL)''') IMHO you are mixing data with column names. Usually the column name in this case would be just os. What is your use case for this? > But I don't know how to pass the os key to the sqlite command. > > Thank you in advance for any help, > Kind regards, > > From akleider at sonic.net Thu Mar 20 17:02:41 2014 From: akleider at sonic.net (Alex Kleider) Date: Thu, 20 Mar 2014 09:02:41 -0700 Subject: [Tutor] String with literal %s In-Reply-To: <20140320144653.GB3111@macarra> References: <20140320144653.GB3111@macarra> Message-ID: On 2014-03-20 07:46, Toni Fuente wrote: > Hi again, > > I am trying to create a string this way: > > insertion = "INSERT INTO mytable(week %s) VALUES (\%s, \%s)" % > osStringI > > not enough arguments for format string > > Where the first %s is going to be substitute by the variable osStringI, > but the other two VALUES (\%s, \%s), should be created as literals > '%s'. > > How can I do that? > > Regards, Would insertion = "INSERT INTO mytable(week %s) VALUES (\%s, \%s)" % (osStringI, literal1, literal2, ) not work? ..assuming you have first created the two literals, if I understand you correctly. .. although I understand that this type of string formatting in the SQL context exposes one to security vulnerabilities if there is the potential for data to be coming from potentially unfriendly parties. From alan.gauld at btinternet.com Thu Mar 20 17:18:35 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Mar 2014 16:18:35 +0000 Subject: [Tutor] String with literal %s In-Reply-To: <20140320144653.GB3111@macarra> References: <20140320144653.GB3111@macarra> Message-ID: On 20/03/14 14:46, Toni Fuente wrote: > I am trying to create a string this way: > > insertion = "INSERT INTO mytable(week %s) VALUES (\%s, \%s)" % osStringI > > not enough arguments for format string > > Where the first %s is going to be substitute by the variable osStringI, > but the other two VALUES (\%s, \%s), should be created as literals '%s'. If you double the % sign it is treated as a percent character. "INSERT INTO mytable(week %s) VALUES (%%s, %%s)" But do you really want to do it this way? Wouldn't it be better to use the SQLite parameter insertion syntax and do it all at the execute stage? cur.execute("INSERT INTO mytable(week ?) VALUES (?, ?)", val1,val2,val3) just a thought, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From tonifuente at yahoo.co.uk Thu Mar 20 18:31:32 2014 From: tonifuente at yahoo.co.uk (Toni Fuente) Date: Thu, 20 Mar 2014 17:31:32 +0000 Subject: [Tutor] How to create a sqlite table schema dynamically In-Reply-To: <532B0B87.5020405@gmail.com> References: <20140319121953.GA9878@macarra> <532B0B87.5020405@gmail.com> Message-ID: <20140320173132.GC3111@macarra> * bob gailer [2014-03-20 11:38:47 -0400]: > On 3/19/2014 8:19 AM, Toni Fuente wrote: > >Hello everyone, > > > >I am stack with a problem that I can't find a solution: > > > >I need to create a sqlite schema dynamically, I've got a dictionary with > >text keys: "RedHat", "CentOS", "SLES9",..., "etc", "etc" > > > >My intention was at the time of creating the table schema run a loop > >through the dictionary keys and incorporate them to the schema: > > > >for os in osDict.items(): > > cur.execute('''CREATE TABLE mytable(week INTEGER NOT NULL, os TEXT NOT NULL, number INTEGER NOT NULL)''') > IMHO you are mixing data with column names. Usually the column name > in this case would be just os. > > What is your use case for this? I'll try to explain: This is a kind of little job/exercise, to learn some python. I got a database from where I get the data that I am going to process, and create a dictionary osDict. This dictionary has the form of: osDict = {'CentOS v4.x': 10, 'Linux OS': 5, 'Redhat Enterprise 4': 7} I want to create a weekly report in form of a csv or a spreadsheet file, with the quantity of different OS that have been installed, and store it in a sqlite database. So the table schema for the sqlite database would be: for os in osDict: osString += ', ' + '"' + os + '"' + ' TEXT NOT NULL' schema = "CREATE TABLE newOS(week INTEGER NOT NULL%s)" % osString Now I can create the table: cur.execute("%s" % schema) My next step is to fill up the sqlite table with data, and that was about my next email to the list with subject "String with literal %s". Thanks to Alan Gauld now I know how to add those literal %s. for os in osDict: osStringI += ', ' + '"' + os + '"' insertion = "INSERT INTO newOS(week%s) VALUES (%%s, %%s)" % osStringI Now I should be able to populate the table, I am now in this stage, so I haven't tried now but this is the code: for os in osDict: cur.execute("%s" % insertion ... mmmhh how do I key in now the values? my idea was to do something like this: for os in osDict: cur.execute("%s" % insertion which will expand to: "INSERT INTO newOS(week, "Redhat Enterprise 4", "Linux OS", "CentOS v4.x") VALUES (%s, %s)" , (weekNumber, osDict[os]) Where weekNumber = datetime.date.today().isocalendar()[1] and osDict[os] the number of OS installed of each one. But yes, now I can see new problems, and here is where I am at the moment. Any advise is very welcome. -- Toni Ninguna palabra asoma a mis labios sin que haya estado primero en mi coraz?n. -- Andre Gide. (1869-1951) Escritor franc?s. From tonifuente at yahoo.co.uk Thu Mar 20 18:34:31 2014 From: tonifuente at yahoo.co.uk (Toni Fuente) Date: Thu, 20 Mar 2014 17:34:31 +0000 Subject: [Tutor] String with literal %s In-Reply-To: References: <20140320144653.GB3111@macarra> Message-ID: <20140320173431.GD3111@macarra> * Alex Kleider [2014-03-20 09:02:41 -0700]: > On 2014-03-20 07:46, Toni Fuente wrote: > >Hi again, > > > >I am trying to create a string this way: > > > >insertion = "INSERT INTO mytable(week %s) VALUES (\%s, \%s)" % > >osStringI > > > >not enough arguments for format string > > > >Where the first %s is going to be substitute by the variable osStringI, > >but the other two VALUES (\%s, \%s), should be created as literals > >'%s'. > > > >How can I do that? > > > >Regards, > > > Would > insertion = "INSERT INTO mytable(week %s) VALUES (\%s, \%s)" % > (osStringI, literal1, literal2, ) > not work? ..assuming you have first created the two literals, if I > understand you correctly. > .. although I understand that this type of string formatting in the > SQL context exposes one to security vulnerabilities if there is the > potential for data to be coming from potentially unfriendly parties. Hi Alex, What I was trying to find is what Alan Gauld has suggested the literal %s, %s. Security at this point is not a concern, is just a python exercise. Thank you anyway :-) -- Toni I poured spot remover on my dog. Now he's gone. -- Steven Wright From tonifuente at yahoo.co.uk Thu Mar 20 18:38:02 2014 From: tonifuente at yahoo.co.uk (Toni Fuente) Date: Thu, 20 Mar 2014 17:38:02 +0000 Subject: [Tutor] String with literal %s In-Reply-To: References: <20140320144653.GB3111@macarra> Message-ID: <20140320173802.GE3111@macarra> * Alan Gauld [2014-03-20 16:18:35 +0000]: > On 20/03/14 14:46, Toni Fuente wrote: > > >I am trying to create a string this way: > > > >insertion = "INSERT INTO mytable(week %s) VALUES (\%s, \%s)" % osStringI > > > >not enough arguments for format string > > > >Where the first %s is going to be substitute by the variable osStringI, > >but the other two VALUES (\%s, \%s), should be created as literals '%s'. > > > If you double the % sign it is treated as a percent character. > > "INSERT INTO mytable(week %s) VALUES (%%s, %%s)" > > But do you really want to do it this way? > Wouldn't it be better to use the SQLite parameter insertion syntax > and do it all at the execute stage? > > cur.execute("INSERT INTO mytable(week ?) VALUES (?, ?)", val1,val2,val3) > > just a thought, Thank you Alan, that is what I was trying to achieve (%%s) I forgot to mention that I am using python 2.4. And here is what I am trying to do for the bigger picture: This is a kind of little job/exercise, to learn some python. I got a database from where I get the data that I am going to process, and create a dictionary osDict. This dictionary has the form of: osDict = {'CentOS v4.x': 10, 'Linux OS': 5, 'Redhat Enterprise 4': 7} I want to create a weekly report in form of a csv or a spreadsheet file, with the quantity of different OS that have been installed, and store it in a sqlite database. So the table schema for the sqlite database would be: for os in osDict: osString += ', ' + '"' + os + '"' + ' TEXT NOT NULL' schema = "CREATE TABLE newOS(week INTEGER NOT NULL%s)" % osString Now I can create the table: cur.execute("%s" % schema) My next step is to fill up the sqlite table with data, and that was about my next email to the list with subject "String with literal %s". Thanks to Alan Gauld now I know how to add those literal %s. for os in osDict: osStringI += ', ' + '"' + os + '"' insertion = "INSERT INTO newOS(week%s) VALUES (%%s, %%s)" % osStringI Now I should be able to populate the table, I am now in this stage, so I haven't tried now but this is the code: for os in osDict: cur.execute("%s" % insertion ... mmmhh how do I key in now the values? my idea was to do something like this: for os in osDict: cur.execute("%s" % insertion which will expand to: "INSERT INTO newOS(week, "Redhat Enterprise 4", "Linux OS", "CentOS v4.x") VALUES (%s, %s)" , (weekNumber, osDict[os]) Where weekNumber = datetime.date.today().isocalendar()[1] and osDict[os] the number of OS installed of each one. But yes, now I can see new problems, and here is where I am at the moment. Any advise is very welcome. -- Toni A prig is a fellow who is always making you a present of his opinions. -- George Eliot From alan.gauld at btinternet.com Thu Mar 20 20:27:57 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Mar 2014 19:27:57 +0000 Subject: [Tutor] How to create a sqlite table schema dynamically In-Reply-To: <20140320173132.GC3111@macarra> References: <20140319121953.GA9878@macarra> <532B0B87.5020405@gmail.com> <20140320173132.GC3111@macarra> Message-ID: On 20/03/14 17:31, Toni Fuente wrote: > I got a database from where I get the data that I am going to process, > and create a dictionary osDict. This dictionary has the form of: > > osDict = {'CentOS v4.x': 10, 'Linux OS': 5, 'Redhat Enterprise 4': 7} > > I want to create a weekly report in form of a csv or a spreadsheet file, > with the quantity of different OS that have been installed, and store it > in a sqlite database. > > So the table schema for the sqlite database would be: > > for os in osDict: > osString += ', ' + '"' + os + '"' + ' TEXT NOT NULL' > > schema = "CREATE TABLE newOS(week INTEGER NOT NULL%s)" % osString > > Now I can create the table: > > cur.execute("%s" % schema) You should never do this, it is a huge security hole and even if you are not opening it up to outside access you should still avoid it as bad practice. Instead use the SQLite executes own parameter mechanism. Use a question mark instead of %s and pass the values into the execute() > My next step is to fill up the sqlite table with data, and that was > about my next email to the list with subject "String with literal %s". I confess I'm still not clear on your schema. What should the populated table(s) look like? It all feels very un-SQL like to me. > insertion = "INSERT INTO newOS(week%s) VALUES (%%s, %%s)" % osStringI > > Now I should be able to populate the table, I am now in this stage, so I > haven't tried now but this is the code: > > for os in osDict: > cur.execute("%s" % insertion ... mmmhh how do I key in now the > values? You use ? in your insert string: insertion = "INSERT INTO newOS(week%s) VALUES (?, ?)" % osStringI for os in osDict: cur.execute(insertion, val1,val2) > for os in osDict: > cur.execute("%s" % insertion which will expand to: > "INSERT INTO newOS(week, "Redhat Enterprise 4", "Linux OS", "CentOS v4.x") VALUES (%s, %s)" , (weekNumber, osDict[os]) > This is whee I'm confused. You have a single table, newOS with 4 columns. And you are trying to insert only two values? Its not valid SQL. I would expect your table to have only 3 columns: week, Name, quantity. and the insert to be like insert into os(week, name quantity) values(weekNumber, os, osDict[os]) > Where weekNumber = datetime.date.today().isocalendar()[1] > and osDict[os] the number of OS installed of each one. You then run your report with something like select name, count from os where week == '15' or somesuch -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Thu Mar 20 22:56:53 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 20 Mar 2014 22:56:53 +0100 Subject: [Tutor] How to create a sqlite table schema dynamically References: <20140319121953.GA9878@macarra> <532B0B87.5020405@gmail.com> <20140320173132.GC3111@macarra> Message-ID: Alan Gauld wrote: > I confess I'm still not clear on your schema. What should the populated > table(s) look like? It all feels very un-SQL like to me. I'll make a bold guess that he wants to make a pivot table, something that is indeed not supported by sqlite. E. g., start with week | os | installs -------- | -------- | -------- 2014-01 | redhat | 5 2014-01 | suse | 2 2014-02 | debian | 2 2014-02 | redhat | 7 2014-03 | suse | 3 2014-03 | ubuntu | 3 2014-03 | mint | 1 and wield it into something like week | debian | mint | redhat | suse | ubuntu -------- | -------- | -------- | -------- | -------- | -------- 2014-01 | 0 | 0 | 5 | 2 | 0 2014-02 | 2 | 0 | 7 | 0 | 0 2014-03 | 0 | 1 | 0 | 3 | 3 Below is my attempt: import sqlite3 db = sqlite3.connect(":memory:") cs = db.cursor() data = [ # week, os, installs ("2014-01", "redhat", 5), ("2014-01", "suse", 2), ("2014-02", "debian", 2), ("2014-02", "redhat", 7), ("2014-03", "suse", 3), ("2014-03", "ubuntu", 3), ("2014-03", "mint", 1), ] def print_row(row, space=" "): print(" | ".join(str(field).ljust(8, space) for field in row)) def show(sql): first = True for row in cs.execute(sql): if first: print_row(d[0] for d in cs.description) print_row(("" for d in cs.description), "-") first = False print_row(row) print("") def sanitized(name): """Prevent SQL injection""" if not name.isalpha(): # XXX a tad too rigid raise ValueError("Illegal name {!r}".format(name)) return name cs.execute("create table weekly_installs (week, os, installs);") cs.executemany( "insert into weekly_installs " "(week, os, installs) values (?, ?, ?)", data) show("select * from weekly_installs") distros = sorted( sanitized(distro) for [distro] in cs.execute("select distinct os from weekly_installs")) cs.execute("create table pivot (week, {})".format( ", ".join(d + " default 0" for d in distros))) cs.executemany( "insert into pivot (week) values (?)", cs.execute("select distinct week from weekly_installs").fetchall()) for distro in distros: update = "update pivot set {distro} = ? where week = ?" update = update.format(distro=distro) lookup = ("select installs, week from weekly_installs " "where os = '{distro}'") lookup = lookup.format(distro=distro) cs.executemany(update, cs.execute(lookup).fetchall()) show("select * from pivot order by week") OK, it still may serve as a bad example ;) Doing it in Python should be much cleaner, but I'll leave that as an exercise... From tonifuente at yahoo.co.uk Thu Mar 20 23:39:18 2014 From: tonifuente at yahoo.co.uk (Toni Fuente) Date: Thu, 20 Mar 2014 22:39:18 +0000 Subject: [Tutor] How to create a sqlite table schema dynamically In-Reply-To: References: <20140319121953.GA9878@macarra> <532B0B87.5020405@gmail.com> <20140320173132.GC3111@macarra> Message-ID: <20140320223918.GF3111@macarra> * Alan Gauld [2014-03-20 19:27:57 +0000]: > On 20/03/14 17:31, Toni Fuente wrote: > > >I got a database from where I get the data that I am going to process, > >and create a dictionary osDict. This dictionary has the form of: > > > >osDict = {'CentOS v4.x': 10, 'Linux OS': 5, 'Redhat Enterprise 4': 7} > > > >I want to create a weekly report in form of a csv or a spreadsheet file, > >with the quantity of different OS that have been installed, and store it > >in a sqlite database. > > > >So the table schema for the sqlite database would be: > > > >for os in osDict: > > osString += ', ' + '"' + os + '"' + ' TEXT NOT NULL' > > > >schema = "CREATE TABLE newOS(week INTEGER NOT NULL%s)" % osString > > > >Now I can create the table: > > > >cur.execute("%s" % schema) > > You should never do this, it is a huge security hole and even if you > are not opening it up to outside access you should still avoid it as > bad practice. > > Instead use the SQLite executes own parameter mechanism. > Use a question mark instead of %s and pass the values > into the execute() > Ok, I see, I'll use SQLite own parameter then. > >My next step is to fill up the sqlite table with data, and that was > >about my next email to the list with subject "String with literal %s". > > I confess I'm still not clear on your schema. What should the > populated table(s) look like? It all feels very un-SQL like to me. It would be like this: Week, Redhat, CentOS 6, CentOS 5, Debian Squeeze, Debian Whezzy, ..., Ubuntu, Solaris, Windows XP, Windows 7 13 4 6 5 3 5 8 4 4 8 14 3 7 4 3 5 7 4 4 4 15 I want to generated the columns dynamically from that dictionary, osDict, that I've created collecting data from an outside database: osDict = {'Redhat': 4, 'CentOS 6': 6, 'CentOS 5': 5,..., 'Windows 7': 8} This osDict will have different values every week that I run the script and grab the data from the external database, the keys (OS) will be the same. What I want to do is create the schema dynamically, without keying in all the different operating systems. > >insertion = "INSERT INTO newOS(week%s) VALUES (%%s, %%s)" % osStringI > > > >Now I should be able to populate the table, I am now in this stage, so I > >haven't tried now but this is the code: > > > >for os in osDict: > > cur.execute("%s" % insertion ... mmmhh how do I key in now the > > values? > > You use ? in your insert string: > > insertion = "INSERT INTO newOS(week%s) VALUES (?, ?)" % osStringI > > for os in osDict: > cur.execute(insertion, val1,val2) I thought I wouldn't be able to use SQLite own parameter with python 2.4, but I will give it a try, and if I can't, I will found a place sqlite3 module. > >for os in osDict: > > cur.execute("%s" % insertion which will expand to: > > "INSERT INTO newOS(week, "Redhat Enterprise 4", "Linux OS", "CentOS v4.x") VALUES (%s, %s)" , (weekNumber, osDict[os]) > > > > This is whee I'm confused. > > You have a single table, newOS with 4 columns. And you are trying to > insert only two values? Its not valid SQL. It will have more than four values and my intention was that it would go through a loop that will put the values into the different OS columns, which just one row for each week. As the description above. I think I am trying to build the table as I want the report to look like. Is it the wrong way to create this table? > I would expect your table to have only 3 columns: > > week, Name, quantity. > > and the insert to be like > > insert into os(week, name quantity) values(weekNumber, os, osDict[os]) If you think this is the right way to approach this problem I'll do it like that. My first intention was to explore how to create dynamically the schema. > >Where weekNumber = datetime.date.today().isocalendar()[1] > >and osDict[os] the number of OS installed of each one. > > > You then run your report with something like > > select name, count from os > where week == '15' > > or somesuch Aha, and then produce the report in the way, that I am trying to build the table? Week, Redhat, CentOS 6, CentOS 5, Debian Squeeze, Debian Whezzy, ..., Ubuntu, Solaris, Windows XP, Windows 7 13 4 6 5 3 5 8 4 4 8 14 3 7 4 3 5 7 4 4 4 > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos Regards, -- Toni Well, O.K. I'll compromise with my principles because of EXISTENTIAL DESPAIR! From artcaton at gmail.com Thu Mar 20 23:43:02 2014 From: artcaton at gmail.com (Art Caton) Date: Thu, 20 Mar 2014 18:43:02 -0400 Subject: [Tutor] PLEASE remove me from your e-mailing list Message-ID: ArtCaton at Gmail.com no longer requests your "Tutor Request" e-mailings -------------- next part -------------- An HTML attachment was scrubbed... URL: From tonifuente at yahoo.co.uk Thu Mar 20 23:57:03 2014 From: tonifuente at yahoo.co.uk (Toni Fuente) Date: Thu, 20 Mar 2014 22:57:03 +0000 Subject: [Tutor] PLEASE remove me from your e-mailing list In-Reply-To: References: Message-ID: <20140320225703.GG3111@macarra> * Art Caton [2014-03-20 18:43:02 -0400]: > Date: Thu, 20 Mar 2014 18:43:02 -0400 > From: Art Caton > To: Tutor at python.org > Subject: [Tutor] PLEASE remove me from your e-mailing list > Message-ID: > > ArtCaton at Gmail.com no longer requests your "Tutor Request" e-mailings > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor Hi Art, You can change your subscription status yourself following this link: Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -- Toni Johnson's law: Systems resemble the organizations that create them. From ben+python at benfinney.id.au Thu Mar 20 23:59:01 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 21 Mar 2014 09:59:01 +1100 Subject: [Tutor] PLEASE remove me from your e-mailing list References: Message-ID: <85txassci2.fsf@benfinney.id.au> Art Caton writes: > ArtCaton at Gmail.com no longer requests your "Tutor Request" e-mailings Every message from the ?tutor? mailing list has instructions at the bottom for unsubscribing. We, fellow members, cannot do it for you. -- \ ?There's no excuse to be bored. Sad, yes. Angry, yes. | `\ Depressed, yes. Crazy, yes. But there's no excuse for boredom, | _o__) ever.? ?Viggo Mortensen | Ben Finney From emile at fenx.com Fri Mar 21 00:10:15 2014 From: emile at fenx.com (Emile van Sebille) Date: Thu, 20 Mar 2014 16:10:15 -0700 Subject: [Tutor] PLEASE remove me from your e-mailing list In-Reply-To: References: Message-ID: We can't take you off the list -- see the line below that says: To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor Emile On 3/20/2014 3:43 PM, Art Caton wrote: > ArtCaton at Gmail.com no longer requests your "Tutor Request" e-mailings > > > _______________________________________________ > 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 Mar 21 00:48:39 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 21 Mar 2014 10:48:39 +1100 Subject: [Tutor] String with literal %s In-Reply-To: References: <20140320144653.GB3111@macarra> Message-ID: <20140320234839.GT16526@ando> On Thu, Mar 20, 2014 at 04:18:35PM +0000, Alan Gauld wrote: > On 20/03/14 14:46, Toni Fuente wrote: > > >I am trying to create a string this way: > > > >insertion = "INSERT INTO mytable(week %s) VALUES (\%s, \%s)" % osStringI Don't do this! The world has far too many software vulnerable to code injection attacks already, please don't add another one! When you hear about the latest virus or malware that infects computers, they nearly always are due to a programmer messing up by writing buggy code. In this case, using % to build up SQL queries is a classic example of buggy code that is vulnerable to code injection. http://xkcd.com/327/ http://bobby-tables.com/python.html > >not enough arguments for format string > > > >Where the first %s is going to be substitute by the variable osStringI, > >but the other two VALUES (\%s, \%s), should be created as literals '%s'. > > > If you double the % sign it is treated as a percent character. > > "INSERT INTO mytable(week %s) VALUES (%%s, %%s)" > > But do you really want to do it this way? > Wouldn't it be better to use the SQLite parameter insertion syntax > and do it all at the execute stage? It certainly would! > cur.execute("INSERT INTO mytable(week ?) VALUES (?, ?)", val1,val2,val3) > > just a thought, A very good thought. -- Steven From alan.gauld at btinternet.com Fri Mar 21 00:56:47 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Mar 2014 23:56:47 +0000 Subject: [Tutor] How to create a sqlite table schema dynamically In-Reply-To: <20140320223918.GF3111@macarra> References: <20140319121953.GA9878@macarra> <532B0B87.5020405@gmail.com> <20140320173132.GC3111@macarra> <20140320223918.GF3111@macarra> Message-ID: On 20/03/14 22:39, Toni Fuente wrote: >> I would expect your table to have only 3 columns: >> >> week, Name, quantity. >> >> You then run your report with something like >> >> select name, count from os >> where week == '15' >> > Aha, and then produce the report in the way, that I am trying to build > the table? > > Week, Redhat, CentOS 6, CentOS 5, Debian Squeeze, Debian Whezzy, ..., Ubuntu, Solaris, Windows XP, Windows 7 > > 13 4 6 5 3 5 8 4 4 8 > 14 3 7 4 3 5 7 4 4 4 OK, Then I'd use something like select week, name, count from os ordered by week. That gives you all the rows in week order so all the os values for a given week are together. You can then iterate over each week group and reformat as you require to get your table above. Or use Peter's approach which I just spotted ;-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From castfun05 at gmail.com Fri Mar 21 04:31:10 2014 From: castfun05 at gmail.com (cast fun) Date: Thu, 20 Mar 2014 23:31:10 -0400 Subject: [Tutor] Tkinter and moving round button Message-ID: I am trying to write a UI with text entry box for user input, buttons, and a moving circle when clicked popping up a new UI window. I was thinking Pygame, but didn't know how to show the text entry box. I am now using Tkinter, which is easy for the widgets, but the problem is the moving circle with the click event. 1. Can I use Sprite in Tkinter and if so how about the click event on the Sprite? 2. The other way I am thinking is in Tkinter, drawing a moving circle on the canvas, but don't know how to detect the click event to pop up a new window. 3. Or better in Tkinter if I can use a round button as the circle. I tried the image button. The rectangle border was always there, not really a round button. Thanks you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From james at uplinkzero.com Fri Mar 21 11:54:03 2014 From: james at uplinkzero.com (James Chapman) Date: Fri, 21 Mar 2014 10:54:03 +0000 Subject: [Tutor] mixing 64 bit and 32 bit In-Reply-To: <5329F5CF.6090405@jfcomputer.com> References: <5329D895.9080902@jfcomputer.com> <5329F5CF.6090405@jfcomputer.com> Message-ID: Depending on what you're doing you could run into problems. Areas that have been challenging for me in the past: * Loading 64bit compiled .dll in a 32bit Python environment and vice versa. * Reading registry entries. MS tried to be clever by introducing the Wow6432Node reg key. And I'm sure there has been a 3rd item that I am currently unable to recall. It involved py2exe. This might have been related to the registry issue mentioned above though. With all that said, if you know you're likely to have these kinds of issues it's pretty easy to write code that can deal with these types of problems and do one thing or another depending on the base OS. -- James On 19 March 2014 19:53, John Fabiani wrote: > Thanks > Johnf > > On 03/19/2014 11:01 AM, Reuben wrote: > > Hi John, > > The generated bytecodes will be different - but both version can run same > code without issues > > Regards, > Reuben > > On 19-Mar-2014 11:28 PM, "John Fabiani" wrote: >> >> Hi, >> >> At my office we have a mix of XP (32bit) and Window 7 (64 bit). I >> installed python 64 bit on the windows 7 machines and 32 bit on the XP >> machines. The question is can the different version run the same code >> without causing issues. Can the 64 bit use the same byte code as the 32 >> bit? It seems to be working but I thought best to check. >> >> Johnf >> _______________________________________________ >> 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 gwengstrom at yahoo.com Fri Mar 21 18:14:22 2014 From: gwengstrom at yahoo.com (Gary) Date: Fri, 21 Mar 2014 13:14:22 -0400 Subject: [Tutor] Understanding code line Message-ID: <4CE4A9EA-B6C7-45CA-BCC8-0975F494E2F2@yahoo.com> Pythonists I am trying to understand the difference between a = b b = a + b and a,b = b, a+ b When used in my Fibonacci code the former generates 0,1,2,4,8,16,32 and the later Generates 0,1,1,2,3,5,8,13,21,34,55,89. The second is the sequence I want, but I would Like to understand the second code sequence better so I can write the code in R and Scilab as well as python. G From joel.goldstick at gmail.com Fri Mar 21 18:21:37 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 21 Mar 2014 13:21:37 -0400 Subject: [Tutor] Understanding code line In-Reply-To: <4CE4A9EA-B6C7-45CA-BCC8-0975F494E2F2@yahoo.com> References: <4CE4A9EA-B6C7-45CA-BCC8-0975F494E2F2@yahoo.com> Message-ID: On Mar 21, 2014 1:16 PM, "Gary" wrote: > > > Pythonists > > I am trying to understand the difference between > > a = b You have overwitten a > b = a + b > and > > a,b = b, a+ b This one evaluates the right side first, then assigns the result to a and b > When used in my Fibonacci code the former generates 0,1,2,4,8,16,32 and the later > Generates 0,1,1,2,3,5,8,13,21,34,55,89. The second is the sequence I want, but I would > Like to understand the second code sequence better so I can write the code in R and Scilab as well as python. > G > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From gwengstrom at yahoo.com Fri Mar 21 20:25:41 2014 From: gwengstrom at yahoo.com (Gary Engstrom) Date: Fri, 21 Mar 2014 12:25:41 -0700 (PDT) Subject: [Tutor] (no subject) Message-ID: <1395429941.94496.YahooMailNeo@web142506.mail.bf1.yahoo.com> Dear Pythonists ? Here is the code ? def fiba(n): ??????????? a = 0 ??????????? b = 1 ??????????? while? a < n : ??????????????????????? print(a) ??????????????????????? c =? a + b ??????????????????????? a = a +c ??????????????????????? ???? # 0,1,3,7,15,31,63 ? def fibc(n): ??????????? a = 0 ??????????? b = 1 ??????????? while? a < n : ??????????????????????? print(a) ??????????????????????? a, b = b,a + b ??????????????????????? #0,1,1,2,3,5,8,13,21,34,55,89 ? def fibb(n): a + b ??????????? a = 0 ??????????? b = 1 ??????????? while? a < n : ??????????????????????? print(a) ??????????????????????? a = b ??????????????????????? b = a+b ??????????? #0,1,2,4,8,16,32,64 ? I am trying to understand function fibc code line a,b = b, a + b and would like to see it written line by line without combining multiply assignment. If possible. I sort of follow the right to left evaluation of the other code. -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Fri Mar 21 21:57:32 2014 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 21 Mar 2014 16:57:32 -0400 Subject: [Tutor] (no subject) In-Reply-To: <1395429941.94496.YahooMailNeo@web142506.mail.bf1.yahoo.com> References: <1395429941.94496.YahooMailNeo@web142506.mail.bf1.yahoo.com> Message-ID: On Fri, Mar 21, 2014 at 3:25 PM, Gary Engstrom wrote: > I am trying to understand function fibc code line a,b = b, a + b and would > like to see it written line by line > without combining multiply assignment. If possible. I sort of follow the > right to left evaluation of the other code. Sure. a,b = b, a+b is equivalent to: new_a = b new_b = a + b a = new_a b = new_b del new_a del new_b That is, we first evaluate everything on the right hand side of the equals sign, then assign those values to a and b. Then we get rid of the temporary variables, since the original statement didn't leave any temporary variable floating around. -- Jerry From alan.gauld at btinternet.com Fri Mar 21 22:14:12 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 21 Mar 2014 21:14:12 +0000 Subject: [Tutor] Understanding code line In-Reply-To: <4CE4A9EA-B6C7-45CA-BCC8-0975F494E2F2@yahoo.com> References: <4CE4A9EA-B6C7-45CA-BCC8-0975F494E2F2@yahoo.com> Message-ID: On 21/03/14 17:14, Gary wrote: > > Pythonists > > I am trying to understand the difference between > > a = b > b = a + b This does exactly what it says. It first makes a and b identical then makes b equal their sum, that is, b+b > and > a,b = b, a+ b The second form is not always available in programming languages so R may not support it directly. The more general version would be: temp = a a = b b = temp + b > Like to understand the second code sequence better so I > can write the code in R and Scilab as well as python. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Fri Mar 21 22:21:17 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 21 Mar 2014 21:21:17 +0000 Subject: [Tutor] Tkinter and moving round button In-Reply-To: References: Message-ID: On 21/03/14 03:31, cast fun wrote: > I am trying to write a UI with text entry box for user input, buttons, > and a moving circle when clicked popping up a new UI window. I was > thinking Pygame, but didn't know how to show the text entry box. I am > now using Tkinter, which is easy for the widgets, but the problem is the > moving circle with the click event. While basic Tkinter usage is within our scope I suspect you may be better off pointing this one at the Tkinter mailing list (and maybe the pygame list too?) since it is very specific to Tkinter. > 1. Can I use Sprite in Tkinter and if so how about the click event on > the Sprite? > > 2. The other way I am thinking is in Tkinter, drawing a moving circle on > the canvas, but don't know how to detect the click event to pop up a new > window. The click event in a canvass is easily enough detected by binding to the mouse button events and reading the event information to find out where the mouse is and then determining whether it is within your circle (I seem to recall a shape method that tells you if a point is inside the boundary... but that might not have been in tkinter). > 3. Or better in Tkinter if I can use a round button as the circle. I > tried the image button. The rectangle border was always there, not > really a round button. I don't know of any non rectangular widgets in Tkinter. The canvas might be the best option here. But I'd try the Tkinter mailing list. (If you cant find it, it is listed on the gmane.org news server as gmane.comp.python.tkinter) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From jmmy71 at yahoo.com Fri Mar 21 10:31:07 2014 From: jmmy71 at yahoo.com (Mustafa Musameh) Date: Fri, 21 Mar 2014 20:31:07 +1100 Subject: [Tutor] please help Message-ID: Please help. I have been search the internet to understand how to write a simple program/script with python, and I did not do anything. I have a file that look like this >ID 1 agtcgtacgt? >ID 2 attttaaaaggggcccttcc . . . in other words, it contains several IDs each one has a sequence of 'acgt' letters I need to write a script in python where the output will be, for example, like this > ID 1 a = 10%, c = 40%, g=40%, t = 10% >ID 2 a = 15%, c = 35%, g=35%, t = 15% . . . (i mean the first line is the ID and the second line is the frequency of each letter ) How I can tell python to print the first line as it is and count characters starting from the second line till the beginning of the next '>' and so on Please help From breamoreboy at yahoo.co.uk Fri Mar 21 22:28:43 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 21 Mar 2014 21:28:43 +0000 Subject: [Tutor] please help In-Reply-To: References: Message-ID: On 21/03/2014 09:31, Mustafa Musameh wrote: > Please help. I have been search the internet to understand how to write a simple program/script with python, and I did not do anything. > I have a file that look like this >> ID 1 > agtcgtacgt? >> ID 2 > attttaaaaggggcccttcc > . > . > . > in other words, it contains several IDs each one has a sequence of 'acgt' letters > I need to write a script in python where the output will be, for example, like this >> ID 1 > a = 10%, c = 40%, g=40%, t = 10% >> ID 2 > a = 15%, c = 35%, g=35%, t = 15% > . > . > . > (i mean the first line is the ID and the second line is the frequency of each letter ) > How I can tell python to print the first line as it is and count characters starting from the second line till the beginning of the next '>' and so on > > Please help Welcome :) Start here http://docs.python.org/3/tutorial/index.html and then come back with specific questions about any problems that you may encounter. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From gwengstrom at yahoo.com Fri Mar 21 22:21:32 2014 From: gwengstrom at yahoo.com (Gary) Date: Fri, 21 Mar 2014 17:21:32 -0400 Subject: [Tutor] Fib sequence code assignment Message-ID: <6AD95BFE-B66C-4D98-8D88-1231CF3EAE1B@yahoo.com> Dear Jerry, Thank you so much, once you see it it seems so clear, but to see it I might as well be in the Indian Ocean. Got kinda close using temporary variable,but didn't know enough to use del. A lesson learn. Sent from my iPad From alan.gauld at btinternet.com Fri Mar 21 22:43:36 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 21 Mar 2014 21:43:36 +0000 Subject: [Tutor] please help In-Reply-To: References: Message-ID: On 21/03/14 09:31, Mustafa Musameh wrote: > Please help. I have been search the internet to understand how to write a > simple program/script with python, and I did not do anything. There are ma y tutorials on how to write Python for every level of programmer. What is your level? If you can already program then the official tutorial on the python.org web site is a good start. https://wiki.python.org/moin/BeginnersGuide/Programmers and http://docs.python.org/2/tutorial/ or http://docs.python.org/3/tutorial/ Depending on wheher you are using Pyton v2 or v3 - there are significant differences. If you cannot already program then this project will require quite a bit of work to learn the basics before you can start to solve your problem. For that you should look at the list of tutors for non programmers(including mine as cited below). https://wiki.python.org/moin/BeginnersGuide/NonProgrammers > I have a file that look like this >> ID 1 > agtcgtacgt? >> ID 2 > attttaaaaggggcccttcc > . This looks like bioscience? If so there are standard libraries available to help with processing that. Once you understand how to write basic Python you should probably download one of those libraries. There is a page for bioscientists using Python here: http://www.onlamp.com/pub/a/python/2002/10/17/biopython.html If you try one of the tutorials and have specific questions come back here and we can try to clarify things, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From ben+python at benfinney.id.au Fri Mar 21 23:34:15 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 22 Mar 2014 09:34:15 +1100 Subject: [Tutor] Understanding code line References: <4CE4A9EA-B6C7-45CA-BCC8-0975F494E2F2@yahoo.com> Message-ID: <85pplfrxjs.fsf@benfinney.id.au> Gary writes: > Pythonists > > I am trying to understand the difference between > > a = b Retrieves the value referenced by ?b?, then binds the name ?a? to the value. > b = a + b Evaluates the expression ?a + b?, then binds the name ?b? to the result. > and > > a,b = b, a+ b Evaluates the expression ?b, a + b? ? which will be a two-value tuple ? then binds the names ?a? and ?b? to the two values from that tuple. Since the right side of the assignment, in each case, is evaluated before bindling the left side, the resulting values will depend on what the names are *currently* bound to at the time of evaluation. -- \ ?When in doubt tell the truth. It will confound your enemies | `\ and astound your friends.? ?Mark Twain, _Following the Equator_ | _o__) | Ben Finney From steve at pearwood.info Fri Mar 21 23:40:02 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 22 Mar 2014 09:40:02 +1100 Subject: [Tutor] Understanding code line In-Reply-To: <4CE4A9EA-B6C7-45CA-BCC8-0975F494E2F2@yahoo.com> References: <4CE4A9EA-B6C7-45CA-BCC8-0975F494E2F2@yahoo.com> Message-ID: <20140321224001.GV16526@ando> On Fri, Mar 21, 2014 at 01:14:22PM -0400, Gary wrote: > > Pythonists > > I am trying to understand the difference between > > a = b > b = a + b > and > > a,b = b, a+ b Try to evaluate the code in your head, as if you were the Python interpreter. Starting with the first version: a = b This assigns the value to b. So if b was 4, now a is also 4. b = a + b This takes the value of a and the value of b, adds them together, and assigns the result to b. Since the previous line set a to b, this is exactly the same as: b = b + b so if b was 4, it then becomes 8. The end result of these two lines is that b gets doubled each time. The important thing to realise here is that a gets its new value, the old value being lost, before it gets used to calculate b. Now for the second version: a, b = b, a+b Here, Python evaluates the right hand side of the = sign first, then does the assignments. On the RHS, it evaluates b, and a+b. Then it matches them with the names on the LHS, so that a gets the old value of b, and b gets the value of (a+b). The important thing here is that the values on the RHS are calculated before the assignments, so it works the way you expect. Most programming languages do not allow code like this, so you would have to use a temporary variable to get the same result: temp = a # remember the old value of a a = b # set the new value of a b = temp + b # set the new value of b -- Steven From alan.gauld at btinternet.com Sat Mar 22 00:04:03 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 21 Mar 2014 23:04:03 +0000 Subject: [Tutor] Fib sequence code assignment In-Reply-To: <6AD95BFE-B66C-4D98-8D88-1231CF3EAE1B@yahoo.com> References: <6AD95BFE-B66C-4D98-8D88-1231CF3EAE1B@yahoo.com> Message-ID: On 21/03/14 21:21, Gary wrote: > Got kinda close using temporary variable,but didn't know enough to use del. You don't really need to usae del, thats just being closer to what Python does - ie not leaving any temporary variables lying around. But in most programming languages you wouldn't bother deleting the temporary variable you'd just call it temp or somesuch. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From cs at zip.com.au Fri Mar 21 22:39:16 2014 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 22 Mar 2014 08:39:16 +1100 Subject: [Tutor] please help In-Reply-To: References: Message-ID: <20140321213916.GA57168@cskk.homeip.net> On 21Mar2014 20:31, Mustafa Musameh wrote: > Please help. I have been search the internet to understand how to write a simple program/script with python, and I did not do anything. > I have a file that look like this > >ID 1 > agtcgtacgt? > >ID 2 > attttaaaaggggcccttcc > . > . > . > in other words, it contains several IDs each one has a sequence of 'acgt' letters > I need to write a script in python where the output will be, for example, like this > > ID 1 > a = 10%, c = 40%, g=40%, t = 10% > >ID 2 > a = 15%, c = 35%, g=35%, t = 15% > . > . > . > (i mean the first line is the ID and the second line is the frequency of each letter ) > How I can tell python to print the first line as it is and count characters starting from the second line till the beginning of the next '>' and so on You want a loop that reads lines in pairs. Example: while True: line1 = fp.readline() print line1, line2 = fp.readline() ... process the line and report ... Then to process the line, iterate over the line. Because a line is string, and a string is a sequence of characters, you can write: for c in line2: ... collect statistics about c ... ... print report ... I would collect the statistics using a dictionary to keep count of the characters. See the dict.setdefault method; it should be helpful. Cheers, -- Cameron Simpson ... in '59 I ran out of brakes *four times* -- and I don't mean they didn't work very well, I mean I had none. Like the main oil line had sheared. You know, so that oil, you know, when you put your foot on the floor, the oil just went squirting out into the atmosphere. Things like that. You know, I'd always believed that Colin was close to genius in his design ability and everything -- if he could just get over this failing of his of making things too bloody light. I mean, Colin's idea of a Grand Prix car was it should win the race and, as it crossed the finishing line, it should collapse in a heap of bits. If it didn't do that, it was built too strongly. - Innes Ireland From steve at pearwood.info Sat Mar 22 00:15:39 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 22 Mar 2014 10:15:39 +1100 Subject: [Tutor] please help In-Reply-To: References: Message-ID: <20140321231538.GW16526@ando> On Fri, Mar 21, 2014 at 08:31:07PM +1100, Mustafa Musameh wrote: > Please help. I have been search the internet to understand how to > write a simple program/script with python, and I did not do anything. > I have a file that look like this > >ID 1 > agtcgtacgt? > >ID 2 > attttaaaaggggcccttcc > . > . > . > in other words, it contains several IDs each one has a sequence of 'acgt' letters > I need to write a script in python where the output will be, for example, like this > > ID 1 > a = 10%, c = 40%, g=40%, t = 10% > >ID 2 > a = 15%, c = 35%, g=35%, t = 15% > . > . > . > (i mean the first line is the ID and the second line is the frequency of each letter ) > How I can tell python to print the first line as it is and count > characters starting from the second line till the beginning of the > next '>' and so on This sounds like a homework exercise, and I have a policy of trying not to do homework for people. But I will show you the features you need. Firstly, explain what you would do if you were solving this problem in your head. Write out the steps in English (or the language of your choice). Don't worry about writing code yet, you're writing instructions for a human being at this stage. Those instructions might look like this: Open a file (which file?). Read two lines at a time. The first line will look like ">ID 42". Print that line unchanged. The second line will look line "gatacacagtatta...". Count how many "g", "a", "t", "c" letters there are, then print the results as percentages. Stop when there are no more lines to be read. Now that you know what needs to be done, you can start using Python for it. Start off by opening a file for reading: f = open("some file") There are lots of ways to read the file one line at a time. Here's one way: for line in f: print(line) But you want to read it *two* lines at a time. Here is one way: for first_line in f: second_line = next(f, '') print(first_line) print(second_line) Here's another way: first_line = None while first_line != '': first_line = f.readline() second_line = f.readline() Now that you have the lines, what do you do with them? Printing the first line is easy. How about the second? second_line = "gatacattgacaaccggaataccgagta" Now you need to do four things: - count the total number of characters, ignoring the newline at the end - count the number of g, a, t, c characters individually - work out the percentages of the total - print each character and its percentage Here is one way to count the total number of characters: count = 0 for c in second_line: count += 1 Can you think of a better way? Do you think that maybe Python has a built-in command to calculate the length of a string? Here is one way to count the number of 'g' characters: count_of_g = 0 for c in second_line: count_of_g += 1 (Does this look familiar?) Can you think of another way to count characters? Hint: strings have a count method: py> s = "fjejevffveejf" py> s.count("j") 3 Now you need to calculate the percentages. Do you know how to calculate the percentage of a total? Hint: you'll need to divide two numbers and multiply by 100. Finally, you need to print the results. Putting all these parts together should give you a solution. Good luck! Write as much code as you can, and come back with any specific questions you may have. -- Steven From breamoreboy at yahoo.co.uk Sat Mar 22 01:04:23 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 22 Mar 2014 00:04:23 +0000 Subject: [Tutor] please help In-Reply-To: <20140321213916.GA57168@cskk.homeip.net> References: <20140321213916.GA57168@cskk.homeip.net> Message-ID: On 21/03/2014 21:39, Cameron Simpson wrote: > On 21Mar2014 20:31, Mustafa Musameh wrote: > > I would collect the statistics using a dictionary to keep count of > the characters. See the dict.setdefault method; it should be helpful. > Delightfully old fashioned but I'd now prefer http://docs.python.org/3/library/collections.html#collections.Counter :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From missive at hotmail.com Sat Mar 22 03:07:08 2014 From: missive at hotmail.com (Lee Harr) Date: Sat, 22 Mar 2014 06:37:08 +0430 Subject: [Tutor] Printing from python Message-ID: > is there another way to print a PDF form python? > > My problem is a PDF which is printed well by evince, but not with lp,? > even not out of python using > > os.system("lp some_options file.pdf") > > Later on I have to build the PDF in a python program (using reportlab)? > and then print it, even from the python program. I have done this several times before -- generating a pdf with python using reportlab and then printing the result by handing it to lpr. (Not sure what exactly is the difference between lp and lpr, but from ? ?a bit of research, it looks like either one should do the job.) The first thing you need to do is make sure that you can print the file from your regular shell (not python) using your chosen print command. If that does not work, python is not going to do anything magical. If you are having trouble with that, it is more of a question for the mailing list supporting your chosen operating system. Once you get that working, shelling out from python will be able to accomplish the same task. (The one possible gotcha is finding the correct path to the file. ? ?I think I tended to use full paths to everything to make sure ? ?that the correct things would be found.) From cs at zip.com.au Sat Mar 22 03:50:27 2014 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 22 Mar 2014 13:50:27 +1100 Subject: [Tutor] please help In-Reply-To: References: Message-ID: <20140322025027.GA69291@cskk.homeip.net> On 22Mar2014 00:04, Mark Lawrence wrote: > On 21/03/2014 21:39, Cameron Simpson wrote: > >On 21Mar2014 20:31, Mustafa Musameh wrote: > > > >I would collect the statistics using a dictionary to keep count of > >the characters. See the dict.setdefault method; it should be helpful. > > > > Delightfully old fashioned but I'd now prefer > http://docs.python.org/3/library/collections.html#collections.Counter > :) Maybe, but using a dictionary is easy and Mustafa will learn more. Cheers, -- Cameron Simpson Do not underestimate your abilities. That is your boss's job. It is your job to find ways around your boss's roadblocks. - Glen Appleby http://www.armory.com/~glena/ From denis.spir at gmail.com Sat Mar 22 14:30:39 2014 From: denis.spir at gmail.com (spir) Date: Sat, 22 Mar 2014 14:30:39 +0100 Subject: [Tutor] (no subject) In-Reply-To: References: <1395429941.94496.YahooMailNeo@web142506.mail.bf1.yahoo.com> Message-ID: <532D907F.3020801@gmail.com> On 03/21/2014 09:57 PM, Jerry Hill wrote: > On Fri, Mar 21, 2014 at 3:25 PM, Gary Engstrom wrote: >> I am trying to understand function fibc code line a,b = b, a + b and would >> like to see it written line by line >> without combining multiply assignment. If possible. I sort of follow the >> right to left evaluation of the other code. > > Sure. a,b = b, a+b is equivalent to: > > new_a = b > new_b = a + b > a = new_a > b = new_b > del new_a > del new_b > > That is, we first evaluate everything on the right hand side of the > equals sign, then assign those values to a and b. Then we get rid of > the temporary variables, since the original statement didn't leave any > temporary variable floating around. In other words, it is like a = b ; b = a+b performed *in parallel*. Another way to write it is: old_a = a a = b b = old_a + b d From denis.spir at gmail.com Sat Mar 22 14:45:46 2014 From: denis.spir at gmail.com (spir) Date: Sat, 22 Mar 2014 14:45:46 +0100 Subject: [Tutor] Understanding code line In-Reply-To: <4CE4A9EA-B6C7-45CA-BCC8-0975F494E2F2@yahoo.com> References: <4CE4A9EA-B6C7-45CA-BCC8-0975F494E2F2@yahoo.com> Message-ID: <532D940A.3020308@gmail.com> On 03/21/2014 06:14 PM, Gary wrote: > > Pythonists > > I am trying to understand the difference between > > a = b > b = a + b > and > > a,b = b, a+ b > When used in my Fibonacci code the former generates 0,1,2,4,8,16,32 and the later > Generates 0,1,1,2,3,5,8,13,21,34,55,89. The second is the sequence I want, but I would > Like to understand the second code sequence better so I can write the code in R and Scilab as well as python. To understand a, b = b, a+ b correctly, think of it operating in parallel, each assignment independantly. So, it does what you think (and need to compute a fibonacci sequence). A better explanation, maybe, is that python has *tuples*, which are groups of values held together; and are better written inside parens (), like (1,2,3) or (x,y,z). But () are not compulsary, a comma is enough to make a tuple. Here we have two 2-tuples, also called pairs, meaning tuples of 2 values. The assignment thus actually means: (a, b) = (b, a+b) So, python *first* constructs the right side tuple, *then* assigns it to the left side; however, since we don't have on the left side a (named) tuple variable, it actually assigns to the local variables a & b, in //. Hope it's clear. You can consider this last step as nice, little magic. Rarely needed, but very handy when needed. d From denis.spir at gmail.com Sat Mar 22 14:48:05 2014 From: denis.spir at gmail.com (spir) Date: Sat, 22 Mar 2014 14:48:05 +0100 Subject: [Tutor] Fib sequence code assignment In-Reply-To: <6AD95BFE-B66C-4D98-8D88-1231CF3EAE1B@yahoo.com> References: <6AD95BFE-B66C-4D98-8D88-1231CF3EAE1B@yahoo.com> Message-ID: <532D9495.9010402@gmail.com> On 03/21/2014 10:21 PM, Gary wrote: > Dear Jerry, > > Thank you so much, once you see it it seems so clear, but to see it I might as well be in the Indian Ocean. Got kinda close using temporary variable,but didn't know enough to use del. > A lesson learn. You don't need del (here). Every variable is automagically recycled at the end of the current scope, meaning usually the end of the function (fib). In practice, we so-to-say never need del in python (the common exception being to delete an item in a collection). d From denis.spir at gmail.com Sat Mar 22 14:56:28 2014 From: denis.spir at gmail.com (spir) Date: Sat, 22 Mar 2014 14:56:28 +0100 Subject: [Tutor] please help In-Reply-To: <20140321213916.GA57168@cskk.homeip.net> References: <20140321213916.GA57168@cskk.homeip.net> Message-ID: <532D968C.7030803@gmail.com> On 03/21/2014 10:39 PM, Cameron Simpson wrote: > On 21Mar2014 20:31, Mustafa Musameh wrote: >> Please help. I have been search the internet to understand how to write a simple program/script with python, and I did not do anything. >> I have a file that look like this >>> ID 1 >> agtcgtacgt? >>> ID 2 >> attttaaaaggggcccttcc >> . >> . >> . >> in other words, it contains several IDs each one has a sequence of 'acgt' letters >> I need to write a script in python where the output will be, for example, like this >>> ID 1 >> a = 10%, c = 40%, g=40%, t = 10% >>> ID 2 >> a = 15%, c = 35%, g=35%, t = 15% >> . >> . >> . >> (i mean the first line is the ID and the second line is the frequency of each letter ) >> How I can tell python to print the first line as it is and count characters starting from the second line till the beginning of the next '>' and so on > > You want a loop that reads lines in pairs. Example: > > while True: > line1 = fp.readline() > print line1, > line2 = fp.readline() > ... process the line and report ... > > Then to process the line, iterate over the line. Because a line is > string, and a string is a sequence of characters, you can write: > > for c in line2: > ... collect statistics about c ... > ... print report ... > > I would collect the statistics using a dictionary to keep count of > the characters. See the dict.setdefault method; it should be helpful. I think it would be easier to do that in 2 loops: * first read the file line by line, building a list of pairs (id, base-sequence) (and on the fly check the input is correct, if needed) * then traverse the sequences of bases to get numbers & percentages, and write out d From jmmy71 at yahoo.com Sun Mar 23 07:28:26 2014 From: jmmy71 at yahoo.com (Mustafa Musameh) Date: Sun, 23 Mar 2014 17:28:26 +1100 Subject: [Tutor] character counting Message-ID: <233DA5CF-F2B8-4BD8-9489-40241F8EAF17@yahoo.com> Hi; I have a file that looks like this: >title 1 AAATTTGGGCCCATA... TTAACAAGTTAAAT? >title 2 AAATTTAAACCCGGGG? ATATATATA? ? I wrote the following to count the As, Cs, Gs anTs for each title I wrote the following import sys file = open('file.fna') data=file.readlines() for line in data: line = line.rstrip() if line.startswith('>') : print line if not line.startswith('>') : seq = line.rstrip() counters={} for char in seq: counters[char] = counters.get(char,0) + 1 Ks = counters.keys() Ks.sort() for k in Ks: print sum(counters.itervalues()) I want to get the following out put: >title 234 >title 1 3453 ?. but what i get >title 1 60 60 60 60 ? it seems it do counting for each line and print it out. Can you help me please Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at gmail.com Sun Mar 23 13:27:03 2014 From: denis.spir at gmail.com (spir) Date: Sun, 23 Mar 2014 13:27:03 +0100 Subject: [Tutor] character counting In-Reply-To: <233DA5CF-F2B8-4BD8-9489-40241F8EAF17@yahoo.com> References: <233DA5CF-F2B8-4BD8-9489-40241F8EAF17@yahoo.com> Message-ID: <532ED317.7090003@gmail.com> On 03/23/2014 07:28 AM, Mustafa Musameh wrote: > Hi; > I have a file that looks like this: >> title 1 > AAATTTGGGCCCATA... > TTAACAAGTTAAAT? >> title 2 > AAATTTAAACCCGGGG? > ATATATATA? > ? > > I wrote the following to count the As, Cs, Gs anTs for each title I wrote the following > import sys > > file = open('file.fna') > > data=file.readlines() > > for line in data: > > line = line.rstrip() > > if line.startswith('>') : > > print line > > if not line.startswith('>') : > > seq = line.rstrip() > > counters={} > > for char in seq: > > counters[char] = counters.get(char,0) + 1 > > Ks = counters.keys() > > Ks.sort() > > for k in Ks: > > print sum(counters.itervalues()) > > > > > > I want to get the following out put: > >> title > 234 >> title 1 > 3453 > ?. > but what i get >> title 1 > 60 > 60 > 60 > 60 > ? > it seems it do counting for each line and print it out. > > Can you help me please > Thanks (Your code does not work at all, as is. Probably you did not just copy paste a ruuning program.) You are not taking into account the fact that there is a predefinite and small set of of bases, which are the keys of the 'counters' dict. This would simplify your code: see line below with "***". Example (adapted to python 3, and to read a string directly, instead of a file): data = """\ >title 1 AAATTTGGGCCCATA TTAACAAGTTAAAT >title 2 AAATTTAAACCCGGGG ATATATATA """ for line in data.split("\n"): line = line.strip() if line == "": # for last line, maybe others continue if line.startswith('>'): print(line) continue counters = {"A":0, "C":0, "G":0, "T":0} # *** for base in line: counters[base] += 1 bases = ["A","C","G","T"] # *** for base in bases: print(counters[base], end=" ") print() ==> >title 1 5 3 3 4 7 1 1 5 >title 2 6 3 4 3 5 0 0 4 Is this what you want? denis From alan.gauld at btinternet.com Sun Mar 23 17:23:19 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 23 Mar 2014 16:23:19 +0000 Subject: [Tutor] character counting In-Reply-To: <233DA5CF-F2B8-4BD8-9489-40241F8EAF17@yahoo.com> References: <233DA5CF-F2B8-4BD8-9489-40241F8EAF17@yahoo.com> Message-ID: On 23/03/14 06:28, Mustafa Musameh wrote: > Hi; > I have a file that looks like this: > >title 1 > AAATTTGGGCCCATA... > TTAACAAGTTAAAT? > >title 2 > AAATTTAAACCCGGGG? > ATATATATA? > ? > > I want to get the following out put: > > >title > 234 > >title 1 > 3453 > ?. Your example data and example output don't match - at least not in any way I can see. Can you provide sample input and output from that sample? That will help us understand exactly what you want. It might be useful to break the code into functions so that you have one to read the lines and if appropriate call a second that analyzes a line returning the counts. Then a third function can print the results in the format you want. An optional fourth function could assign the analysis results to the dictionary but that's probably overkill. You could even ignore the first one and just make it your main driver code, but the second and third would be helpful in testing and make the main code easier to read. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From cs at zip.com.au Sun Mar 23 22:51:12 2014 From: cs at zip.com.au (Cameron Simpson) Date: Mon, 24 Mar 2014 08:51:12 +1100 Subject: [Tutor] character counting In-Reply-To: <233DA5CF-F2B8-4BD8-9489-40241F8EAF17@yahoo.com> References: <233DA5CF-F2B8-4BD8-9489-40241F8EAF17@yahoo.com> Message-ID: <20140323215112.GA21052@cskk.homeip.net> On 23Mar2014 17:28, Mustafa Musameh wrote: > Hi; > I have a file that looks like this: > >title 1 > AAATTTGGGCCCATA... > TTAACAAGTTAAAT > >title 2 > AAATTTAAACCCGGGG > ATATATATA > > > I wrote the following to count the As, Cs, Gs anTs for each title I wrote the > following > > import sys > > file = open('file.fna') > > data=file.readlines() > for line in data: > line = line.rstrip() > if line.startswith('>') : > print line > if not line.startswith('>') : You could just say "else" here instead of "if not". > seq = line.rstrip() > counters={} > for char in seq: > counters[char] = counters.get(char,0) + 1 > Ks = counters.keys() > Ks.sort() > for k in Ks: > print sum(counters.itervalues()) This prints the same sum as many times as there are keys. Notice that your print statement has no mention of "k"? You either want just the "print" with no loop over Ks or you want the loop, with some expression inside which changes depending on the value of "k". You call, of course, depending on your desired result. Cheers, -- Cameron Simpson "Don't you know the speed limit is 55 miles per hour???" "Yeah, but I wasn't going to be out that long." - Steven Wright From jf_byrnes at comcast.net Mon Mar 24 05:08:35 2014 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Sun, 23 Mar 2014 23:08:35 -0500 Subject: [Tutor] __abs__() not acting as expected Message-ID: I am reading Practical Programming - An Introduction to Computer Science Using Python 3. They give this example: >>> abs(-3) 3 >>> -3 .__abs__() 3 When I try it in idle or a terminal I get different results. Python 3.3.5 (default, Mar 12 2014, 02:09:17) [GCC 4.6.3] on linux >>> abs(-3) 3 >>> -3 .__abs__() -3 If I use a variable it works. >>> x = -3 >>> x.__abs__() 3 I am curious as to what is happening. Is the book wrong? I checked it's errata and nothing is mentioned. Regards, Jim From ben+python at benfinney.id.au Mon Mar 24 05:36:45 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 24 Mar 2014 15:36:45 +1100 Subject: [Tutor] Expressions, literals, operator precedence (was: __abs__() not acting as expected) References: Message-ID: <85r45sqkki.fsf@benfinney.id.au> Jim Byrnes writes: > I am reading Practical Programming - An Introduction to Computer > Science Using Python 3. They give this example: > > >>> abs(-3) > 3 > > >>> -3 .__abs__() > 3 That's a poor example, in my opinion. It's not good for an introductory text to show calling dunder methods like that on an integer literal. Perhaps you could communicate with the maintainer of that material, to point out the problem with their example. Hopefully they will remove the example from an introductory text. > Python 3.3.5 (default, Mar 12 2014, 02:09:17) > [GCC 4.6.3] on linux > > >>> abs(-3) > 3 > > >>> -3 .__abs__() > -3 Yes, I get the same result as you. The reason is that the expression is being evaluated as:: -( (3) .__abs__() ) That is: * Create the integer object 3 * Get the result of that object's ?__abs__? method * Negate (invert the sign) of the value (If you really care, see the end of this message[0] for a demonstration that this is exactly what happens.) Presumably the expression should be different, as shown in your next example:: > If I use a variable it works. > > >>> x = -3 > >>> x.__abs__() > 3 Yes, this is a better way to do it. But why are we calling the ?__abs__? function directly at all? That is, after all, the point of the ?abs? built-in function: to call the correct method on the object:: >>> x = -3 >>> abs(x) 3 > I am curious as to what is happening. Is the book wrong? I checked > it's errata and nothing is mentioned. I think that this is both an erratum, and a demonstration that the example is a bad idea for the book entirely. Can you contact the maintainer of that work to let them know? [0]:: >>> import dis >>> dis.dis("-3 .__abs__()") 1 0 LOAD_CONST 0 (3) 3 LOAD_ATTR 0 (__abs__) 6 CALL_FUNCTION 0 (0 positional, 0 keyword pair) 9 UNARY_NEGATIVE 10 RETURN_VALUE -- \ ?When I get new information, I change my position. What, sir, | `\ do you do with new information?? ?John Maynard Keynes | _o__) | Ben Finney From davea at davea.name Mon Mar 24 06:43:53 2014 From: davea at davea.name (Dave Angel) Date: Mon, 24 Mar 2014 01:43:53 -0400 (EDT) Subject: [Tutor] __abs__() not acting as expected References: Message-ID: Jim Byrnes Wrote in message: > I am reading Practical Programming - An Introduction to Computer Science > Using Python 3. They give this example: > > >>> abs(-3) > 3 > > >>> -3 .__abs__() > 3 > Ben is right, dunder methods don't belong in introductory texts. And they seldom should be called directly; they're there for folks who are defining new classes that want to mimic behavior of builtins. But he didn't show you the simplest fix: (-3).__abs__() -- DaveA From ben+python at benfinney.id.au Mon Mar 24 07:06:09 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 24 Mar 2014 17:06:09 +1100 Subject: [Tutor] __abs__() not acting as expected References: Message-ID: <85mwggqgfi.fsf@benfinney.id.au> Dave Angel writes: > Ben is right, dunder methods don't belong in introductory texts. [?] > But he didn't show you the simplest fix: > > (-3).__abs__() I disagree; the simplest fix is not to call that method directly, and just use:: abs(-3) -- \ ?Computer perspective on Moore's Law: Human effort becomes | `\ twice as expensive roughly every two years.? ?anonymous | _o__) | Ben Finney From jf_byrnes at comcast.net Mon Mar 24 15:03:57 2014 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Mon, 24 Mar 2014 09:03:57 -0500 Subject: [Tutor] Expressions, literals, operator precedence In-Reply-To: <85r45sqkki.fsf@benfinney.id.au> References: <85r45sqkki.fsf@benfinney.id.au> Message-ID: On 03/23/2014 11:36 PM, Ben Finney wrote: > Jim Byrnes writes: > >> I am reading Practical Programming - An Introduction to Computer >> Science Using Python 3. They give this example: >> >>>>> abs(-3) >> 3 >> >>>>> -3 .__abs__() >> 3 > > That's a poor example, in my opinion. It's not good for an introductory > text to show calling dunder methods like that on an integer literal. > > Perhaps you could communicate with the maintainer of that material, to > point out the problem with their example. Hopefully they will remove the > example from an introductory text. > To be fair to the authors this was in a section taking about how the double underscore was special to Python and showing a little about what was going on behind the scenes. They stressed that programmers would almost never use them in code. I plan on sending them a message pointing out the results they show are incorrect. >> Python 3.3.5 (default, Mar 12 2014, 02:09:17) >> [GCC 4.6.3] on linux >> >>>>> abs(-3) >> 3 >> >>>>> -3 .__abs__() >> -3 > > Yes, I get the same result as you. > > The reason is that the expression is being evaluated as:: > > -( (3) .__abs__() ) > > That is: > > * Create the integer object 3 > > * Get the result of that object's ?__abs__? method > > * Negate (invert the sign) of the value > > (If you really care, see the end of this message[0] for a demonstration > that this is exactly what happens.) > > > Presumably the expression should be different, as shown in your next > example:: > >> If I use a variable it works. >> >>>>> x = -3 >>>>> x.__abs__() >> 3 > > Yes, this is a better way to do it. But why are we calling the ?__abs__? > function directly at all? That is, after all, the point of the ?abs? > built-in function: to call the correct method on the object:: I am not really using it. I was just trying to verify the result shown in an example. > >>> x = -3 > >>> abs(x) > 3 > >> I am curious as to what is happening. Is the book wrong? I checked >> it's errata and nothing is mentioned. > > I think that this is both an erratum, and a demonstration that the > example is a bad idea for the book entirely. Can you contact the > maintainer of that work to let them know? > > Thanks for the confirmation and the explanation of what was happening, much appreciated. Regards, Jim From dyoo at hashcollision.org Mon Mar 24 19:13:21 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 24 Mar 2014 11:13:21 -0700 Subject: [Tutor] __abs__() not acting as expected In-Reply-To: References: Message-ID: Hi Jim, The point the book is trying to make here is purely a parsing problem. It's trying to say that the expression: -3.__abs__() has a parse tree that may be unexpected to beginners. The parse is analogous to: unary subtraction on the following: the __abs__() method on 3 whereas you might expecting: the __abs__() method on -3 English has an analogous problem, as do a lot of languages: http://en.wikipedia.org/wiki/List_of_linguistic_example_sentences#Syntactic_ambiguity where it's easy to misinterpret what the meaning of sentences are, either because they have an unexpected parse tree, or there are multiple parse trees, where the meaning becomes ambiguous. In the case of Python, ambiguity isn't the issue, but the way that the program parses may be in a particular segmentation that you might not expect at first. From jmmy71 at yahoo.com Mon Mar 24 09:43:02 2014 From: jmmy71 at yahoo.com (Jumana yousef) Date: Mon, 24 Mar 2014 01:43:02 -0700 (PDT) Subject: [Tutor] Tutor Digest, Vol 121, Issue 56 In-Reply-To: References: Message-ID: <1395650582.43321.YahooMailNeo@web160904.mail.bf1.yahoo.com> Thank you,? just a reminder of my data: it cossets of multiple sequences of DNA that I need to count the bases(characters) and calculate the percentage of C+G and calculate the entropy. before each sequence there is a header or identifier (lets say ID) so it is like >ID 1?etc AAGGTAACCATATATACCGGG?.etc (up to or even more than 3000 characters) >ID 2?etc AAATTTTTAAATTTTTTAAAATATATATACGCGCGCATGCCCCGGGGG?.. etc ??etc I need the out pu to be like this: > ID?1.. etc sequence length = a value G & G content: a value Entropy = a value > ID?2.. etc sequence length = a value G & G content: a value Entropy = a value ?.etc I wrote a program close to what Denis suggested , however it works only if I have one sequence (one header and one sequence), I can not modify it to work if I have several sequences (like above). I also get an incorrect value for entropy (H)? #!/usr/bin/python seq = '' while True: ? ? try: ? ? ? ? line = raw_input() ? ? ? ? index = line.find('>') ? ? ? ? if index > -1: ? ? ? ? ? ? print line ? ? ? ? else: ? ? ? ? ? ? line = line.rstrip() ? ? ? ? ? ? line = line.upper() ? ? ? ? ? ? seq = seq + line ? ? except: ? ? ? ? break print ' Sequence length : ', len(seq) counters = {} for char in seq: ? ? char = char.strip() ? ? if counters.has_key(char): ? ? ? ? counters[char] += 1 ? ? else: ? ? ? ? counters[char] = 1 c_g = 100*(counters['C']+counters['G'])/len(seq) print ' The C & G content: ' '%.1f'% ?c_g, '%' import math all = len(seq) Pa = (counters['A'])/all Pc = counters['C']/all Pg = counters['G']/all Pt = counters['T']/all H =-1*(Pa*math.log(Pa,2) + Pc*math.log(Pc,2) + Pg*math.log(Pg,2) + Pt*math.log(Pt,2)) print ' H = ' , H I do not know why Pa, Pc, Pg, Pt give me a value of 0, although when I type counters['A'] or counters['C']. counters[T'] , counters['G'] or all I get values > 0. So please how I can fix this calculations and how I modify this program to read each sequence, print the results then read the second one and print the results and so on.. Many thanks for your help and support. On Monday, 24 March 2014 5:09 PM, "tutor-request at python.org" wrote: Send Tutor mailing list submissions to ??? tutor at python.org To subscribe or unsubscribe via the World Wide Web, visit ??? https://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to ??? tutor-request at python.org You can reach the person managing the list at ??? tutor-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: ? 1. Re: character counting (spir) ? 2. Re: character counting (Alan Gauld) ? 3. Re: character counting (Cameron Simpson) ? 4. __abs__()? not acting as expected (Jim Byrnes) ? 5. Expressions, literals,??? operator precedence (was: __abs__() ? ? ? not acting as expected) (Ben Finney) ? 6. Re: __abs__()? not acting as expected (Dave Angel) ? 7. Re: __abs__()? not acting as expected (Ben Finney) ---------------------------------------------------------------------- Message: 1 Date: Sun, 23 Mar 2014 13:27:03 +0100 From: spir To: tutor at python.org Subject: Re: [Tutor] character counting Message-ID: <532ED317.7090003 at gmail.com> Content-Type: text/plain; charset=UTF-8; format=flowed On 03/23/2014 07:28 AM, Mustafa Musameh wrote: > Hi; > I have a file that looks like this: >> title 1 > AAATTTGGGCCCATA... > TTAACAAGTTAAAT? >> title 2 > AAATTTAAACCCGGGG? > ATATATATA? > ? > > I wrote the following to count the As, Cs, Gs anTs for each title I wrote the following > import sys > > file = open('file.fna') > > data=file.readlines() > > for line in data: > >? ? ? line = line.rstrip() > >? ? ? if line.startswith('>') : > >? ? ? ? ? print line > >? ? ? if not line.startswith('>') : > >? ? ? ? ? seq = line.rstrip() > >? ? ? ? ? counters={} > >? ? ? ? ? for char in seq: > >? ? ? ? ? ? ? counters[char] = counters.get(char,0) + 1 > >? ? ? ? ? Ks = counters.keys() > >? ? ? ? ? Ks.sort() > >? ? ? ? ? for k in Ks: > >? ? ? ? ? ? ? print sum(counters.itervalues()) > > > > > > I want to get the following out put: > >> title > 234 >> title 1 > 3453 > ?. > but what i get >> title 1 > 60 > 60 > 60 > 60 > ? > it seems it do counting for each line and print it out. > > Can you help me please > Thanks (Your code does not work at all, as is. Probably you did not just copy paste a ruuning program.) You are not taking into account the fact that there is a predefinite and small set of of bases, which are the keys of the 'counters' dict. This would simplify your code: see line below with "***". Example (adapted to python 3, and to read a string directly, instead of a file): data = """\ >title 1 AAATTTGGGCCCATA TTAACAAGTTAAAT >title 2 AAATTTAAACCCGGGG ATATATATA """ for line in data.split("\n"): ? ? line = line.strip() ? ? if line == "":? ? ? # for last line, maybe others ? ? ? ? continue ? ? if line.startswith('>'): ? ? ? ? print(line) ? ? ? ? continue ? ? counters = {"A":0, "C":0, "G":0, "T":0}??? # *** ? ? for base in line: ? ? ? ? counters[base] += 1 ? ? bases = ["A","C","G","T"]??? ??? ??? # *** ? ? for base in bases: ? ? ? ? print(counters[base], end=" ") ? ? print() ==> >title 1 5 3 3 4 7 1 1 5 >title 2 6 3 4 3 5 0 0 4 Is this what you want? denis ------------------------------ Message: 2 Date: Sun, 23 Mar 2014 16:23:19 +0000 From: Alan Gauld To: tutor at python.org Subject: Re: [Tutor] character counting Message-ID: Content-Type: text/plain; charset=windows-1252; format=flowed On 23/03/14 06:28, Mustafa Musameh wrote: > Hi; > I have a file that looks like this: >? >title 1 > AAATTTGGGCCCATA... > TTAACAAGTTAAAT? >? >title 2 > AAATTTAAACCCGGGG? > ATATATATA? > ? > > I want to get the following out put: > >? >title > 234 >? >title 1 > 3453 > ?. Your example data and example output don't match - at least not in any way I can see. Can you provide sample input and output from that sample? That will help us understand exactly what you want. It might be useful to break the code into functions so that you have one to read the lines and if appropriate call a second that analyzes a line returning the counts. Then a third function can print the results in the format you want. An optional fourth function could assign the analysis results to the dictionary but that's probably overkill. You could even ignore the first one and just make it your main driver code, but the second and third would be helpful in testing and make the main code easier to read. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos ------------------------------ Message: 3 Date: Mon, 24 Mar 2014 08:51:12 +1100 From: Cameron Simpson To: tutor at python.org Subject: Re: [Tutor] character counting Message-ID: <20140323215112.GA21052 at cskk.homeip.net> Content-Type: text/plain; charset=us-ascii On 23Mar2014 17:28, Mustafa Musameh wrote: > Hi; > I have a file that looks like this: > >title 1 > AAATTTGGGCCCATA... > TTAACAAGTTAAAT > >title 2 > AAATTTAAACCCGGGG > ATATATATA > > > I wrote the following to count the As, Cs, Gs anTs for each title I wrote the > following > > import sys > > file = open('file.fna') > > data=file.readlines() > for line in data: >? ? line = line.rstrip() >? ? if line.startswith('>') : >? ? ? ? print line >? ? if not line.startswith('>') : You could just say "else" here instead of "if not". >? ? ? ? seq = line.rstrip() >? ? ? ? counters={} >? ? ? ? for char in seq: >? ? ? ? ? ? counters[char] = counters.get(char,0) + 1 >? ? ? ? Ks = counters.keys() >? ? ? ? Ks.sort() >? ? ? ? for k in Ks: >? ? ? ? ? ? print sum(counters.itervalues()) This prints the same sum as many times as there are keys. Notice that your print statement has no mention of "k"? You either want just the "print" with no loop over Ks or you want the loop, with some expression inside which changes depending on the value of "k". You call, of course, depending on your desired result. Cheers, -- Cameron Simpson "Don't you know the speed limit is 55 miles per hour???" "Yeah, but I wasn't going to be out that long." ? ? ? ? - Steven Wright ------------------------------ Message: 4 Date: Sun, 23 Mar 2014 23:08:35 -0500 From: Jim Byrnes To: tutor at python.org Subject: [Tutor] __abs__()? not acting as expected Message-ID: Content-Type: text/plain; charset=ISO-8859-1; format=flowed I am reading Practical Programming - An Introduction to Computer Science Using Python 3.? They give this example: >>> abs(-3) 3 >>> -3 .__abs__() 3 When I try it in idle or a terminal I get different results. Python 3.3.5 (default, Mar 12 2014, 02:09:17) [GCC 4.6.3] on linux >>> abs(-3) 3 >>> -3 .__abs__() -3 If I use a variable it works. >>> x = -3 >>> x.__abs__() 3 I am curious as to what is happening.? Is the book wrong?? I checked it's errata and nothing is mentioned. Regards, Jim ------------------------------ Message: 5 Date: Mon, 24 Mar 2014 15:36:45 +1100 From: Ben Finney To: tutor at python.org Subject: [Tutor] Expressions, literals,??? operator precedence (was: ??? __abs__()? not acting as expected) Message-ID: <85r45sqkki.fsf at benfinney.id.au> Content-Type: text/plain; charset=utf-8 Jim Byrnes writes: > I am reading Practical Programming - An Introduction to Computer > Science Using Python 3.? They give this example: > > >>> abs(-3) > 3 > > >>> -3 .__abs__() > 3 That's a poor example, in my opinion. It's not good for an introductory text to show calling dunder methods like that on an integer literal. Perhaps you could communicate with the maintainer of that material, to point out the problem with their example. Hopefully they will remove the example from an introductory text. > Python 3.3.5 (default, Mar 12 2014, 02:09:17) > [GCC 4.6.3] on linux > > >>> abs(-3) > 3 > > >>> -3 .__abs__() > -3 Yes, I get the same result as you. The reason is that the expression is being evaluated as:: ? ? -( (3) .__abs__() ) That is: * Create the integer object 3 * Get the result of that object's ?__abs__? method * Negate (invert the sign) of the value (If you really care, see the end of this message[0] for a demonstration that this is exactly what happens.) Presumably the expression should be different, as shown in your next example:: > If I use a variable it works. > > >>> x = -3 > >>> x.__abs__() > 3 Yes, this is a better way to do it. But why are we calling the ?__abs__? function directly at all? That is, after all, the point of the ?abs? built-in function: to call the correct method on the object:: ? ? >>> x = -3 ? ? >>> abs(x) ? ? 3 > I am curious as to what is happening.? Is the book wrong?? I checked > it's errata and nothing is mentioned. I think that this is both an erratum, and a demonstration that the example is a bad idea for the book entirely. Can you contact the maintainer of that work to let them know? [0]:: ? ? >>> import dis ? ? >>> dis.dis("-3 .__abs__()") ? ? ? 1? ? ? ? ? 0 LOAD_CONST? ? ? ? ? ? ? 0 (3) ? ? ? ? ? ? ? ? ? 3 LOAD_ATTR? ? ? ? ? ? ? ? 0 (__abs__) ? ? ? ? ? ? ? ? ? 6 CALL_FUNCTION? ? ? ? ? ? 0 (0 positional, 0 keyword pair) ? ? ? ? ? ? ? ? ? 9 UNARY_NEGATIVE? ? ? ? ? ? ? ? ? ? ? 10 RETURN_VALUE? ? ? ? -- \? ? ? ?When I get new information, I change my position. What, sir, | ? `\? ? ? ? ? ? do you do with new information?? ?John Maynard Keynes | _o__)? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | Ben Finney ------------------------------ Message: 6 Date: Mon, 24 Mar 2014 01:43:53 -0400 (EDT) From: Dave Angel To: tutor at python.org Subject: Re: [Tutor] __abs__()? not acting as expected Message-ID: Jim Byrnes Wrote in message: > I am reading Practical Programming - An Introduction to Computer Science > Using Python 3.? They give this example: > >? >>> abs(-3) > 3 > >? >>> -3 .__abs__() > 3 > Ben is right,? dunder methods don't belong in introductory texts. And they seldom should be called directly;? they're there for folks who are defining new classes that want to mimic behavior of builtins. But he didn't show you the simplest fix: (-3).__abs__() -- DaveA ------------------------------ Message: 7 Date: Mon, 24 Mar 2014 17:06:09 +1100 From: Ben Finney To: tutor at python.org Subject: Re: [Tutor] __abs__()? not acting as expected Message-ID: <85mwggqgfi.fsf at benfinney.id.au> Content-Type: text/plain; charset=utf-8 Dave Angel writes: > Ben is right,? dunder methods don't belong in introductory texts. [?] > But he didn't show you the simplest fix: > > (-3).__abs__() I disagree; the simplest fix is not to call that method directly, and just use:: ? ? abs(-3) -- \? ? ? ? ? ?Computer perspective on Moore's Law: Human effort becomes | ? `\? ? ? ? ? twice as expensive roughly every two years.? ?anonymous | _o__)? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | Ben Finney ------------------------------ Subject: Digest Footer _______________________________________________ Tutor maillist? -? Tutor at python.org https://mail.python.org/mailman/listinfo/tutor ------------------------------ End of Tutor Digest, Vol 121, Issue 56 ************************************** -------------- next part -------------- An HTML attachment was scrubbed... URL: From vidya0576 at gmail.com Mon Mar 24 12:58:31 2014 From: vidya0576 at gmail.com (vidyashree vasanth) Date: Mon, 24 Mar 2014 12:58:31 +0100 Subject: [Tutor] camera caliberation Message-ID: hiii i am geting an error ibpng warning: Image width is zero in IHDR libpng warning: Image height is zero in IHDR libpng error: Invalid IHDR data whilw executing camera caliberation programin open cv can you help me -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Mon Mar 24 19:58:48 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 24 Mar 2014 11:58:48 -0700 Subject: [Tutor] FASTA parsing, biological sequence analysis Message-ID: Hi Jumana, Following up. Let's change the subject line. This makes it much easier for folks to see that this is a new topic of conversation. [Apologies to the others on the list for my last reply: I didn't realize that the subject was wrong, as well as the long quoted digest. I'll try to be more careful next time.] Jumana, I would strongly suggest separating string parsing issues from computational issues. The suggestion to use Biopython is twofold: not only do you get to avoid writing a FASTA parser, but it gets you in the right mindset of processing _multiple_ sequences. You are encountering this problem, as your comment suggests: > I wrote a program close to what Denis suggested , however it works only if I > have one sequence (one header and one sequence), I can not modify it to work > if I have several sequences (like above). You want the structure of your program to do an analysis on each biological sequence, rather than on just on each character of your sequence. ### ### pseudocode below: # ### from Bio import SeqIO import sys def doAnalysis(record): print("I see: ", record.id, record.seq) ## fill me in for record in SeqIO.parse(sys.stdin, 'fasta'): doAnalysis(record) ### And you can fill in the details of doAnalysis() so that it does the nucleotide counting and only needs to worry about the contents of the record's single sequence. In bioinformatics contexts, you must either deal with memory consumption, or use libraries that naturally lend to doing things in a memory-careful way, or else your computer will start swapping RAM. At least, unless your data sets are trivial, which I am guessing is not the case. In short, please use the BioPython library. It will handle a lot of issues that you are not considering, including memory consumption and correct, stream-oriented parsing of FASTA. From __peter__ at web.de Mon Mar 24 22:21:35 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Mar 2014 22:21:35 +0100 Subject: [Tutor] Character counting again, was Re: Tutor Digest, Vol 121, Issue 56 References: <1395650582.43321.YahooMailNeo@web160904.mail.bf1.yahoo.com> Message-ID: Jumana yousef wrote: [Please don't reply to the digest. At the very least change the subject to its original text. Thank you.] > just a reminder of my data: > it cossets of multiple sequences of DNA that I need to count the bases(characters) and calculate the percentage of C+G and calculate the entropy. > before each sequence there is a header or identifier (lets say ID) > so it is like > >ID 1?etc > AAGGTAACCATATATACCGGG?.etc (up to or even more than 3000 characters) > >ID 2?etc > AAATTTTTAAATTTTTTAAAATATATATACGCGCGCATGCCCCGGGGG?.. etc > ? etc > I need the out pu to be like this: > > ID?1.. etc > sequence length = a value > G & G content: a value > Entropy = a value > > ID?2.. etc > sequence length = a value > G & G content: a value > Entropy = a value > ?.etc > > > I wrote a program close to what Denis suggested , however it works only if I have one sequence (one header and one sequence), I can not modify it to work if I have several sequences (like above). I also get an incorrect value for entropy (H) > > #!/usr/bin/python If you put the following into a function, say show_stats(seq) > print ' Sequence length : ', len(seq) > counters = {} > for char in seq: > char = char.strip() > if counters.has_key(char): > counters[char] += 1 > else: > counters[char] = 1 > c_g = 100*(counters['C']+counters['G'])/len(seq) > print ' The C & G content: ' '%.1f'% c_g, '%' > import math > all = len(seq) > Pa = (counters['A'])/all > Pc = counters['C']/all > Pg = counters['G']/all > Pt = counters['T']/all > > H =-1*(Pa*math.log(Pa,2) + Pc*math.log(Pc,2) + Pg*math.log(Pg,2) + Pt*math.log(Pt,2)) > > print ' H = ' , H you can invoke that function in and after the while loop like so: > seq = '' > while True: > try: > line = raw_input() > index = line.find('>') > if index > -1: if seq: show_stats(seq) seq = "" > print line > else: > line = line.rstrip() > line = line.upper() > seq = seq + line > except: > break if seq: show_stats() > I do not know why Pa, Pc, Pg, Pt give me a value of 0, although when I type counters['A'] or counters['C']. counters[T'] , counters['G'] or all I get values > 0. When you divide an integer by an integer Python 2 gives you an integer by default: >>> 1/3 0 You can avoid that by converting at least one operand to float >>> float(1)/3 0.3333333333333333 >>> 1/float(3) 0.3333333333333333 or by putting the following magic import at the beginning of every module where you want float or "true" division rather than integer division: >>> from __future__ import division >>> 1/3 0.3333333333333333 > So please how I can fix this calculations and how I modify this program to read each sequence, print the results then read the second one and print the results and so on.. > > Many thanks for your help and support. From alan.gauld at btinternet.com Mon Mar 24 23:05:12 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 24 Mar 2014 22:05:12 +0000 Subject: [Tutor] camera caliberation In-Reply-To: References: Message-ID: On 24/03/14 11:58, vidyashree vasanth wrote: > hiii > i am geting an error > ibpng warning: Image width is zero in IHDR > libpng warning: Image height is zero in IHDR > libpng error: Invalid IHDR data > whilw executing camera caliberation programin open cv can you help me This is a mailing list for those learning the Python programming language. Does your post have anything to do with the Python language or standard library? If not, you will probably get better responses if you ask on an imaging forum, or possibly ask the author of the libpng library (which looks like it may be a C library?) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From s.shall at virginmedia.com Tue Mar 25 16:36:12 2014 From: s.shall at virginmedia.com (Sydney Shall) Date: Tue, 25 Mar 2014 15:36:12 +0000 Subject: [Tutor] FASTA parsing, biological sequence analysis In-Reply-To: References: Message-ID: <5331A26C.7050302@virginmedia.com> I did not know about biopython, but then I am a debutant. I tried to import biopython and I get the message that the name is unknown. I am using Enthought Python 2.7.3on MAC OS X10.6.8. Where and more importantly for me, how do I find and import BioPython on to my machine. With many thanks, Sydney On 24/03/2014 18:58, Danny Yoo wrote: > Hi Jumana, > > Following up. Let's change the subject line. This makes it much > easier for folks to see that this is a new topic of conversation. > > > [Apologies to the others on the list for my last reply: I didn't > realize that the subject was wrong, as well as the long quoted digest. > I'll try to be more careful next time.] > > > Jumana, I would strongly suggest separating string parsing issues from > computational issues. The suggestion to use Biopython is twofold: not > only do you get to avoid writing a FASTA parser, but it gets you in > the right mindset of processing _multiple_ sequences. > > > You are encountering this problem, as your comment suggests: > >> I wrote a program close to what Denis suggested , however it works only if I >> have one sequence (one header and one sequence), I can not modify it to work >> if I have several sequences (like above). > > You want the structure of your program to do an analysis on each > biological sequence, rather than on just on each character of your > sequence. > > ### > ### pseudocode below: # > ### > from Bio import SeqIO > import sys > > > def doAnalysis(record): > print("I see: ", record.id, record.seq) > ## fill me in > > > for record in SeqIO.parse(sys.stdin, 'fasta'): > doAnalysis(record) > ### > > > And you can fill in the details of doAnalysis() so that it does the > nucleotide counting and only needs to worry about the contents of the > record's single sequence. > > In bioinformatics contexts, you must either deal with memory > consumption, or use libraries that naturally lend to doing things in a > memory-careful way, or else your computer will start swapping RAM. At > least, unless your data sets are trivial, which I am guessing is not > the case. > > In short, please use the BioPython library. It will handle a lot of > issues that you are not considering, including memory consumption and > correct, stream-oriented parsing of FASTA. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Sydney Shall From steve at pearwood.info Tue Mar 25 16:55:57 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 26 Mar 2014 02:55:57 +1100 Subject: [Tutor] FASTA parsing, biological sequence analysis In-Reply-To: <5331A26C.7050302@virginmedia.com> References: <5331A26C.7050302@virginmedia.com> Message-ID: <20140325155557.GB16526@ando> On Tue, Mar 25, 2014 at 03:36:12PM +0000, Sydney Shall wrote: > I did not know about biopython, but then I am a debutant. > I tried to import biopython and I get the message that the name is unknown. > I am using Enthought Python 2.7.3on MAC OS X10.6.8. > Where and more importantly for me, how do I find and import BioPython on > to my machine. https://duckduckgo.com/html/?q=download+biopython which leads to this: http://biopython.org/wiki/Biopython If you read the installation instructions, they have instructions for Macs. I don't know how much experience you have, I suggest you read the instructions then come back with any questions. (We're not really Mac experts here, or at least I'm not, it's been 15 years since I've used one, but we can try to help.) -- Steven From s.shall at virginmedia.com Tue Mar 25 17:31:01 2014 From: s.shall at virginmedia.com (Sydney Shall) Date: Tue, 25 Mar 2014 16:31:01 +0000 Subject: [Tutor] FASTA parsing, biological sequence analysis In-Reply-To: <20140325155557.GB16526@ando> References: <5331A26C.7050302@virginmedia.com> <20140325155557.GB16526@ando> Message-ID: <5331AF45.2060705@virginmedia.com> On 25/03/2014 15:55, Steven D'Aprano wrote: > On Tue, Mar 25, 2014 at 03:36:12PM +0000, Sydney Shall wrote: >> I did not know about biopython, but then I am a debutant. >> I tried to import biopython and I get the message that the name is unknown. >> I am using Enthought Python 2.7.3on MAC OS X10.6.8. >> Where and more importantly for me, how do I find and import BioPython on >> to my machine. > > https://duckduckgo.com/html/?q=download+biopython > > which leads to this: > > http://biopython.org/wiki/Biopython > > > If you read the installation instructions, they have instructions for > Macs. I don't know how much experience you have, I suggest you read the > instructions then come back with any questions. (We're not really Mac > experts here, or at least I'm not, it's been 15 years since I've used > one, but we can try to help.) > > Thanks. I will ask if I have difficulty. I think that I understand the instructions. Sydney -- Sydney Shall -------------- next part -------------- An HTML attachment was scrubbed... URL: From piotrhusiatynski at gmail.com Tue Mar 25 18:07:18 2014 From: piotrhusiatynski at gmail.com (=?UTF-8?Q?Piotr_Husiaty=C5=84ski?=) Date: Tue, 25 Mar 2014 18:07:18 +0100 Subject: [Tutor] Basic asyncio usage Message-ID: Hi, I'm trying to get more familiar with asyncio library. Using python 3.4, I wrote simple echo server (see attachement for the code). I know that instead of using bare bone send/recv I could use some of the helper functions, but I want to start with the basics. Using current code, I can connect from multiple sources, but echo won't work for all clients. Also, please look at the `sendall` mehtod - I have to manually remove write callback, otherwise it will be called all the time. Any tips on solving this problem? -------------- next part -------------- A non-text attachment was scrubbed... Name: asynciotest.py Type: text/x-python Size: 2065 bytes Desc: not available URL: From dyoo at hashcollision.org Tue Mar 25 22:41:20 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 25 Mar 2014 14:41:20 -0700 Subject: [Tutor] FASTA parsing, biological sequence analysis In-Reply-To: <1395736213.14806.YahooMailNeo@web160906.mail.bf1.yahoo.com> References: <1395736213.14806.YahooMailNeo@web160906.mail.bf1.yahoo.com> Message-ID: On Tue, Mar 25, 2014 at 1:30 AM, Jumana yousef wrote: > Thanks Danny, but I need to write my program in python. > I managed to get it write if I have one header and one sequence. > Can you please tell me how I can get python to read each sequence (as if it > is a paragraph in a text) analyse it then go to the next and so on. Hi Jumana, Please read: http://biopython.org/DIST/docs/tutorial/Tutorial.html#sec2 and let us know if there's anything there that you do not understand. In particular, Biopython is a library that is written in Python, developed by bioinformaticists, and has been heavily used and tested. Unless you are doing something highly unusual and customized, you should invest some time into using this library. Reusing the work of other people is very important to learn: it can lead to less wasted effort. I'm trying to head you away from wasting time writing a FASTA parser. From bashir.saad at gmail.com Tue Mar 25 20:21:49 2014 From: bashir.saad at gmail.com (Saad Bashir) Date: Tue, 25 Mar 2014 22:21:49 +0300 Subject: [Tutor] 2 Very basic queries Message-ID: Hi everyone! I am a novice programmer and actually learning to program in Python. I have two issues that I am embarrassed to present as they seem to be extremely basic. 1. But encouraged by the site to ask event the most basic questions on this forum, here goes: I am using the book: Practical Programming: an introduction to computer science using Python 3. As per its instructions I am using the IDLE environment (Python shell) of Python [3.2.3 MSC v.1500 64 bit AMD64]. I have been going through the book without any problems but have become stuck at the following stage: When using "if" and "elif" statement I get two types of error messages: 1. Practicing the code as given in the book: >>> ph = float(input('Enter the pH level: ')) Enter the pH level: 8.5 >>> if ph < 7.0: ... print(ph, "is acidic.") ... elif ph > 7.0: ... print(ph, "is basic.") When I write this in the Python shell, as soon as I hit return after "elif ph > 7.0:" I get an error message highlighting "elif" and saying syntax error. Or if I try the indentation as follows with elif aligned if above I get the message below: >>> ph = float(input('Enter the pH level: ')) Enter the pH level: 8.5 >>> if ph < 7.0: ... print(ph, "is acidic.") ... elif ph > 7.0: ... print(ph, "is basic.") "SyntaxError: : unindent does not match any outer indentation level. I have tried everything I can think of but to no avail. Please help. 2. Another problem is that the Python shell is allowing me to copy/paste any code at all. Is there something I am not doing right? Apologies in advance for wasting everyone's time but will be very grateful if I am helped. Saad -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Wed Mar 26 02:00:35 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 26 Mar 2014 12:00:35 +1100 Subject: [Tutor] SyntaxError with indentation (was: 2 Very basic queries) References: Message-ID: <85eh1prcy4.fsf@benfinney.id.au> Saad Bashir writes: > 1. But encouraged by the site to ask event the most basic questions on > this forum, here goes: Welcome! Yes, even very basic questions are appropriate here. But please try to keep separate questions in separate threads, with a ?Subject? field that indicates what the topic is. I'll restrict this answer to the first question. > 1. Practicing the code as given in the book: > > >>> ph = float(input('Enter the pH level: ')) > Enter the pH level: 8.5 > >>> if ph < 7.0: > ... print(ph, "is acidic.") > ... elif ph > 7.0: > ... print(ph, "is basic.") > > When I write this in the Python shell, as soon as I hit return after "elif > ph > 7.0:" > I get an error message highlighting "elif" and saying syntax error. Right. Programmers who read code are greatly assisted when the indentation matches the sematic structure of the code. ?Other programmers? includes you, when you read the code later. So, in Python, the indentation is significant and determines how the Python compiler will parse your code. In other words: you must tell Python the structure of your code, by expressing that structure consistently through indentation. Your code as you show it, above, does not have sensible indentation. The ?if? and ?elif? clauses will only be matched together if they are at the same indentation level; for your example above, that means they need to have no indentation. Also, the code blocks (each ?print? function call) should be at the same indentation level, relative to the ?if? and ?elif?. Conventionally, they should be indented by four spaces. You are working from an instructional text; that will have a section describing how Python code must be indented. Have another read of that section, to understand better what needs to be done. You can also read the Python community convention on coding style, PEP 8 , to see how other programmers will expect your code to be formatted. > 2. Another problem is that the Python shell is allowing me to copy/paste > any code at all. Is there something I am not doing right? Please start another thread for this question, by composing a new message. > Apologies in advance for wasting everyone's time but will be very > grateful if I am helped. Hope that helps you! -- \ ?Two hands working can do more than a thousand clasped in | `\ prayer.? ?Anonymous | _o__) | Ben Finney From alan.gauld at btinternet.com Wed Mar 26 02:20:57 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Mar 2014 01:20:57 +0000 Subject: [Tutor] Basic asyncio usage In-Reply-To: References: Message-ID: On 25/03/14 17:07, Piotr Husiaty?ski wrote: > Hi, > I'm trying to get more familiar with asyncio library. Using python > 3.4, Given that this stuff is pretty much hot off the press you might get a better response on the main python list rather than on tutor. However, some of our resident guru's may have messed with asyncio already.... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Wed Mar 26 02:26:14 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Mar 2014 01:26:14 +0000 Subject: [Tutor] 2 Very basic queries In-Reply-To: References: Message-ID: On 25/03/14 19:21, Saad Bashir wrote: > As per its instructions I am using the IDLE environment (Python shell) > of Python [3.2.3 MSC v.1500 64 bit AMD64]. I have been going through > the book without any problems but have become stuck at the following stage: > > When using "if" and "elif" statement I get two types of error messages: > > 1. Practicing the code as given in the book: > > >>> ph = float(input('Enter the pH level: ')) > Enter the pH level: 8.5 > >>> if ph < 7.0: > ... print(ph, "is acidic.") > ... elif ph > 7.0: > ... print(ph, "is basic.") > > When I write this in the Python shell, as soon as I hit return after > "elif ph > 7.0:" > I get an error message highlighting "elif" and saying syntax error. > > Or if I try the indentation as follows with elif aligned if above I get > the message below: > > >>> ph = float(input('Enter the pH level: ')) > Enter the pH level: 8.5 > >>> if ph < 7.0: > ... print(ph, "is acidic.") > ... elif ph > 7.0: > ... print(ph, "is basic.") > > "SyntaxError: : unindent does not match any outer indentation level. > Do you actually get the three dots in your IDLE? I don't in mine... And thats important because in my IDLE I have to align my indentation with the left margin rather than the code above. So your code would look like: >>> if ph < 7.0: print(ph, "is acidic.") elif ph > 7.0: print(ph, "is basic.") in my IDLE. That's pretty ugly and I wish the IDLE guys would fix it but it's been that way for a long time. Basically you have to pretend the first line started on the left margin... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Wed Mar 26 02:28:49 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 26 Mar 2014 12:28:49 +1100 Subject: [Tutor] 2 Very basic queries In-Reply-To: References: Message-ID: <20140326012849.GF16526@ando> On Tue, Mar 25, 2014 at 10:21:49PM +0300, Saad Bashir wrote: > 2. Another problem is that the Python shell is allowing me to copy/paste > any code at all. Is there something I am not doing right? Which shell are you using? How are you trying to copy/paste? Are you on Linux, Mac, Windows, or something else? -- Steven From jf_byrnes at comcast.net Wed Mar 26 02:32:53 2014 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Tue, 25 Mar 2014 20:32:53 -0500 Subject: [Tutor] 2 Very basic queries In-Reply-To: References: Message-ID: On 03/25/2014 02:21 PM, Saad Bashir wrote: > Hi everyone! > > I am a novice programmer and actually learning to program in Python. I have > two issues that I am embarrassed to present as they seem to be extremely > basic. > > 1. But encouraged by the site to ask event the most basic questions on > this forum, here goes: > > I am using the book: > > Practical Programming: an introduction to computer science using Python 3. > > As per its instructions I am using the IDLE environment (Python shell) of > Python [3.2.3 MSC v.1500 64 bit AMD64]. I have been going through the book > without any problems but have become stuck at the following stage: > > When using "if" and "elif" statement I get two types of error messages: > > 1. Practicing the code as given in the book: > > >>> ph = float(input('Enter the pH level: ')) > Enter the pH level: 8.5 >>>> if ph < 7.0: > ... print(ph, "is acidic.") > ... elif ph > 7.0: > ... print(ph, "is basic.") > > When I write this in the Python shell, as soon as I hit return after "elif > ph > 7.0:" > I get an error message highlighting "elif" and saying syntax error. > > Or if I try the indentation as follows with elif aligned if above I get the > message below: > >>>> ph = float(input('Enter the pH level: ')) > Enter the pH level: 8.5 >>>> if ph < 7.0: > ... print(ph, "is acidic.") > ... elif ph > 7.0: > ... print(ph, "is basic.") > > "SyntaxError: : unindent does not match any outer indentation level. > > I have tried everything I can think of but to no avail. Please help. >>> ph = float(input('Enter the ph level: ')) Enter the ph level: 8.5 >>> >>> if ph < 7.0: print(ph, 'is acidic.') elif ph > 7.0: SyntaxError: unindent does not match any outer indentation level >>> if ph < 7.0: print(ph, 'is acidic.') elif ph > 7.0: print(ph, 'is basic.') 8.5 is basic. I am also learning Python and find idle hard to use. My first if/elif pair looks perfectly aligned but gives a SyntaxError, while my second if/elif pair looks to be not aligned but works fine. I imagine there is a better explanation but here is how I think of it. Python seems to ignore the >>> and considers the i starting if to be in column 0, so if you put your elif against the left margin it works. > > 2. Another problem is that the Python shell is allowing me to copy/paste > any code at all. Is there something I am not doing right? I was able to copy from idle using Ctrl-C and paste to my newreader using Ctrl-V and then copy from my newsreader back to idle using the same procedure. I am using Linux and you seem to be using Windows may be it works differently so I can't help you with it. Regards, Jim From davea at davea.name Wed Mar 26 03:23:20 2014 From: davea at davea.name (Dave Angel) Date: Tue, 25 Mar 2014 22:23:20 -0400 (EDT) Subject: [Tutor] 2 Very basic queries References: Message-ID: Saad Bashir Wrote in message: >>> ph = float(input('Enter the pH level: ')) Enter the pH level: 8.5 >>> if ph < 7.0: ... ?? ?? ?? print(ph, "is acidic.") ... ?? ??elif ph > 7.0: ... ?? ?? print(ph, "is basic.") "SyntaxError: : unindent does not match any outer indentation level. ............................ Welcome. We are seeing 3 extra dots before the continuation lines, probably because you mistakenly posted in html. Please post in text mode, so we all see the same thing, and so it matches what you pasted in. As for your query, what matters is the number of spaces you type before each line. Don't bother trying to make the columns line up visually at the interactive prompt. Same number f spaces for the if as for the elif, in this case zero. -- DaveA From denis.spir at gmail.com Wed Mar 26 13:13:17 2014 From: denis.spir at gmail.com (spir) Date: Wed, 26 Mar 2014 13:13:17 +0100 Subject: [Tutor] 2 Very basic queries In-Reply-To: References: Message-ID: <5332C45D.4080702@gmail.com> On 03/26/2014 02:32 AM, Jim Byrnes wrote: >> 2. Another problem is that the Python shell is allowing me to copy/paste >> any code at all. Is there something I am not doing right? > > I was able to copy from idle using Ctrl-C and paste to my newreader using Ctrl-V > and then copy from my newsreader back to idle using the same procedure. I am > using Linux and you seem to be using Windows may be it works differently so I > can't help you with it. If Ctrl-C & Ctrl-V don't work, try shift-Ctrl-C & shift-Ctrl-V, or using the contextual menu with right-click. Anyway, in my view an interactive interpreter is annoying for anything but using python as a pocket calculator. If you feel like me, you may instead having a python trial file always open (as a tab) in your favorite editor, and do most all your trials there (instead of through the interpretor). This allow all doing editing, modifications, variants... you like. Much better in my view. d From jf_byrnes at comcast.net Wed Mar 26 14:37:43 2014 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Wed, 26 Mar 2014 08:37:43 -0500 Subject: [Tutor] 2 Very basic queries In-Reply-To: <5332C45D.4080702@gmail.com> References: <5332C45D.4080702@gmail.com> Message-ID: On 03/26/2014 07:13 AM, spir wrote: > On 03/26/2014 02:32 AM, Jim Byrnes wrote: >>> 2. Another problem is that the Python shell is allowing me to copy/paste >>> any code at all. Is there something I am not doing right? >> >> I was able to copy from idle using Ctrl-C and paste to my newreader >> using Ctrl-V >> and then copy from my newsreader back to idle using the same >> procedure. I am >> using Linux and you seem to be using Windows may be it works >> differently so I >> can't help you with it. > > If Ctrl-C & Ctrl-V don't work, try shift-Ctrl-C & shift-Ctrl-V, or using > the contextual menu with right-click. Anyway, in my view an interactive > interpreter is annoying for anything but using python as a pocket > calculator. If you feel like me, you may instead having a python trial > file always open (as a tab) in your favorite editor, and do most all > your trials there (instead of through the interpretor). This allow all > doing editing, modifications, variants... you like. Much better in my view. Actually this is what I do also if the example I am looking at is more than a line or two. When I am done with one example I just comment it out and move on to the next one. regards, Jim From breamoreboy at yahoo.co.uk Wed Mar 26 16:38:31 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 26 Mar 2014 15:38:31 +0000 Subject: [Tutor] 2 Very basic queries In-Reply-To: References: Message-ID: On 26/03/2014 01:26, Alan Gauld wrote: > > >>> if ph < 7.0: > print(ph, "is acidic.") > elif ph > 7.0: > print(ph, "is basic.") > > in my IDLE. > > That's pretty ugly and I wish the IDLE guys would fix it but > it's been that way for a long time. > Please raise an issue on the bug tracker if there isn't one already, as Terry Reedy and others have been doing a lot of work to improve IDLE recently, helped by PEP 434 "IDLE Enhancement Exception for All Branches". -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From alan.gauld at btinternet.com Wed Mar 26 17:54:29 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Mar 2014 16:54:29 +0000 Subject: [Tutor] 2 Very basic queries In-Reply-To: References: Message-ID: On 26/03/14 15:38, Mark Lawrence wrote: > On 26/03/2014 01:26, Alan Gauld wrote: >> >> >>> if ph < 7.0: >> print(ph, "is acidic.") >> elif ph > 7.0: >> print(ph, "is basic.") >> >> in my IDLE. >> >> That's pretty ugly and I wish the IDLE guys would fix it but >> it's been that way for a long time. > > Please raise an issue on the bug tracker if there isn't one already, Its well known as an issue and already logged. There are even a couple of unofficial version of IDLE that fix it, but for some reason they never get into the official code base. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From bashir.saad at gmail.com Wed Mar 26 19:13:31 2014 From: bashir.saad at gmail.com (Saad Bashir) Date: Wed, 26 Mar 2014 21:13:31 +0300 Subject: [Tutor] 2 Very basic queries In-Reply-To: References: Message-ID: Jay Lozier, Alan Gauld, Steven D'Aprano, Jim Byrnes, Jim Byrnes, Dave Angel and Denis Spir, Thank you each and every one of you. My code now works and the stumbling block is over. Thank you for taking the time and making the effort for helping a novice with such a piddling problem. Specially Alan Gauld, your advice for aligning the code with the left margin was the key. It has been said that do not help the one in trouble. If you do he will come back to you the next time he is in trouble. So now you have been warned! Saad On Wed, Mar 26, 2014 at 7:54 PM, Alan Gauld wrote: > On 26/03/14 15:38, Mark Lawrence wrote: > >> On 26/03/2014 01:26, Alan Gauld wrote: >> >>> >>> >>> if ph < 7.0: >>> print(ph, "is acidic.") >>> elif ph > 7.0: >>> print(ph, "is basic.") >>> >>> in my IDLE. >>> >>> That's pretty ugly and I wish the IDLE guys would fix it but >>> it's been that way for a long time. >>> >> >> Please raise an issue on the bug tracker if there isn't one already, >> > > Its well known as an issue and already logged. There are even a couple of > unofficial version of IDLE that fix it, but for some reason they never get > into the official code base. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dexternet89 at mail.ru Wed Mar 26 17:59:06 2014 From: dexternet89 at mail.ru (=?UTF-8?B?0JTQvNC40YLRgNC40Lk=?=) Date: Wed, 26 Mar 2014 18:59:06 +0200 Subject: [Tutor] 2 Very basic queries In-Reply-To: <20140326012849.GF16526@ando> References: <20140326012849.GF16526@ando> Message-ID: <5333075A.3030505@mail.ru> ph=float(input("Input ph: ")) if ph<7.0: print "acid" elif ph>7.0: print "basic" else: print "don't know what:)" paste it in notepad and save as some_name.py or i can send you this file it is realy easy. 26.03.2014 03:28, Steven D'Aprano ?????: > On Tue, Mar 25, 2014 at 10:21:49PM +0300, Saad Bashir wrote: > >> 2. Another problem is that the Python shell is allowing me to copy/paste >> any code at all. Is there something I am not doing right? > Which shell are you using? How are you trying to copy/paste? Are you on > Linux, Mac, Windows, or something else? > > > From waterfallroad at gmail.com Thu Mar 27 07:43:33 2014 From: waterfallroad at gmail.com (Leo Nardo) Date: Thu, 27 Mar 2014 01:43:33 -0500 Subject: [Tutor] Help Noob Question Message-ID: Im on windows 8 and i need to open a file called string1.py that is on my desktop, in both the interpreter and notepad++, so that i can work on it. I already have it open in notepad, but for the life of me cannot figure out how to open it in the interpreter. Invalid syntax is the error message when i type in""" python string1.py""""" into the interpreter! maybe a dumb question but i would appreciate the help for sure. thanks :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From dpalao.python at gmail.com Thu Mar 27 09:55:33 2014 From: dpalao.python at gmail.com (David Palao) Date: Thu, 27 Mar 2014 09:55:33 +0100 Subject: [Tutor] Help Noob Question In-Reply-To: References: Message-ID: Hello, What do you mean by "open it in the interpreter"? Do you want to open it and read from it its content? or do you want to execute its python code within the interpreter? Best 2014-03-27 7:43 GMT+01:00 Leo Nardo : > Im on windows 8 and i need to open a file called string1.py that is on my > desktop, in both the interpreter and notepad++, so that i can work on it. I > already have it open in notepad, but for the life of me cannot figure out > how to open it in the interpreter. Invalid syntax is the error message when > i type in""" python string1.py""""" into the interpreter! maybe a dumb > question but i would appreciate the help for sure. thanks :) > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From breamoreboy at yahoo.co.uk Thu Mar 27 09:56:35 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 27 Mar 2014 08:56:35 +0000 Subject: [Tutor] 2 Very basic queries In-Reply-To: References: Message-ID: On 26/03/2014 16:54, Alan Gauld wrote: > On 26/03/14 15:38, Mark Lawrence wrote: >> On 26/03/2014 01:26, Alan Gauld wrote: >>> >>> >>> if ph < 7.0: >>> print(ph, "is acidic.") >>> elif ph > 7.0: >>> print(ph, "is basic.") >>> >>> in my IDLE. >>> >>> That's pretty ugly and I wish the IDLE guys would fix it but >>> it's been that way for a long time. >> >> Please raise an issue on the bug tracker if there isn't one already, > > Its well known as an issue and already logged. There are even a couple > of unofficial version of IDLE that fix it, but for some reason they > never get into the official code base. > There's a message on the IDLE mailing list asking about this earlier today. Jessica McKellar, a PSF board member, is also pushing to get more fixed on IDLE as it's often a newbie's first interaction with Python. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From breamoreboy at yahoo.co.uk Thu Mar 27 10:00:15 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 27 Mar 2014 09:00:15 +0000 Subject: [Tutor] Help Noob Question In-Reply-To: References: Message-ID: On 27/03/2014 08:55, David Palao wrote: > Hello, > What do you mean by "open it in the interpreter"? > Do you want to open it and read from it its content? or do you want to > execute its python code within the interpreter? > Best > > 2014-03-27 7:43 GMT+01:00 Leo Nardo : >> Im on windows 8 and i need to open a file called string1.py that is on my >> desktop, in both the interpreter and notepad++, so that i can work on it. I >> already have it open in notepad, but for the life of me cannot figure out >> how to open it in the interpreter. Invalid syntax is the error message when >> i type in""" python string1.py""""" into the interpreter! maybe a dumb >> question but i would appreciate the help for sure. thanks :) >> Please don't top post on this list. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From ben+python at benfinney.id.au Thu Mar 27 10:11:12 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 27 Mar 2014 20:11:12 +1100 Subject: [Tutor] Help Noob Question References: Message-ID: <85eh1oovkf.fsf@benfinney.id.au> Leo Nardo writes: > Im on windows 8 and i need to open a file called string1.py that is on > my desktop, in both the interpreter and notepad++, so that i can work > on it. It's not clear what you want. What does it mean to you for a Python program to be ?open in the interpreter?? You have opened the file in a text editor, which is fine; the editor presents the file contents for you to edit and save. There isn't really an equivalent with the Python interactive interpreter. It takes its input from you typing at the console. Do you mean ?import the module?? That executes the module and makes it available in a distinct namespace. But it doesn't seem to be quite what you're asking. Do you mean ?run the module as a program?? That is done *non*-interactively, so you don't do it at the interactive Python interpreter. Instead, you do it by issuing a command at your operating system's command prompt. > I already have it open in notepad, but for the life of me cannot > figure out how to open it in the interpreter. Welcome to the forum :-) Hopefully you can make clearer what it is you want to do. -- \ ?Intellectual property is to the 21st century what the slave | `\ trade was to the 16th.? ?David Mertz | _o__) | Ben Finney From davea at davea.name Thu Mar 27 12:12:57 2014 From: davea at davea.name (Dave Angel) Date: Thu, 27 Mar 2014 07:12:57 -0400 (EDT) Subject: [Tutor] Help Noob Question References: Message-ID: Leo Nardo Wrote in message > > Im on windows 8 and i need to open a file called string1.py that is on my desktop, in both the interpreter and notepad++, so that i can work on it. I already have it open in notepad, but for the life of me cannot figure out how to open it in the interpreter. Invalid syntax is the error message when i type in""" python string1.py""""" into the interpreter! maybe a dumb question but i would appreciate the help for sure. thanks :) ................. (Please post in text mode, not html. Sometimes html is a pain on a text mailing list like this one. ) I'm assuming you're asking how to *run* your string1.py script. First you need a shell prompt. For Windows, that's cmd.exe, which you usually get by opening a DOS box. Then at the cmd prompt, you type python string1.py That will start the interpreter, import the script, run the script, and exit the interpreter. -- DaveA From alan.gauld at btinternet.com Thu Mar 27 20:56:40 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 27 Mar 2014 19:56:40 +0000 Subject: [Tutor] Help Noob Question In-Reply-To: References: Message-ID: On 27/03/14 06:43, Leo Nardo wrote: > Im on windows 8 and i need to open a file called string1.py that is on > my desktop, Thats your first problem. Its usually a bad idea to store your python code on the desktop, because the desktop is a pain to find from a command line. Instead create a folder at the top level of a disk - if you have a D drive then D:\PythonProjects or some such name. Move your file into that folder Then you can start a CMD shell window by hitting Windows-R and typing cmd into the dialog that opens. That should open a CMD shell(aka DOS box) with a prompt like: C:\WINDOWS> or similar At that prompt type python D:\PythonProjects\string1.py And your file should run, display any output (or errors) and stop. > error message when i type in""" python string1.py""""" into the > interpreter! You never type 'python' into the Python interpreter. You run python propgrams by typing 'python progmname.py' into your Operating system shell(CMD.exe on windows) You can also run them by double clicking the file in Windows explorer but that often results in a DOS box opening, the code running and the DOS box closing again too fast for you to see anything. So opening the DOS box in advance as described above is usually better. Get used to using the OS command line, programmers tend to use it a lot. (In fact you might want to create a shortcut on your desktop/start screen to open it...) :-) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From kwpolska at gmail.com Thu Mar 27 22:01:52 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Thu, 27 Mar 2014 22:01:52 +0100 Subject: [Tutor] Help Noob Question In-Reply-To: References: Message-ID: On Mar 27, 2014 8:58 PM, "Alan Gauld" wrote: > > On 27/03/14 06:43, Leo Nardo wrote: >> >> Im on windows 8 and i need to open a file called string1.py that is on >> my desktop, > > > Thats your first problem. Its usually a bad idea to store your python code on the desktop, because the desktop is a pain to find from a command line. Painful? How painful can `cd Desktop` be? Certainly less than `D:` followed by `cd PythonProjects`? -- Chris ?Kwpolska? Warrick -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Thu Mar 27 22:13:21 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 27 Mar 2014 21:13:21 +0000 Subject: [Tutor] Help Noob Question In-Reply-To: References: Message-ID: On 27/03/2014 19:56, Alan Gauld wrote: > On 27/03/14 06:43, Leo Nardo wrote: >> Im on windows 8 and i need to open a file called string1.py that is on >> my desktop, > > Thats your first problem. Its usually a bad idea to store your python > code on the desktop, because the desktop is a pain to find from a > command line. > I disagree with this. From the run prompt I use cmd /F:ON /T:02 /K cd your\code\path /F:ON Enable file and directory name completion characters /T:fg Sets the foreground/background colors /K Carries out the command specified by string -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From emile at fenx.com Thu Mar 27 22:21:45 2014 From: emile at fenx.com (Emile van Sebille) Date: Thu, 27 Mar 2014 14:21:45 -0700 Subject: [Tutor] Understanding code line In-Reply-To: <20140321224001.GV16526@ando> References: <4CE4A9EA-B6C7-45CA-BCC8-0975F494E2F2@yahoo.com> <20140321224001.GV16526@ando> Message-ID: On 3/21/2014 3:40 PM, Steven D'Aprano wrote: > a = b > > This assigns the value to b. So if b was 4, now a is also 4. Steven means 'assigns the value to a' here. For anyone looking down the line... From alan.gauld at btinternet.com Fri Mar 28 02:17:40 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 28 Mar 2014 01:17:40 +0000 Subject: [Tutor] Help Noob Question In-Reply-To: References: Message-ID: On 27/03/14 21:01, Chris ?Kwpolska? Warrick wrote: > On Mar 27, 2014 8:58 PM, "Alan Gauld" > wrote: > > > > On 27/03/14 06:43, Leo Nardo wrote: > >> > >> Im on windows 8 and i need to open a file called string1.py that is on > >> my desktop, > > > > > > Thats your first problem. Its usually a bad idea to store your python > code on the desktop, because the desktop is a pain to find from a > command line. > > Painful? How painful can `cd Desktop` be? Certainly less than `D:` > followed by `cd PythonProjects`? Because the desktop is hardly ever anywhere near where the cmd prompt lands you. So cd desktop usually results in an error and typing the full path (even with directory completion, Mark) is a royal pain because you have to remember where it is. There is no ~ shortcut in Windows. On my system that means typing something like: C:\Documents and Settings\alang\Desktop or some such nonsense, complete with spaces in the path that add to the pain. Now I probably could use something like cd %HOMEPATH% to get to what Windows laughingly considers my 'home' directory and then find it from there but even so its not always obvious depending on the windows version and the install options used. And of course if the file happens to be on the "all users" Desktop looking in my local Desktop doesn't help. I find it much easier to know where my Python code lives from wherever I happen to find myself in the labrynthian file system that is Windows. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From denis.spir at gmail.com Fri Mar 28 10:28:27 2014 From: denis.spir at gmail.com (spir) Date: Fri, 28 Mar 2014 10:28:27 +0100 Subject: [Tutor] Help Noob Question In-Reply-To: References: Message-ID: <533540BB.7090102@gmail.com> On 03/28/2014 02:17 AM, Alan Gauld wrote: > On 27/03/14 21:01, Chris ?Kwpolska? Warrick wrote: >> On Mar 27, 2014 8:58 PM, "Alan Gauld" > > wrote: >> > >> > On 27/03/14 06:43, Leo Nardo wrote: >> >> >> >> Im on windows 8 and i need to open a file called string1.py that is on >> >> my desktop, >> > >> > >> > Thats your first problem. Its usually a bad idea to store your python >> code on the desktop, because the desktop is a pain to find from a >> command line. >> >> Painful? How painful can `cd Desktop` be? Certainly less than `D:` >> followed by `cd PythonProjects`? > > Because the desktop is hardly ever anywhere near where the cmd prompt lands you. > > So cd desktop usually results in an error and typing the full path (even with > directory completion, Mark) is a royal pain because > you have to remember where it is. There is no ~ shortcut in Windows. > On my system that means typing something like: > > C:\Documents and Settings\alang\Desktop Can't you make a symlink pointing to Desktop? (in C:\ or anywhere else) > or some such nonsense, complete with spaces in the path that add > to the pain. > > Now I probably could use something like cd %HOMEPATH% to get to what Windows > laughingly considers my 'home' directory and then find it > from there but even so its not always obvious depending on the > windows version and the install options used. And of course if > the file happens to be on the "all users" Desktop looking in my > local Desktop doesn't help. > > I find it much easier to know where my Python code lives from wherever I happen > to find myself in the labrynthian file system that is Windows. Well, all filesystems are labyrinthians, AFAIK (at least, for people like me who cannot learn by heart). I never know where things are are, in my box (Linux), apart from my own home. d From ljmamoreira at gmail.com Fri Mar 28 10:42:29 2014 From: ljmamoreira at gmail.com (Jose Amoreira) Date: Fri, 28 Mar 2014 09:42:29 +0000 Subject: [Tutor] Slices of lists of lists Message-ID: <53354405.80500@gmail.com> Hello! Here is something that surprised me and I still didn't get it. If we want to store a matrix in pure python (no numpy), the first thing that comes to (my) mind is to use a list of lists, like the list l below: In [1]: l=[ ...: [11,12,13], ...: [21,22,23] ...: ] We can access individual components of this object in a simple, to be expected way: In [2]: l[0][1], l[1][0] Out[2]: (12, 21) OK, that's fine. If we want to access individual rows of this matrix like object, the standard slice notation (on the second index) works as expected also: In [3]: l[0][:] Out[3]: [11, 12, 13] In [4]: l[1][:] Out[4]: [21, 22, 23] Again, fine! But what if we want to access a particular row? My first guess was that standard slice notation on the first index would do it, but it doesn't! Instead, we get the rows again: In [6]: l[:][0] Out[6]: [11, 12, 13] In [7]: l[:][1] Out[7]: [21, 22, 23] Why is this so? Thanks, Jose Amoreira From breamoreboy at yahoo.co.uk Fri Mar 28 11:09:10 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 28 Mar 2014 10:09:10 +0000 Subject: [Tutor] Help Noob Question In-Reply-To: References: Message-ID: On 28/03/2014 01:17, Alan Gauld wrote: > On 27/03/14 21:01, Chris ?Kwpolska? Warrick wrote: >> On Mar 27, 2014 8:58 PM, "Alan Gauld" > > wrote: >> > >> > On 27/03/14 06:43, Leo Nardo wrote: >> >> >> >> Im on windows 8 and i need to open a file called string1.py that >> is on >> >> my desktop, >> > >> > >> > Thats your first problem. Its usually a bad idea to store your python >> code on the desktop, because the desktop is a pain to find from a >> command line. >> >> Painful? How painful can `cd Desktop` be? Certainly less than `D:` >> followed by `cd PythonProjects`? > > Because the desktop is hardly ever anywhere near where the cmd prompt > lands you. > > So cd desktop usually results in an error and typing the full path (even > with directory completion, Mark) is a royal pain because > you have to remember where it is. There is no ~ shortcut in Windows. The point is you type it once and then rerun the command from the run prompt. How can anything be easier? > On my system that means typing something like: > > C:\Documents and Settings\alang\Desktop > > or some such nonsense, complete with spaces in the path that add > to the pain. > > Now I probably could use something like cd %HOMEPATH% to get to what > Windows laughingly considers my 'home' directory and then find it > from there but even so its not always obvious depending on the > windows version and the install options used. And of course if > the file happens to be on the "all users" Desktop looking in my > local Desktop doesn't help. > > I find it much easier to know where my Python code lives from wherever I > happen to find myself in the labrynthian file system that is Windows. > -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From linux at barrowhillfarm.org.uk Fri Mar 28 11:09:20 2014 From: linux at barrowhillfarm.org.uk (Bob Williams) Date: Fri, 28 Mar 2014 10:09:20 +0000 Subject: [Tutor] Slices of lists of lists In-Reply-To: <53354405.80500@gmail.com> References: <53354405.80500@gmail.com> Message-ID: <53354A50.5040105@barrowhillfarm.org.uk> On 28/03/14 09:42, Jose Amoreira wrote: > Hello! > Here is something that surprised me and I still didn't get it. > > If we want to store a matrix in pure python (no numpy), the first thing > that comes to (my) mind is to use a list of lists, like the list l below: > In [1]: l=[ > ...: [11,12,13], > ...: [21,22,23] > ...: ] > > We can access individual components of this object in a simple, to be > expected way: > > In [2]: l[0][1], l[1][0] > Out[2]: (12, 21) > > OK, that's fine. If we want to access individual rows of this matrix > like object, the standard slice notation (on the second index) works as > expected also: > > In [3]: l[0][:] > Out[3]: [11, 12, 13] > > In [4]: l[1][:] > Out[4]: [21, 22, 23] > > Again, fine! But what if we want to access a particular row? My first > guess was that standard slice notation on the first index would do it, > but it doesn't! Instead, we get the rows again: > > In [6]: l[:][0] > Out[6]: [11, 12, 13] > > In [7]: l[:][1] > Out[7]: [21, 22, 23] > Jose, Just for clarity, are you trying to access a particular *column* in your last example? Bob -- Bob Williams System: Linux 3.11.10-7-desktop Distro: openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.3 Uptime: 06:00am up 4 days 19:51, 4 users, load average: 0.37, 0.18, 0.15 From ljmamoreira at gmail.com Fri Mar 28 11:19:27 2014 From: ljmamoreira at gmail.com (Jose Amoreira) Date: Fri, 28 Mar 2014 10:19:27 +0000 Subject: [Tutor] Slices of lists of lists In-Reply-To: <53354A50.5040105@barrowhillfarm.org.uk> References: <53354405.80500@gmail.com> <53354A50.5040105@barrowhillfarm.org.uk> Message-ID: <53354CAF.7040901@gmail.com> > > Jose, > > Just for clarity, are you trying to access a particular *column* in your > last example? > > Bob > Yes, that's it! I wanted to say "column", not "row" in my last example. Sorry about that! Thanks Jose From alan.gauld at btinternet.com Fri Mar 28 11:24:44 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 28 Mar 2014 10:24:44 +0000 Subject: [Tutor] Help Noob Question In-Reply-To: <533540BB.7090102@gmail.com> References: <533540BB.7090102@gmail.com> Message-ID: On 28/03/14 09:28, spir wrote: > On 03/28/2014 02:17 AM, Alan Gauld wrote: >> you have to remember where it is. There is no ~ shortcut in Windows. >> On my system that means typing something like: >> >> C:\Documents and Settings\alang\Desktop > > Can't you make a symlink pointing to Desktop? (in C:\ or anywhere else) You could, and that would help a little. But the problem on Windows is that what appears on the Desktop *display* is an amalgam of (up to 3?) different folders in the file system. So just because you see an icon on the 'desktop' doesn't mean you actually know which folder it is in. Secondly this correlation between desktop folder and desktop display means that's a bad place to store python files since every file you create will add to the clutter of icons on your display. In my python projects file I have over 100 small test files. That would be a lot of icons messing up my screen. So because of a combination of: a) path complexity, b) the disconnect between display and physical location and c) the correlation between files and displayed icons I recommend not using the desktop to store python files. Of course everyone is free to ignore this recommendation, it's just my experience/opinion. :-) > Well, all filesystems are labyrinthians Yes but Windows is much more so because of the disconnect between how it displays things in visual tools and how it stores things on the disk (and the fact that it has multiple disks often with partially duplicated file structures!) Very few things wind up in one place only. For a user, this is ameliorated by the use of Libraries to group folders with similar content, but they only serve to make life even harder for the programmer! [Even worse is the iPad with its insistance on storing files with the app that last worked on them. A moving target indeed, even assuming you can find the files in the first place. Stupid decision.] -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Fri Mar 28 11:32:26 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 28 Mar 2014 10:32:26 +0000 Subject: [Tutor] Slices of lists of lists In-Reply-To: <53354405.80500@gmail.com> References: <53354405.80500@gmail.com> Message-ID: On 28/03/14 09:42, Jose Amoreira wrote: > Hello! > Here is something that surprised me and I still didn't get it. > > If we want to store a matrix in pure python (no numpy), the first thing > that comes to (my) mind is to use a list of lists, like the list l below: > In [1]: l=[ > ...: [11,12,13], > ...: [21,22,23] > ...: ] > But remember this is not actually a two dimensional table it is a sequential list of lists. So Python sees it like: > In [1]: l=[[11,12,13],[21,22,23]...] > We can access individual components of this object in a simple, to be > expected way: > > In [2]: l[0][1], l[1][0] > Out[2]: (12, 21) > > OK, that's fine. If we want to access individual rows of this matrix > like object, the standard slice notation (on the second index) works as > expected also: > > In [3]: l[0][:] > Out[3]: [11, 12, 13] The slice notation makes a copy. You don;t need that you can just use the first index: In [3]: l[0] Out[3]: [11, 12, 13] > Again, fine! But what if we want to access a particular row? I assume you mean column? That concept doesn't exist, instead you must ask Python for the n-th element of every sublist. That's not too hard using a list comprehension: >>> [row[0] for row in l] [11, 21] > guess was that standard slice notation on the first index would do it, No, standard slices on the first element will give you sublists of the first row. Python doesn't have any concept of that second dimension, it only sees a list of items. The fact those items are themselves lists is purely incidental to the interpreter. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From ljmamoreira at gmail.com Fri Mar 28 12:01:14 2014 From: ljmamoreira at gmail.com (Jose Amoreira) Date: Fri, 28 Mar 2014 11:01:14 +0000 Subject: [Tutor] Slices of lists of lists In-Reply-To: References: <53354405.80500@gmail.com> Message-ID: <5335567A.4080005@gmail.com> On 03/28/2014 10:32 AM, Alan Gauld wrote: > No, standard slices on the first element will give you sublists of the > first row. Python doesn't have any concept of that second dimension, it > only sees a list of items. The fact those items are themselves lists is > purely incidental to the interpreter. > > > HTH Thanks, Alan. It was very helpful. I see it now: l[:] is just a copy of the list itself. Then, l[:][k] == l[k]. Thanks again. Jose From 13411 at budehaven.cornwall.sch.uk Fri Mar 28 13:00:26 2014 From: 13411 at budehaven.cornwall.sch.uk (Nathan Curnow (Year 10)) Date: Fri, 28 Mar 2014 12:00:26 +0000 Subject: [Tutor] Writing to text files Message-ID: HU. HU. HU. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kwpolska at gmail.com Fri Mar 28 16:27:18 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Fri, 28 Mar 2014 16:27:18 +0100 Subject: [Tutor] Help Noob Question In-Reply-To: References: <533540BB.7090102@gmail.com> Message-ID: On Fri, Mar 28, 2014 at 2:17 AM, Alan Gauld wrote: > On 27/03/14 21:01, Chris ?Kwpolska? Warrick wrote: >> Painful? How painful can `cd Desktop` be? Certainly less than `D:` >> followed by `cd PythonProjects`? > > > Because the desktop is hardly ever anywhere near where the cmd prompt lands > you. I just tested on my Windows 7 box. It got me to C:\Users\Kwpolska. `cd Desktop` is enough. I also tested on a third-party?s XP box. C:\Documents and Settings\[username]. `cd Desktop`, too (though it?s locale-dependent). Does not look far from the desktop, does it? Well, the only places where this might not work are Administrator prompts in Vista-and-newer (which there is NO REAL REASON to use for Python) ? or possibly some ultra-crazy corporate environments (but you should not be learning Python there ? and if you are working there, you know how to work with the command line/Windows/source control already). Or, of course, systems where you changed something and it is not your profile directory ? but it?s your doing. So, it?s pretty much the home directory everywhere you should be concerned with. > you have to remember where it is. There is no ~ shortcut in Windows. > On my system that means typing something like: > > C:\Documents and Settings\alang\Desktop or just cd %USERPROFILE%. Different drives would make you jump to %HOMEDRIVE% and then to %HOMEPATH%. >> >> >> Can't you make a symlink pointing to Desktop? (in C:\ or anywhere else) > > > You could, and that would help a little. But the problem on Windows is that > what appears on the Desktop *display* is an amalgam of (up to 3?) different > folders in the file system. So just because you see an icon on the 'desktop' > doesn't mean you actually know which folder it is in. But, for user-created files, it always goes to %USERPROFILE%/Desktop. > Secondly this correlation between desktop folder and desktop display means > that's a bad place to store python files since every file you create will > add to the clutter of icons on your display. In my python projects file I > have over 100 small test files. That would be a > lot of icons messing up my screen. Create a folder on the desktop, or even in the home directory. A much nicer place than the drive root ? and a much modern way to store it (drive root sounds DOS-y) -- Chris ?Kwpolska? Warrick PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense From david at graniteweb.com Fri Mar 28 17:33:54 2014 From: david at graniteweb.com (David Rock) Date: Fri, 28 Mar 2014 11:33:54 -0500 Subject: [Tutor] Help Noob Question In-Reply-To: References: <533540BB.7090102@gmail.com> Message-ID: <20140328163354.GB25607@wdfs.graniteweb.com> * Chris ?Kwpolska? Warrick [2014-03-28 16:27]: > > Create a folder on the desktop, or even in the home directory. A much > nicer place than the drive root ? and a much modern way to store it > (drive root sounds DOS-y) I'll have to disagree with this statement. Dropping all your files in you Desktop directory puts all the files ON the Desktop, which quickly becomes a mess. Regardless of whether it's a new directory at the base, or a new directory under your User directory, you should at least have a dedicated directory to put the files. I'm not discussing the merits of one place over the other, just that simple organization is a good thing. Put it wherever you want, but at least keep it organized. Dropping everything in Desktop is not organized. -- David Rock david at graniteweb.com From wprins at gmail.com Fri Mar 28 19:21:22 2014 From: wprins at gmail.com (Walter Prins) Date: Fri, 28 Mar 2014 20:21:22 +0200 Subject: [Tutor] Help Noob Question In-Reply-To: References: Message-ID: Hi Leo, On 27 March 2014 08:43, Leo Nardo wrote: > Im on windows 8 and i need to open a file called string1.py that is on my > desktop, in both the interpreter and notepad++, so that i can work on it. I > already have it open in notepad, but for the life of me cannot figure out > how to open it in the interpreter. Invalid syntax is the error message when > i type in""" python string1.py""""" into the interpreter! maybe a dumb > question but i would appreciate the help for sure. thanks :) I know a lot's been said already, but nothwithstanding, here's my answer to your question(s): You need to type python string1.py into a Windows command prompt, not directly into a running Python interpreter. For that command to work as shown, at least 2 things need to be true: 1) The Python interpreter (python.exe) must be on the system PATH (so the operating system will be able to locate it) 2) The file string1.py must be in the "Current Directory" (folder) of the Windows command prompt. This is the path location displayed in the prompt to the left of the cursor. A simple way to open a command prompt with the current directory set to a known location, is to open a Windows file explorer window, then browse to the folder you'd like a command prompt in, then overtype the address in the explorer window with "cmd" and press Enter. This little feature makes it trivial to open command prompts in any chosen folder as needed. (Note: This feature is only available in Windows 7 and higher.) Walter From denis.spir at gmail.com Fri Mar 28 20:03:53 2014 From: denis.spir at gmail.com (spir) Date: Fri, 28 Mar 2014 20:03:53 +0100 Subject: [Tutor] Slices of lists of lists In-Reply-To: <53354405.80500@gmail.com> References: <53354405.80500@gmail.com> Message-ID: <5335C799.3080005@gmail.com> On 03/28/2014 10:42 AM, Jose Amoreira wrote: > [...] If we want to access individual rows of this matrix like > object, the standard slice notation (on the second index) works as expected also: > > In [3]: l[0][:] > Out[3]: [11, 12, 13] > > In [4]: l[1][:] > Out[4]: [21, 22, 23] > > Again, fine! No! You *made* here *copies* of the rows. To *get* the rows themselves as they are, just type: l[index_of_row] Also note the following: thinking in terms of row/column is very much misleading. The row number/index is actually the "vertical"(y or j) coordinate, and the column index is a horizontal coordinate... Thus, if you to think that way, speak of "columns & rows"! not the other way round. This means that, if you want yourself or a user to write down a matrix (or eg a game board or map), they would have to inverse their logic; or you would have to reverse the map (your other question). d From alan.gauld at btinternet.com Fri Mar 28 22:33:04 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 28 Mar 2014 21:33:04 +0000 Subject: [Tutor] Help Noob Question In-Reply-To: References: <533540BB.7090102@gmail.com> Message-ID: On 28/03/14 15:27, Chris ?Kwpolska? Warrick wrote: > On Fri, Mar 28, 2014 at 2:17 AM, Alan Gauld wrote: >> Because the desktop is hardly ever anywhere near where the cmd prompt lands >> you. > > I just tested on my Windows 7 box. It got me to C:\Users\Kwpolska. > `cd Desktop` is enough. > I also tested on a third-party?s XP box. C:\Documents and > Settings\[username]. `cd Desktop`, too (though it?s > locale-dependent). > > Does not look far from the desktop, does it? True when you first open the DOS box, but not after you've been using it for a while. I usually find I've moved around several folders and even several disks. > Python) ? or possibly some ultra-crazy corporate environments (but you > should not be learning Python there ? and if you are working there, > you know how to work with the command line/Windows/source control > already). Both are true for me, and a large part of why I wouldn't put stuff on the desktop. For example my desktop was made up of my personal desktop, the PC all-user desktop and the corporate shared desktop (only when connected to the corporate network). Knowing which files/icons belonged to which location was a nightmare. > or just cd %USERPROFILE%. Different drives would make you jump to > %HOMEDRIVE% and then to %HOMEPATH%. Which is true for files I create but not for other users of the PC or for shared desktops. And its still a lot to type compared to Unix (~) or using a drive root. >>> Can't you make a symlink pointing to Desktop? (in C:\ or anywhere else) >> You could, and that would help a little. But the problem on Windows is that >> what appears on the Desktop *display* is an amalgam of (up to 3?) different >> folders in the file system. So just because you see an icon on the 'desktop' >> doesn't mean you actually know which folder it is in. > > But, for user-created files, it always goes to %USERPROFILE%/Desktop. But which user? It may not be me that created the file. And I may have deliberately copied/saved it to one of the shared desktops a long time ago and forgotten. > Create a folder on the desktop, or even in the home directory. I agree a folder is more sensible and avoids the icon overkill but the OP specifically had his *file* on the desktop. > nicer place than the drive root ? and a much modern way to store it > (drive root sounds DOS-y) I accept that but its still the shortest absolute path to type on Windows! And if you are a programmer typing is what you wind up doing a lot of! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From ben+python at benfinney.id.au Sat Mar 29 04:02:26 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 29 Mar 2014 14:02:26 +1100 Subject: [Tutor] Writing to text files References: Message-ID: <85y4ztogfx.fsf@benfinney.id.au> "Nathan Curnow (Year 10)" <13411 at budehaven.cornwall.sch.uk> writes: > HU. HU. HU. Here's hoping you improve your communication skills during Year 10, Nathan. -- \ ?What we usually pray to God is not that His will be done, but | `\ that He approve ours.? ?Helga Bergold Gross | _o__) | Ben Finney From scott.w.d at cox.net Sat Mar 29 06:18:52 2014 From: scott.w.d at cox.net (Scott W Dunning) Date: Fri, 28 Mar 2014 22:18:52 -0700 Subject: [Tutor] while loop In-Reply-To: References: Message-ID: <272461FE-60A1-4614-A968-18EC0AF87831@cox.net> On Mar 28, 2014, at 9:54 PM, Scott W Dunning wrote: > Hello, I?m working on some practice exercises from my homework and I?m having some issues figuring out what is wanted. > > We?re working with the while loop and this is what the question states; > > Write a function print_n that prints a string n times using iteration. > > """Print the string `s`, `n` times. > > > This is also in the exercises and I?m not sure what it means and why it?s there. > > assert isinstance(s, str) > assert isinstance(n, int) > > > Any help is greatly appreciated! > > Scott This is what I have so far but I?m not really sure it?s what the excersise is asking for? n = 5 def print_n(s, n): while n > 0: print s * n print_n("hello", 10) From ben+python at benfinney.id.au Sat Mar 29 06:36:41 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 29 Mar 2014 16:36:41 +1100 Subject: [Tutor] while loop References: <272461FE-60A1-4614-A968-18EC0AF87831@cox.net> Message-ID: <85lhvto9au.fsf@benfinney.id.au> Scott W Dunning writes: > On Mar 28, 2014, at 9:54 PM, Scott W Dunning wrote: > > > We?re working with the while loop and this is what the question states; > > > > Write a function print_n that prints a string n times using iteration. > This is what I have so far but I?m not really sure it?s what the > excersise is asking for? A good programming exercise will show an example input and the expected output, to give an unambiguous test case. Does the homework have that? If not, you're unfortunately left to your own interpretation of what the requirements mean. -- \ ?Truth would quickly cease to become stranger than fiction, | `\ once we got as used to it.? ?Henry L. Mencken | _o__) | Ben Finney From scott.w.d at cox.net Sat Mar 29 05:54:57 2014 From: scott.w.d at cox.net (Scott W Dunning) Date: Fri, 28 Mar 2014 21:54:57 -0700 Subject: [Tutor] while loop Message-ID: Hello, I?m working on some practice exercises from my homework and I?m having some issues figuring out what is wanted. We?re working with the while loop and this is what the question states; Write a function print_n that prints a string n times using iteration. """Print the string `s`, `n` times. This is also in the exercises and I?m not sure what it means and why it?s there. assert isinstance(s, str) assert isinstance(n, int) Any help is greatly appreciated! Scott From jslozier at gmail.com Sat Mar 29 07:27:07 2014 From: jslozier at gmail.com (Jay Lozier) Date: Sat, 29 Mar 2014 02:27:07 -0400 Subject: [Tutor] while loop In-Reply-To: <272461FE-60A1-4614-A968-18EC0AF87831@cox.net> References: <272461FE-60A1-4614-A968-18EC0AF87831@cox.net> Message-ID: <533667BB.3070806@gmail.com> On 03/29/2014 01:18 AM, Scott W Dunning wrote: > On Mar 28, 2014, at 9:54 PM, Scott W Dunning wrote: > >> Hello, I?m working on some practice exercises from my homework and I?m having some issues figuring out what is wanted. >> >> We?re working with the while loop and this is what the question states; >> >> Write a function print_n that prints a string n times using iteration. >> >> """Print the string `s`, `n` times. >> >> >> This is also in the exercises and I?m not sure what it means and why it?s there. >> >> assert isinstance(s, str) >> assert isinstance(n, int) >> >> >> Any help is greatly appreciated! >> >> Scott > This is what I have so far but I?m not really sure it?s what the excersise is asking for? > > n = 5 > def print_n(s, n): > while n > 0: > print s * n > > print_n("hello", 10) > Scott, Are required to use a while loop? Two ways to solve this, while loop and for in range loop while loop n = 5 s = 'some string' def while_print(s, n): index = o while index < n: print(index, s) index += 1 def alternative_print(s, n): for index in range(0, n): print(index, s) The while loop requires that a counter variable or some loop exit condition so you do not end up in an endless loop. This is a common problem with while loops in programming, not just Python. So, if there is alternative method of looping available, good programming practice is to avoid a while loop in any language. The for loop version automatically iterates over the range from 0 to n-1 (5 times). I included the index variable in the print to show the increase of the index. The results for both: 0 some string 1 some string 2 some string 3 some string 4 some string -- Jay Lozier jslozier at gmail.com From davea at davea.name Sat Mar 29 08:47:36 2014 From: davea at davea.name (Dave Angel) Date: Sat, 29 Mar 2014 03:47:36 -0400 (EDT) Subject: [Tutor] while loop References: <272461FE-60A1-4614-A968-18EC0AF87831@cox.net> Message-ID: Scott W Dunning Wrote in message: > > On Mar 28, 2014, at 9:54 PM, Scott W Dunning wrote: > >> Hello, I???m working on some practice exercises from my homework and I???m having some issues figuring out what is wanted. >> >> We???re working with the while loop and this is what the question states; >> >> Write a function print_n that prints a string n times using iteration. >> >> """Print the string `s`, `n` times. >> >> >> This is also in the exercises and I???m not sure what it means and why it???s there. >> >> assert isinstance(s, str) >> assert isinstance(n, int) What are you uncertain about, assert or isinstance? Such statements are frequently used to make sure the function arguments are of the right type. > > > This is what I have so far but I???m not really sure it???s what the excersise is asking for? > > n = 5 > def print_n(s, n): > while n > 0: > print s * n > > print_n("hello", 10) > So did your code print the string 10 times? When asking for help, it's useful to show what you tried, and what was expected, and what actually resulted. You use * to replicate the string, but that wasn't what the assignment asked for. So take out the *n part. You're supposed to use iteration, specifically the while loop. Your while loop doesn't quit after 10 times, it keeps going. Can you figure out why? -- DaveA From street.sweeper at mailworks.org Fri Mar 28 23:59:31 2014 From: street.sweeper at mailworks.org (street.sweeper at mailworks.org) Date: Fri, 28 Mar 2014 18:59:31 -0400 Subject: [Tutor] ElementTree, iterable container, depth of elements Message-ID: <1396047571.2752.100220245.4DE826F7@webmail.messagingengine.com> I'm trying to sort the order of elements in an xml file, mostly to make visual inspection/comparison easier. The example xml and code on http://effbot.org/zone/element-sort.htm get me almost what I need, but the xml I'm working with has the element I'm trying to sort on one level deeper. That page's example xml: Ned 555-8904 John 555-5782 Julius 555-3642 And that page's last example of code: import xml.etree.ElementTree as ET tree = ET.parse("data.xml") def getkey(elem): return elem.findtext("number") container = tree.find("entries") container[:] = sorted(container,key=getkey) tree.write("new-data.xml") I used the interactive shell to experiment a bit with that, and I can see that 'container' in container = tree.find("entries") is iterable, using for a in container: print(a) However, the xml I'm working with looks something like this:
20140325 dentist 20140324 barber
What I'd like to do is rearrange the elements within based on the element. If I remove the level, this will work, but I'm interested in getting the code to work without editing the file. I look for "Date" and "diary" rather than "number" and "entries" but when I try to process the file as-is, I get an error like Traceback (most recent call last): File "./xmlSort.py", line 16, in container[:] = sorted(container, key=getkey) TypeError: 'NoneType' object is not iterable "container[:] = sorted(container, key=getkey)" confuses me, particularly because I don't see how the elem parameter is passed to the getkey function. I know if I do root = tree.getroot() (from the python.org ElementTree docs) it is possible to step down through the levels of root with root[0], root[0][0], etc, and it seems to be possible to iterate with for i in root[0][0]: print(i) but trying to work root[0][0] into the code has not worked, and tree[0] is not possible. How can I get this code to do its work one level down in the xml? Thanks From davea at davea.name Sat Mar 29 18:01:18 2014 From: davea at davea.name (Dave Angel) Date: Sat, 29 Mar 2014 13:01:18 -0400 (EDT) Subject: [Tutor] ElementTree, iterable container, depth of elements References: <1396047571.2752.100220245.4DE826F7@webmail.messagingengine.com> Message-ID: street.sweeper at mailworks.org Wrote in message: > I'm trying to sort the order of elements in an xml file, mostly > to make visual inspection/comparison easier. The example xml and > code on http://effbot.org/zone/element-sort.htm get me almost > what I need, but the xml I'm working with has the element I'm > trying to sort on one level deeper. > > > That page's example xml: > > > > > Ned > 555-8904 > > > John > 555-5782 > > > Julius > 555-3642 > > > > > > And that page's last example of code: > > import xml.etree.ElementTree as ET > tree = ET.parse("data.xml") > def getkey(elem): > return elem.findtext("number") > container = tree.find("entries") > container[:] = sorted(container,key=getkey) That would be more clearly written sort(container,key=getkey) > tree.write("new-data.xml") > > ...... > Traceback (most recent call last): > File "./xmlSort.py", line 16, in > container[:] = sorted(container, key=getkey) > TypeError: 'NoneType' object is not iterable > That simply tells you that tree.find () returns None. > > "container[:] = sorted(container, key=getkey)" confuses me, > particularly because I don't see how the elem parameter is passed > to the getkey function. > You should play with a list, sorting it with a key function. For example make a list of strings, using a key= def mykey (elem): return elem.lower () To see what's going on, add a print to that function, showing yourself that the sort function will call mykey () on each element. I can't help with the xml stuff, but it seems clear you have to produce a find call that gives you the right list. -- DaveA From __peter__ at web.de Sat Mar 29 18:00:27 2014 From: __peter__ at web.de (Peter Otten) Date: Sat, 29 Mar 2014 18:00:27 +0100 Subject: [Tutor] ElementTree, iterable container, depth of elements References: <1396047571.2752.100220245.4DE826F7@webmail.messagingengine.com> Message-ID: street.sweeper at mailworks.org wrote: > I'm trying to sort the order of elements in an xml file, mostly > to make visual inspection/comparison easier. The example xml and > code on http://effbot.org/zone/element-sort.htm get me almost > what I need, but the xml I'm working with has the element I'm > trying to sort on one level deeper. > > > That page's example xml: > > > > > Ned > 555-8904 > > > John > 555-5782 > > > Julius > 555-3642 > > > > > > And that page's last example of code: > > import xml.etree.ElementTree as ET > tree = ET.parse("data.xml") > def getkey(elem): > return elem.findtext("number") > container = tree.find("entries") > container[:] = sorted(container,key=getkey) > tree.write("new-data.xml") > > I used the interactive shell to experiment a bit with that, > and I can see that 'container' in > > container = tree.find("entries") > > is iterable, using > > for a in container: > print(a) > > However, the xml I'm working with looks something like this: > > >
> > > 20140325 > dentist > > > 20140324 > barber > > >
>
> > > What I'd like to do is rearrange the elements within > based on the element. If I remove the > level, this will work, but I'm interested in getting the code to > work without editing the file. > > I look for "Date" and "diary" rather than "number" and "entries" > but when I try to process the file as-is, I get an error like > > > Traceback (most recent call last): > File "./xmlSort.py", line 16, in > container[:] = sorted(container, key=getkey) > TypeError: 'NoneType' object is not iterable > > > "container[:] = sorted(container, key=getkey)" confuses me, > particularly because I don't see how the elem parameter is passed > to the getkey function. In the original example container is the "entries" element, and sorted() iterates over the items of its first argument. Iteration over an element yield its children, i. e. the first "entry" element, then the second "entry", and so on. > I know if I do > > root = tree.getroot() > > (from the python.org ElementTree docs) it is possible to step > down through the levels of root with root[0], root[0][0], etc, > and it seems to be possible to iterate with > > for i in root[0][0]: > print(i) > > but trying to work root[0][0] into the code has not worked, > and tree[0] is not possible. > > How can I get this code to do its work one level down in the xml? try tree.find("main").find("diary") or container = tree.find("main/diary") or even tree.find(".//diary") # we don't care about the parent From swdunning at me.com Sun Mar 30 00:16:31 2014 From: swdunning at me.com (Scott Dunning) Date: Sat, 29 Mar 2014 16:16:31 -0700 Subject: [Tutor] while loop In-Reply-To: References: <272461FE-60A1-4614-A968-18EC0AF87831@cox.net> Message-ID: On Mar 28, 2014, at 10:36 PM, Ben Finney wrote: > > A good programming exercise will show an example input and the expected > output, to give an unambiguous test case. Does the homework have that? This is what the exercise has as examples? """Print the string `s`, `n` times. Parameters ---------- s -- A string n -- an integer, the number of times to print `s' Examples -------- >>> print_n("hello", 3) hello hello hello >>> print_n("bye", 0) >>> print_n("a", 6) a a a a a a """ assert isinstance(s, str) assert isinstance(n, int) #TODO: Implement the function > > If not, you're unfortunately left to your own interpretation of what the > requirements mean. > I?m not sure what assert isinstance means? This is what I have, it works but I?m not sure it?s what the exercise is asking for. n = 5 def print_n(s, n): while n > 0: print s * n break print_n("hello\n", 10) From swdunning at me.com Sun Mar 30 01:51:17 2014 From: swdunning at me.com (Scott Dunning) Date: Sat, 29 Mar 2014 17:51:17 -0700 Subject: [Tutor] while loop In-Reply-To: References: <272461FE-60A1-4614-A968-18EC0AF87831@cox.net> Message-ID: <9F5F2E3F-84CF-4928-865F-CB32AA1DEE0B@me.com> On Mar 29, 2014, at 12:47 AM, Dave Angel wrote: > > What are you uncertain about, assert or isinstance? Such > statements are frequently used to make sure the function > arguments are of the right type. I?m not sure exactly what it?s doing. I guess I need to read up on it again. > >> >> >> This is what I have so far but I?m not really sure it?s what the excersise is asking for? >> >> n = 5 >> def print_n(s, n): >> while n > 0: >> print s * n >> >> print_n("hello", 10) >> > > So did your code print the string 10 times? When asking for help, > it's useful to show what you tried, and what was expected, and > what actually resulted. Yes it repeated forever, I put a break after the print statement. > > You use * to replicate the string, but that wasn't what the > assignment asked for. So take out the *n part. You're supposed to > use iteration, specifically the while loop. That?s where I was confused, I wasn?t sure how to get the while loop to work just the n times and then stop. > > Your while loop doesn't quit after 10 times, it keeps going. Can > you figure out why? > I understand why it didn?t stop after 10 times, because I said while n is greater than 0 print s, and I have the value of n as 5 so it will never stop, that?s why I added a break after the print statement. I?m sure there is a better way , I?m just not seeing it. Any hints? From swdunning at me.com Sun Mar 30 03:36:43 2014 From: swdunning at me.com (Scott Dunning) Date: Sat, 29 Mar 2014 18:36:43 -0700 Subject: [Tutor] while loop In-Reply-To: References: <272461FE-60A1-4614-A968-18EC0AF87831@cox.net> Message-ID: <397E85C0-1C2C-44AF-9379-A2C8F4E48B86@me.com> On Mar 29, 2014, at 12:47 AM, Dave Angel wrote: > > So did your code print the string 10 times? When asking for help, > it's useful to show what you tried, and what was expected, and > what actually resulted. > > You use * to replicate the string, but that wasn't what the > assignment asked for. So take out the *n part. You're supposed to > use iteration, specifically the while loop. > > Your while loop doesn't quit after 10 times, it keeps going. Can > you figure out why? This works without a break. Is this more a long the line of what the excercise was looking for you think? > def print_n(s, n): while n <= 10: print s n = n + 1 print_n("hello\n", 0) From alan.gauld at btinternet.com Sun Mar 30 13:17:13 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 30 Mar 2014 12:17:13 +0100 Subject: [Tutor] while loop In-Reply-To: <397E85C0-1C2C-44AF-9379-A2C8F4E48B86@me.com> References: <272461FE-60A1-4614-A968-18EC0AF87831@cox.net> <397E85C0-1C2C-44AF-9379-A2C8F4E48B86@me.com> Message-ID: On 30/03/14 02:36, Scott Dunning wrote: >> Your while loop doesn't quit after 10 times, it keeps going. Can >> you figure out why? > > This works without a break. > Is this more a long the line of what the excercise was > looking for you think? Yes. > while n <= 10: > print s > n = n + 1 Python while loops effectively come in two patterns: 1) while some condition do stuff modify the test condition 2) while True: if some condition: break else do stuff The first version is actually the intended use of while from a computing science point of view. The second one, which creates an infinite loop and then breaks out of it is a bit of a kluge which pure structured programming theory says is bad practice. It has become idiomatic in Python however, because it often avoids another bad practice, namely repeating yourself. For example if we only used the first pattern we often need to do this: display_menu() choice = input('pick a choice: ') while choice != 'quit': if choice == 'save': do_save() elif choice == ... display_menu() choice = input('pick a choice: ') Notice how we have to have the menu/input pair both before and inside the loop. We can avoid that using the infinite loop version: while True: display_menu() choice = input('pick a choice: ') if choice == 'quit' break elif choice == 'save': do_save() elif choice == ... So we have effectively chosen the lesser of two evils. Compromising on computer science purity is not unusual in the real world of programming. In your example there was no need to repeat code so you could use the uncompromised, pure while loop with an effective test condition. In that case you can and should modify the test condition variables inside the loop, which is what you did with the n = n+1 line. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From davea at davea.name Sun Mar 30 13:29:03 2014 From: davea at davea.name (Dave Angel) Date: Sun, 30 Mar 2014 07:29:03 -0400 (EDT) Subject: [Tutor] while loop References: <272461FE-60A1-4614-A968-18EC0AF87831@cox.net> <397E85C0-1C2C-44AF-9379-A2C8F4E48B86@me.com> Message-ID: Scott Dunning Wrote in message: > > On Mar 29, 2014, at 12:47 AM, Dave Angel wrote: >> >> So did your code print the string 10 times? When asking for help, >> it's useful to show what you tried, and what was expected, and >> what actually resulted. >> >> You use * to replicate the string, but that wasn't what the >> assignment asked for. So take out the *n part. You're supposed to >> use iteration, specifically the while loop. >> >> Your while loop doesn't quit after 10 times, it keeps going. Can >> you figure out why? > > This works without a break. Is this more a long the line of what the excercise was looking for you think? >> > def print_n(s, n): > while n <= 10: > print s > n = n + 1 > > print_n("hello\n", 0) > > > You're getting closer. Remember that the assignment shows your function being called with 10, not zero. So you should have a separate local variable, probably called I, which starts at zero, and gets incremented each time. The test in the while should be comparing them. Note that the number of times is specified in top level code, and implemented in the function. You should not have a literal 10 in the function. -- DaveA From swdunning at me.com Mon Mar 31 03:37:30 2014 From: swdunning at me.com (Scott Dunning) Date: Sun, 30 Mar 2014 18:37:30 -0700 Subject: [Tutor] while loop In-Reply-To: References: <272461FE-60A1-4614-A968-18EC0AF87831@cox.net> <397E85C0-1C2C-44AF-9379-A2C8F4E48B86@me.com> Message-ID: <9051BFE9-31B5-4DFF-B279-A37CD37C5EE9@me.com> On Mar 30, 2014, at 4:29 AM, Dave Angel wrote: > > > You're getting closer. Remember that the assignment shows your > function being called with 10, not zero. So you should have a > separate local variable, probably called I, which starts at > zero, and gets incremented each time. The exercise just asks to print (s), (n) times using iteration. The exersise is in a doctest which I didn?t really understand at first. So, I guess while I was doing it ?correctly? it wasn?t what the exercise is asking for. This I guess is what the doctest is looking for. """Print the string `s`, `n` times. Parameters ---------- s -- A string n -- an integer, the number of times to print `s' Examples -------- >>> print_n("hello", 3) hello hello hello >>> print_n("bye", 0) >>> print_n("a", 6) a a a a a a """ > > The test in the while should be comparing them. > > Note that the number of times is specified in top level code, and > implemented in the function. You should not have a literal 10 in > the function. Without out a break or placing that 10 in there I can?t think of a way to have the while loop stop once it reaches (n). Any hints? SCott From swdunning at me.com Mon Mar 31 04:13:00 2014 From: swdunning at me.com (Scott Dunning) Date: Sun, 30 Mar 2014 19:13:00 -0700 Subject: [Tutor] while loop In-Reply-To: References: <272461FE-60A1-4614-A968-18EC0AF87831@cox.net> <397E85C0-1C2C-44AF-9379-A2C8F4E48B86@me.com> Message-ID: <5D78B877-4314-4FA8-A547-A402F962A6E2@me.com> On Mar 30, 2014, at 4:29 AM, Dave Angel wrote: > > You're getting closer. Remember that the assignment shows your > function being called with 10, not zero. So you should have a > separate local variable, probably called I, which starts at > zero, and gets incremented each time. > > The test in the while should be comparing them. > So, this is what I have now and it ?works? but, instead of printing (s) on seperate lines they?re all on the same line? def print_n(s,n): while n < 10: print s * n break assert isinstance(s, str) assert isinstance(n, int) From breamoreboy at yahoo.co.uk Mon Mar 31 10:39:31 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 31 Mar 2014 09:39:31 +0100 Subject: [Tutor] while loop In-Reply-To: <5D78B877-4314-4FA8-A547-A402F962A6E2@me.com> References: <272461FE-60A1-4614-A968-18EC0AF87831@cox.net> <397E85C0-1C2C-44AF-9379-A2C8F4E48B86@me.com> <5D78B877-4314-4FA8-A547-A402F962A6E2@me.com> Message-ID: On 31/03/2014 03:13, Scott Dunning wrote: > > On Mar 30, 2014, at 4:29 AM, Dave Angel wrote: >> >> You're getting closer. Remember that the assignment shows your >> function being called with 10, not zero. So you should have a >> separate local variable, probably called I, which starts at >> zero, and gets incremented each time. >> >> The test in the while should be comparing them. >> > So, this is what I have now and it ?works? but, instead of printing (s) on seperate lines they?re all on the same line? > > def print_n(s,n): > while n < 10: > print s * n > break > assert isinstance(s, str) > assert isinstance(n, int) > They say that the truth hurts, so if that's the best you can come up with, I suggest you give up programming :( -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From alan.gauld at btinternet.com Mon Mar 31 11:01:02 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 31 Mar 2014 10:01:02 +0100 Subject: [Tutor] while loop In-Reply-To: <9051BFE9-31B5-4DFF-B279-A37CD37C5EE9@me.com> References: <272461FE-60A1-4614-A968-18EC0AF87831@cox.net> <397E85C0-1C2C-44AF-9379-A2C8F4E48B86@me.com> <9051BFE9-31B5-4DFF-B279-A37CD37C5EE9@me.com> Message-ID: On 31/03/14 02:37, Scott Dunning wrote: >> You're getting closer. Remember that the assignment shows your >> function being called with 10, not zero. So you should have a >> separate local variable, probably called I, which starts at >> zero, and gets incremented each time. > Without out a break or placing that 10 in there I can?t think > of a way to have the while loop stop once it reaches (n). Dave has explained in his first paragraph(above) how to do it. n is a parameter in your function so the value is passed in by the caller. You should not be using a literal 10 you should be using n, since that's the required number of repeats. Then you need to create a new local variable in your function and let that variable count up until it equals whatever n is. That's where the iteration comes in. And as you count up, towards n, print s. hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Mon Mar 31 11:01:35 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 31 Mar 2014 10:01:35 +0100 Subject: [Tutor] while loop In-Reply-To: <5D78B877-4314-4FA8-A547-A402F962A6E2@me.com> References: <272461FE-60A1-4614-A968-18EC0AF87831@cox.net> <397E85C0-1C2C-44AF-9379-A2C8F4E48B86@me.com> <5D78B877-4314-4FA8-A547-A402F962A6E2@me.com> Message-ID: On 31/03/14 03:13, Scott Dunning wrote: >> separate local variable, probably called I, which starts at >> zero, and gets incremented each time. >> >> The test in the while should be comparing them. >> > So, this is what I have now and it ?works? It doesn't work because they are all on the same line. But also because it does NOT use iteration. Your while loop is completely redundant. You could remove the while and break lines and it would do exactly the same. > def print_n(s,n): > while n < 10: > print s * n > break You're other attempt where you increment n is much closer to what is being asked for. The only difference is you need to modify the while test to not use a hard coded 10 but use the parameter instead. Then use a separate value to do the counting. Incidentally, your assignment does not appear to require a while loop, just iteration? If thats the case you could use a for loop instead and it would actually be more suitable. Have you covered for loops yet? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From davea at davea.name Mon Mar 31 14:15:41 2014 From: davea at davea.name (Dave Angel) Date: Mon, 31 Mar 2014 08:15:41 -0400 (EDT) Subject: [Tutor] while loop References: <272461FE-60A1-4614-A968-18EC0AF87831@cox.net> <397E85C0-1C2C-44AF-9379-A2C8F4E48B86@me.com> <5D78B877-4314-4FA8-A547-A402F962A6E2@me.com> Message-ID: Scott Dunning Wrote in message: > > On Mar 30, 2014, at 4:29 AM, Dave Angel wrote: >> >> You're getting closer. Remember that the assignment shows your >> function being called with 10, not zero. So you should have a >> separate local variable, probably called I, which starts at >> zero, and gets incremented each time. >> >> The test in the while should be comparing them. >> > So, this is what I have now and it ???works??? but, instead of printing (s) on seperate lines they???re all on the same line? > > def print_n(s,n): > while n < 10: > print s * n > break > assert isinstance(s, str) > assert isinstance(n, int) > > So much for getting closer. Go back to the version I replied to. Do you know how to define and initialize a second local variable? Create one called i, with a value zero. You test expression will not have a literal, but compare the two locals. And the statement that increments will change i, not n. -- DaveA From welcome.to.eye.o.rama at gmail.com Mon Mar 31 15:38:15 2014 From: welcome.to.eye.o.rama at gmail.com (John Aten) Date: Mon, 31 Mar 2014 08:38:15 -0500 Subject: [Tutor] Storing dictionary value, indexed by key, into a variable Message-ID: <8D6408E3-43DD-4235-8F78-B6E1F1FB3EA3@gmail.com> Hey all, I am writing a program to drill the user on Latin demonstrative pronouns and adjectives (DPA). It displays a description, and the user has to enter the DPA that corresponds to the description. DPA vary for gender, number and case, and there are 3 separate DPA. I have these stored in a bunch of dictionaries, with the DPA, gender and number in the dictionary name and the cases as keys. Of course, the values are the DPA themselves. Like so: that_those_Masculine_Singular = {'nom': 'ille', 'gen': 'ill?us', 'dat': 'ill?', 'acc': 'illum', 'abl': 'ill?'} I have a function that randomly selects one of these dictionaries, and another that randomly selects strings corresponding to the keys ('nom', 'gen', etc.). The trouble begins somewhere along here: D = chooseDict() c = chooseCase() print(D, c) guess = '' # code to get the guess # then, answer = D[c] if guess == answer: # Do stuff, change score, continue, etc. This doesn't work, and I get this error: TypeError: string indices must be integers So my question is, why does Python think that D is a string? When I type the actual names (i.e., that_those_Masculine_Singular["nom"]) the answer is returned just fine. I have tried D['c'] and D["c"] also, and got the same error. I searched the web, and I can find no explanation on how to do what I am doing, and I can find nothing that indicates why this doesn't work. I'd really appreciate any help! Thank you, J From david at graniteweb.com Mon Mar 31 15:45:32 2014 From: david at graniteweb.com (David Rock) Date: Mon, 31 Mar 2014 08:45:32 -0500 Subject: [Tutor] while loop In-Reply-To: <9051BFE9-31B5-4DFF-B279-A37CD37C5EE9@me.com> References: <272461FE-60A1-4614-A968-18EC0AF87831@cox.net> <397E85C0-1C2C-44AF-9379-A2C8F4E48B86@me.com> <9051BFE9-31B5-4DFF-B279-A37CD37C5EE9@me.com> Message-ID: <20140331134532.GA30896@wdfs.graniteweb.com> * Scott Dunning [2014-03-30 18:37]: > Without out a break or placing that 10 in there I can?t think of a way > to have the while loop stop once it reaches (n). Any hints? As discussed already, you can't use fixed values (ie, you don't know that 10 is always going to be there). > def print_n(s, n): > while n <= 10: > print s > n = n + 1 > So, instead of while n <= 10: Think about: while something <= n: and changing something and retesting. -- David Rock david at graniteweb.com From akleider at sonic.net Mon Mar 31 16:08:34 2014 From: akleider at sonic.net (Alex Kleider) Date: Mon, 31 Mar 2014 07:08:34 -0700 Subject: [Tutor] Storing dictionary value, indexed by key, into a variable In-Reply-To: <8D6408E3-43DD-4235-8F78-B6E1F1FB3EA3@gmail.com> References: <8D6408E3-43DD-4235-8F78-B6E1F1FB3EA3@gmail.com> Message-ID: On 2014-03-31 06:38, John Aten wrote: > Hey all, > > I am writing a program to drill the user on Latin demonstrative > pronouns and adjectives (DPA). It displays a description, and the user > has to enter the DPA that corresponds to the description. DPA vary for > gender, number and case, and there are 3 separate DPA. I have these > stored in a bunch of dictionaries, with the DPA, gender and number in > the dictionary name and the cases as keys. Of course, the values are > the DPA themselves. Like so: > > that_those_Masculine_Singular = {'nom': 'ille', 'gen': 'ill?us', > 'dat': 'ill?', 'acc': 'illum', 'abl': 'ill?'} > > I have a function that randomly selects one of these dictionaries, and > another that randomly selects strings corresponding to the keys > ('nom', 'gen', etc.). The trouble begins somewhere along here: > > D = chooseDict() > c = chooseCase() > > print(D, c) > > guess = '' > # code to get the guess > # then, > answer = D[c] > > if guess == answer: > # Do stuff, change score, continue, etc. > > This doesn't work, and I get this error: > > TypeError: string indices must be integers > > So my question is, why does Python think that D is a string? When I > type the actual names (i.e., that_those_Masculine_Singular["nom"]) the > answer is returned just fine. I have tried D['c'] and D["c"] also, and > got the same error. I searched the web, and I can find no explanation > on how to do what I am doing, and I can find nothing that indicates > why this doesn't work. I'd really appreciate any help! > > Thank you, > > J > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor Assuming that it is the answer = D[c] statement is giving you the TypeError, I suggest you add the following print statements just before it: print("'D' is of type %s"%(type(D), ) print("'c' = %s and is of type %s."%(c, type(c), ) You might get some surprises. From __peter__ at web.de Mon Mar 31 16:18:58 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 31 Mar 2014 16:18:58 +0200 Subject: [Tutor] Storing dictionary value, indexed by key, into a variable References: <8D6408E3-43DD-4235-8F78-B6E1F1FB3EA3@gmail.com> Message-ID: John Aten wrote: > Hey all, > > I am writing a program to drill the user on Latin demonstrative pronouns > and adjectives (DPA). It displays a description, and the user has to enter > the DPA that corresponds to the description. DPA vary for gender, number > and case, and there are 3 separate DPA. I have these stored in a bunch of > dictionaries, with the DPA, gender and number in the dictionary name and > the cases as keys. Of course, the values are the DPA themselves. Like so: > > that_those_Masculine_Singular = {'nom': 'ille', 'gen': 'ill?us', 'dat': > 'ill?', 'acc': 'illum', 'abl': 'ill?'} > > I have a function that randomly selects one of these dictionaries, and > another that randomly selects strings corresponding to the keys ('nom', > 'gen', etc.). The trouble begins somewhere along here: Unfortunately the problem is in the code you don't show. You might add the line > D = chooseDict() print("D is of type", type(D)) and if that prints D is of type you can be sure that the problem originates in the chooseDict() function. Try to find the error yourself first, looking closely at the function's code, and if you run out of ideas or places where you can put print() calls for debugging purposes come back here. Don't forget to include the code this time. > c = chooseCase() > > print(D, c) > > guess = '' > # code to get the guess > # then, > answer = D[c] > > if guess == answer: > # Do stuff, change score, continue, etc. > > This doesn't work, and I get this error: > > TypeError: string indices must be integers As a general note, error messages are most useful when the are accompanied by the traceback. As it stands I have no idea what line triggers the error; you might have the line ""[""] somewhere in your code. > So my question is, why does Python think that D is a string? When I type > the actual names (i.e., that_those_Masculine_Singular["nom"]) the answer > is returned just fine. I have tried D['c'] and D["c"] also, and got the > same error. I searched the web, and I can find no explanation on how to do > what I am doing, and I can find nothing that indicates why this doesn't > work. I'd really appreciate any help! If the D in the line D = chooseDict() is actually a dict you are most certainly reassigning D = "some string" or you have two different variables named "D" in separate scopes. From hgandhi7760 at yahoo.com Mon Mar 31 16:36:45 2014 From: hgandhi7760 at yahoo.com (Hardik Gandhi) Date: Mon, 31 Mar 2014 10:36:45 -0400 Subject: [Tutor] Fwd: Python bingo game. References: <2FBCC06A-A81B-41C9-8C67-F808F2AA28F0@yahoo.com> Message-ID: > Hello, > > Can some one help me with displaying a matrix vertically. > > For example my output matrix is:- > > [1 2 5 7 9] > [25 67 78 23 34] > [33 22 66 88 98] > [32 31 41 56 78] > [21 34 58 99 76] > > And i want my matrix to look like this:- > [1 25 33 32 21] > [2 67 22 31 34] > [5 78 66 41 58] > [7 23 88 56 99] > [9 34 98 78 76] > > Please, help me with the code in eclipse using py-dev as preference. > > Thank you From dyoo at hashcollision.org Mon Mar 31 21:49:20 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 31 Mar 2014 12:49:20 -0700 Subject: [Tutor] Fwd: Python bingo game. In-Reply-To: References: <2FBCC06A-A81B-41C9-8C67-F808F2AA28F0@yahoo.com> Message-ID: >> Can some one help me with displaying a matrix vertically. >> >> For example my output matrix is:- >> >> [1 2 5 7 9] >> [25 67 78 23 34] >> [33 22 66 88 98] >> [32 31 41 56 78] >> [21 34 58 99 76] >> >> And i want my matrix to look like this:- >> [1 25 33 32 21] >> [2 67 22 31 34] >> [5 78 66 41 58] >> [7 23 88 56 99] >> [9 34 98 78 76] You have described the "matrix transpose" problem, which is fairly standard homework as an introductory list-processing exercise. Your comment about PyDev and Eclipse is technically irrelevant, so we have to ignore that part of your question. Why should it matter what your program is written in, as long as it's a program? What difficulty are you having? I need to be straightforward so that you understand, without ambiguity: we do not do your homework. We will not violate the honor code of your institution. To do so is anathema to why folks here volunteer to help beginners. We will be happy to help with coding questions or techniques. In some cases, we'll also try to help present problem solving techniques. Have you done a problem that has any similarity to the problem you're tackling now? Have you written functions that work on matrices before? Do you have any smaller test cases? Starting on the 5x5 case is large. Have you considered smaller cases like the 1x1 and 2x2 matrices? Are your matrices always square? What is the representation of your data? What is the type of your input? Can you describe it precisely? What is the type of your output? Can you describe it precisely? From dyoo at hashcollision.org Mon Mar 31 22:00:20 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 31 Mar 2014 13:00:20 -0700 Subject: [Tutor] Storing dictionary value, indexed by key, into a variable In-Reply-To: <8D6408E3-43DD-4235-8F78-B6E1F1FB3EA3@gmail.com> References: <8D6408E3-43DD-4235-8F78-B6E1F1FB3EA3@gmail.com> Message-ID: > So my question is, why does Python think that D is a string? Assume that Python is telling the truth, at least unless something really unusual is happening. :P Assume D is a string. Your question should really be: why is D a string? Where does "D" get assigned? --- Also note that in your presentation of the bug, the presentation omits a bit of the error message: It presents the error message text, but not the entire "traceback". You don't need to do that, and in fact, you will usually want to be verbose. The context in which the error occurs might be helpful: in particular, you might be misinterpreting the subject or object of the error message. Without seeing context, we can't do a cursory confirmation that the error matches your diagnosis. We want to verify by looking at symptoms. Don't curtail error messages and stack traces, but include them next time.