[Tutor] Please Help
Hi, I have another small problem. Pls help. I have written the following code: f = open ("digi_2.txt", "r+") lines = f.readlines() for line in lines: number_list = [] for number in line.split(','): number_list.append(float(number)) s_data = [] for i in range(len(number_list)): if number_list[i] > 5: s_data = number_list[i] print 'Data val:', s_data The problem is: it is printing only the last value, not all the values. In this case '10', not '9,8,6,10'. Regards, Arijit Ukil Tata Consultancy Services Mailto: arijit.u...@tcs.com Website: http://www.tcs.com Experience certainty. IT Services Business Solutions Outsourcing From: Amit Saha To: Arijit Ukil Cc: tutor@python.org Date: 03/21/2013 05:30 PM Subject: Re: [Tutor] Please Help Hi Arijit, On Thu, Mar 21, 2013 at 8:42 PM, Arijit Ukil wrote: > > I am new to python. I like to calculate average of the numbers by reading > the file 'digi_2.txt'. I have written the following code: > > def average(s): return sum(s) * 1.0 / len(s) > > f = open ("digi_2.txt", "r+") > > list_of_lists1 = f.readlines() > > > for index in range(len(list_of_lists1)): > > > tt = list_of_lists1[index] > > print 'Current value :', tt > > avg =average (tt) > > > This gives an error: > > def average(s): return sum(s) * 1.0 / len(s) > TypeError: unsupported operand type(s) for +: 'int' and 'str' > > I also attach the file i am reading. > > > > Please help to rectify. The main issue here is that when you are reading from a file, to Python, its all strings. And although, 'abc' + 'def' is valid, 'abc' + 5 isn't (for example). Hence, besides the fact that your average calculation is not right, you will have to 'convert' the string to an integer/float to do any arithmetic operation on them. (If you know C, this is similar to typecasting). So, coming back to your program, I will first demonstrate you a few things and then you can write the program yourself. If you were to break down this program into simple steps, they would be: 1. Read the lines from a file (Assume a generic case, where you have more than one line in the file, and you have to calculate the average for each such row) 2. Create a list of floating point numbers for each of those lines 3. And call your average function on each of these lists You could of course do 2 & 3 together, so you create the list and call the average function. So, here is step 1: with open('digi.txt','r') as f: lines = f.readlines() Please refer to http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects for an explanation of the advantage of using 'with'. Now, you have *all* the lines of the file in 'lines'. Now, you want to perform step 2 for each line in this file. Here you go: for line in lines: number_list = [] for number in line.split(','): number_list.append(float(number)) (To learn more about Python lists, see http://effbot.org/zone/python-list.htm). It is certainly possible to use the index of an element to access elements from a list, but this is more Pythonic way of doing it. To understand this better, in the variable 'line', you will have a list of numbers on a single line. For example: 1350696461, 448.0, 538660.0, 1350696466, 448.0. Note how they are separated by a ',' ? To get each element, we use the split( ) function, which returns a list of the individual numbers. (See: http://docs.python.org/2/library/stdtypes.html#str.split). And then, we use the .append() method to create the list. Now, you have a number_list which is a list of floating point numbers for each line. Now, step 2 & 3 combined: for line in lines: number_list = [] for number in line.split(','): number_list.append(float(number)) print average(number_list) Where average( ) is defined as: def average(num_list): return sum(num_list)/len(num_list) There may be a number of unknown things I may have talked about, but i hope the links will help you learn more and write your program now. Good Luck. -Amit. -- http://amitsaha.github.com/ =-=-= Notice: The information contained in this e-mail message and/or attachments to it may contain confidential or privileged information. If you are not the intended recipient, any dissemination, use, review, distribution, printing or copying of the information contained in this e-mail message and/or attachments to it are strictly prohibited. If you have received this communication in error, please notify us by reply e-mail or telephone and immediately and permanently delete the message and any attachments. Thank you 1,0,9,0,8,6,0,10___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Please Help
Hi Arijit, I have modified your program a bit and it is working fine for me. Values greater than 5 are being printed. Here is the code: f = open ("D:\\digi_2.txt", "r+") lines = f.readlines() number_list = [] for line in lines: print line for number in line.split(','): #number_list.append(float(number)) number_list.append(int(number)) s_data = [] for i in number_list: print i #if number_list[i] > 5: if(i>5):s_data.append(i) for x in s_data:print 'Data val:', float(x) RegardsSuhas To: tutor@python.org From: arijit.u...@tcs.com Date: Fri, 22 Mar 2013 12:54:01 +0530 Subject: [Tutor] Please Help Hi, I have another small problem. Pls help. I have written the following code: f = open ("digi_2.txt", "r+") lines = f.readlines() for line in lines: number_list = [] for number in line.split(','): number_list.append(float(number)) s_data = [] for i in range(len(number_list)): if number_list[i] > 5: s_data = number_list[i] print 'Data val:', s_data The problem is: it is printing only the last value, not all the values. In this case '10', not '9,8,6,10'. Regards, Arijit Ukil Tata Consultancy Services Mailto: arijit.u...@tcs.com Website: http://www.tcs.com Experience certainty.IT Services Business Solutions Outsourcing From: Amit Saha To: Arijit Ukil Cc: tutor@python.org Date: 03/21/2013 05:30 PM Subject: Re: [Tutor] Please Help Hi Arijit, On Thu, Mar 21, 2013 at 8:42 PM, Arijit Ukil wrote: > > I am new to python. I like to calculate average of the numbers by reading > the file 'digi_2.txt'. I have written the following code: > > def average(s): return sum(s) * 1.0 / len(s) > > f = open ("digi_2.txt", "r+") > > list_of_lists1 = f.readlines() > > > for index in range(len(list_of_lists1)): > > > tt = list_of_lists1[index] > > print 'Current value :', tt > > avg =average (tt) > > > This gives an error: > > def average(s): return sum(s) * 1.0 / len(s) > TypeError: unsupported operand type(s) for +: 'int' and 'str' > > I also attach the file i am reading. > > > > Please help to rectify. The main issue here is that when you are reading from a file, to Python, its all strings. And although, 'abc' + 'def' is valid, 'abc' + 5 isn't (for example). Hence, besides the fact that your average calculation is not right, you will have to 'convert' the string to an integer/float to do any arithmetic operation on them. (If you know C, this is similar to typecasting). So, coming back to your program, I will first demonstrate you a few things and then you can write the program yourself. If you were to break down this program into simple steps, they would be: 1. Read the lines from a file (Assume a generic case, where you have more than one line in the file, and you have to calculate the average for each such row) 2. Create a list of floating point numbers for each of those lines 3. And call your average function on each of these lists You could of course do 2 & 3 together, so you create the list and call the average function. So, here is step 1: with open('digi.txt','r') as f: lines = f.readlines() Please refer to http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects for an explanation of the advantage of using 'with'. Now, you have *all* the lines of the file in 'lines'. Now, you want to perform step 2 for each line in this file. Here you go: for line in lines: number_list = [] for number in line.split(','): number_list.append(float(number)) (To learn more about Python lists, see http://effbot.org/zone/python-list.htm). It is certainly possible to use the index of an element to access elements from a list, but this is more Pythonic way of doing it. To understand this better, in the variable 'line', you will have a list of numbers on a single line. For example: 1350696461, 448.0, 538660.0, 1350696466, 448.0. Note how they are separated by a ',' ? To get each element, we use the split( ) function, which returns a list of the individual numbers. (See: http://docs.python.org/2/library/stdtypes.html#str.split). And then, we use the .append() method to create the list. Now, you have a number_list which is a list of floating point numbers for each line. Now, step 2 & 3 combined: for line in lines: number_list = [] for number in line.split(','): number_list.append(float(number)) print average(number_list) Where average( ) is defined as: def average(num_list): return sum(num_list)/len(num_list) There may be a number of unknown things I may have talked about, but i hope the links will help you learn more and write your program now. Good
Re: [Tutor] Please Help
On 22/03/13 07:24, Arijit Ukil wrote: f = open ("digi_2.txt", "r+") lines = f.readlines() for line in lines: number_list = [] for number in line.split(','): number_list.append(float(number)) s_data = [] for i in range(len(number_list)): You hardly ever need to do this, its much simpler to just iterate over the list items directly: for number in number_list: if number_list[i] > 5: s_data = number_list[i] Note that you are overwriting your list with a single value. You need to do what you did above and use append(). *The problem is: it is printing only the last value, not all the values. In this case '10', **not**'9,8,6,10'.* Because you overwrote the list each time. You need to remember to append data to lists not replace the list. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Starting a simple python project
Greetings all! My name is Miguel Guasch, I'm a software tester who's trying to slowly get into automation, and eventually (in a couple of years) into development. For that, I need to learn. At the moment I'm studying computer engineering in the evenings, and we do a lot of work in C and assembly. Java will be coming at some time, but not for the moment. So I decided to learn python as a side project, so I could get my feet wet with OOP and start actually being productive. I understand the basics of OOP thanks to a class I took about object modelling and design (UML on Enterprise Architect) In order to better learn python, I'm trying to "automate" (or make it easier to do) repetitive tasks here in the company. Like, for example: We have to write a daily "status" e-mail of our tasks, divided into: planned for tomorrow, open tasks, finished tasks, general findings. I thought I could take it upon me to write a small program to, instead of writing these e-mails at the end of the day, we could just have the program open, and, as soon as we start working on a task, we enter it, and before we close it, we can write "general findings" to it. It would work like this in the beginning: Open the program, import a new template, write the open tasks you have (and any you receive during the day), and then start working on a certain task. While working on the task, you can write a "general findings" entry to it, and when you're done, you "close it" (meaning, you open the next one). The tasks have specific ID numbers based on our ClearQuest entry numbers, so it would be easy to match the open and finished tasks, and substact the finished from the done ones. At the end of the day, you can click on "end" and it would generate a simple text file with a very simple formatting, like: Planned for tomorrow: 1. 2.. And the same with the others. We could then just copy the text files contents and paste them into a regular outlook e-mail This is a simple start, but in the future I'd like to be able to store these tasks in a folder and name the text files with the days date, so I can "import" them back in case I need to look at it. I'd also like to make a small dictionary with the names and e-mail addresses of the people who should receive the e-mail, and somehow either copy the text into an outlook e-mail, or directly send it over SMTP (whichever is simpler) I'm having a hard time actually starting, but so far I have a basic idea and it shouldn't be too hard. I'm planning to use wxPython on Windows 7 because it looks pretty simple so far and it also looks elegant enough :-) If you guys/gals could comment on this, or give me some kind of advice, I'd be more than thankful. I'll be sure to let you know how it goes, and share the source. Thanks, everyone! All the best! Miguel A. Guasch miguel.gua...@hushmail.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Please Help
I have the following data points. data = [1,2,0,9,0,1,4] I like to store in an array and print the odd-indexed points, i.e. 2, 9,1 (considering index starts at 0) I have written the following code which is not running: import math number_list = [1,2,0,9,0,1,4] number_list_1 = [] for k in range(math.floor(float(len(number_list)/2))): if (k< math.floor(float(len(number_list)/2))): number_list_1[k] = number_list[k*2 + 1] print 'data: ', number_list_1 Please help Regards, Arijit Ukil Tata Consultancy Services Mailto: arijit.u...@tcs.com Website: http://www.tcs.com Experience certainty. IT Services Business Solutions Outsourcing =-=-= Notice: The information contained in this e-mail message and/or attachments to it may contain confidential or privileged information. If you are not the intended recipient, any dissemination, use, review, distribution, printing or copying of the information contained in this e-mail message and/or attachments to it are strictly prohibited. If you have received this communication in error, please notify us by reply e-mail or telephone and immediately and permanently delete the message and any attachments. Thank you ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Please Help
Please use a meaningful subject. On 22.03.2013 13:37, Arijit Ukil wrote: I have the following data points. data = [1,2,0,9,0,1,4] I like to store in an array and print the odd-indexed points, i.e. 2, 9,1 (considering index starts at 0) You can simply slice your list: >>> data = [1, 2, 0, 9, 0, 1, 4] >>> number_list = data[1::2] >>> number_list [2, 9, 1] See also http://docs.python.org/3/library/stdtypes.html#common-sequence-operations Bye, Andreas ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Please Help
On Fri, Mar 22, 2013 at 6:07 PM, Arijit Ukil wrote: > I have the following data points. > data = [1,2,0,9,0,1,4] > I like to store in an array and print the odd-indexed points, i.e. 2, 9,1 > (considering index starts at 0) > > *I have written the following code which is** not **running:* > > import math > > number_list = [1,2,0,9,0,1,4] > > number_list_1 = [] > for k in range(math.floor(float(len(number_list)/2))): > if (k< math.floor(float(len(number_list)/2))): > number_list_1[k] = number_list[k*2 + 1] > > print *'data: '*, number_list_1 > > Please help > > Regards, > I would suggest that your roblems have more to do with insufficient understanding of basic constructs, and that you should work on them, "Learn Python the hard way" a book by Zed Shaw is a good one. Why do I say that? Among other things, k< math.floor(float(len(number_list)/2)) is very poor in any language. Asokan Pichai The root of all superstition is that men observe when a thing hits, but not when it misses. -- Francis Bacon ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Please Help
Greetings, : I have the following data points. : data = [1,2,0,9,0,1,4] : I like to store in an array and print the odd-indexed points, i.e. 2, 9,1 : (considering index starts at 0) : : I have written the following code which is not running: : : import math : : number_list = [1,2,0,9,0,1,4] : : number_list_1 = [] : for k in range(math.floor(float(len(number_list)/2))): : if (k< math.floor(float(len(number_list)/2))): : number_list_1[k] = number_list[k*2 + 1] : : print 'data: ', number_list_1 My first thought when I see the above is that you appear to be taking a circuitous route to the market! You must really want to get your exercise on your journey to fetch the list of [2, 9, 1]. My second observation is that the looping over a list using the technique you showed here (and in your prior mail) is something that looks more like C or Java. Looping on an list (array, or any sort of sequence) is a bit easier here in the lands of Python. You can simply: for item in list_data: # -- do something with item Since you are in the lands of Python (and welcome, by the way), the Python docs are pretty good (and not overwhelming), and include some excellent examples, so try reading about sequences and how to manipulate them at this online doc: http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange Anyway, I think you may benefit from seeing this solution a bit more Pythonically, so I have offered two different solutions. -Martin data = number_list = [1,2,0,9,0,1,4] # -- you call it 'number_list_1'; I will call it 'outlist' # outlist = [] for idx,val in enumerate(data): print idx, val if 0 == (idx % 2): # -- skip even entries; do not append continue outlist.append(val) print 'loop over enumerate() to get your data: ', outlist # -- OR, given how simple your operation on the list is, consider #learning about slicing; see the standard docs on sequences: # # http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange # print 'slice out from your original data: ', data[1::2] -- Martin A. Brown http://linux-ip.net/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Starting a simple python project
On 3/22/2013 5:02 AM, miguel.gua...@hushmail.com wrote: Greetings all! Hi. I decided to learn python as a side project, so I could get my feet wet with OOP and start actually being productive. I understand the basics of OOP thanks to a class I took about object modelling and design (UML on Enterprise Architect) In order to better learn python, I'm trying to "automate" (or make it easier to do) repetitive tasks here in the company. IMHO this is not a simple project. I suggest you start with something a lot simpler so you can focus on learning Python rather than all the complexities involved in the daily "status" e-mail project (which includes learning wxPython). When you do tackle daily "status" e-mail - start with one step. A good starting point is to clarify the project (expand the description, be very specific, draw pictures of the user interface, ...) Have you gone through any Python tutorials? Might be a good idea. Personally I'd tackle a task like thhis using Access rather than Python. Like, for example: We have to write a daily "status" e-mail of our tasks, divided into: planned for tomorrow, open tasks, finished tasks, general findings. I thought I could take it upon me to write a small program to, instead of writing these e-mails at the end of the day, we could just have the program open, and, as soon as we start working on a task, we enter it, and before we close it, we can write "general findings" to it. It would work like this in the beginning: Open the program, import a new template, write the open tasks you have (and any you receive during the day), and then start working on a certain task. While working on the task, you can write a "general findings" entry to it, and when you're done, you "close it" (meaning, you open the next one). The tasks have specific ID numbers based on our ClearQuest entry numbers, so it would be easy to match the open and finished tasks, and substact the finished from the done ones. At the end of the day, you can click on "end" and it would generate a simple text file with a very simple formatting, like: Planned for tomorrow: 1. 2.. And the same with the others. We could then just copy the text files contents and paste them into a regular outlook e-mail This is a simple start, but in the future I'd like to be able to store these tasks in a folder and name the text files with the days date, so I can "import" them back in case I need to look at it. I'd also like to make a small dictionary with the names and e-mail addresses of the people who should receive the e-mail, and somehow either copy the text into an outlook e-mail, or directly send it over SMTP (whichever is simpler) I'm having a hard time actually starting, but so far I have a basic idea and it shouldn't be too hard. I'm planning to use wxPython on Windows 7 because it looks pretty simple so far and it also looks elegant enough :-) If you guys/gals could comment on this, or give me some kind of advice, I'd be more than thankful. I'll be sure to let you know how it goes, and share the source. Thanks, everyone! All the best! Miguel A. Guasch miguel.gua...@hushmail.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Starting a simple python project
On 03/22/2013 05:02 AM, miguel.gua...@hushmail.com wrote: Greetings all! > > > My name is Miguel Guasch, I'm a software tester who's trying to > slowly get into automation, and eventually (in a couple of years) > into development. For that, I need to learn. At the moment I'm > studying computer engineering in the evenings, and we do a lot of > work in C and assembly. Java will be coming at some time, but not > for the moment. So I decided to learn python as a side project, so > I could get my feet wet with OOP and start actually being > productive. I understand the basics of OOP thanks to a class I took > about object modelling and design (UML on Enterprise Architect) > > In order to better learn python, I'm trying to "automate" (or make > it easier to do) repetitive tasks here in the company. > > Like, for example: > > We have to write a daily "status" e-mail of our tasks, divided > into: planned for tomorrow, open tasks, finished tasks, general > findings. > > I thought I could take it upon me to write a small program to, > instead of writing these e-mails at the end of the day, we could > just have the program open, and, as soon as we start working on a > task, we enter it, and before we close it, we can write "general > findings" to it. > > It would work like this in the beginning: Open the program, import > a new template, write the open tasks you have (and any you receive > during the day), and then start working on a certain task. While > working on the task, you can write a "general findings" entry to > it, and when you're done, you "close it" (meaning, you open the > next one). The tasks have specific ID numbers based on our > ClearQuest entry numbers, so it would be easy to match the open and > finished tasks, and substact the finished from the done ones. > > At the end of the day, you can click on "end" and it would generate > a simple text file with a very simple formatting, like: > > Planned for tomorrow: > 1. > 2.. > > And the same with the others. > > We could then just copy the text files contents and paste them into > a regular outlook e-mail > > This is a simple start, but in the future I'd like to be able to > store these tasks in a folder and name the text files with the days > date, so I can "import" them back in case I need to look at it. > I'd also like to make a small dictionary with the names and e-mail > addresses of the people who should receive the e-mail, and somehow > either copy the text into an outlook e-mail, or directly send it > over SMTP (whichever is simpler) > > > I'm having a hard time actually starting, but so far I have a basic > idea and it shouldn't be too hard. > > I'm planning to use wxPython on Windows 7 because it looks pretty > simple so far and it also looks elegant enough :-) > > > If you guys/gals could comment on this, or give me some kind of > advice, I'd be more than thankful. I'll be sure to let you know how > it goes, and share the source. > > > Thanks, everyone! > > All the best! > > Miguel A. Guasch > miguel.gua...@hushmail.com > > It might be a good idea to first implement this as a command-line script and then consider moving to a gui; note that Tkinter is quite a bit easier than wxPython. (and in recent years it was updated to look nicer than it used to). -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Frisbeetarianism is the belief that when you die, your soul goes up on the roof and gets stuck. George Carlin ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Beep sound
Just out of curiosity how can a beep sound be generated? My interest in this came about because echo -e '\a' no longer works. Also print '\a' doesn't work, presumably for the same reason. The following is also mute: import Tkinter Tkinter.Tk().bell() Print '\a', under Idle, causes a bell icon to be displayed so it seems that the lack of a beep is due to a system setting. A Google search has shown several methods to play .wav files, some easier than others. Perhaps Pulse Audio has made '\a' redundant? -- Regards, Phil ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beep sound
On 23/03/13 12:48, Phil wrote: Just out of curiosity how can a beep sound be generated? My interest in this came about because echo -e '\a' no longer works. Also print '\a' doesn't work, presumably for the same reason. The following is also mute: import Tkinter Tkinter.Tk().bell() Print '\a', under Idle, causes a bell icon to be displayed so it seems that the lack of a beep is due to a system setting. Would you like us to guess what system you are running? Linux, Mac OS, Windows, FreeBSD, OpenBSD, Android, something else? My guess is... Windows XP. Am I close? Is your sound volume on and not muted? Can you play other sounds? Does your terminal have the "Terminal Bell" enabled? -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] send issue
using a socket im trying to send a message between connections. it was a string and my python complained: "TypeError: must be bytes or buffer, not str" .. so i put a b infront of the string. now this works fine but the problem is after recieving this message, i need to send it back with an int included, like: message = 'Thankyou!, processed connection number %d' % connections connections being an int. again this is a string, but puttng a b infront of that strong wont work, it returns: TypeError: unsupported operand type(s) for %: 'bytes' and 'int' i tried everything but i cant seem to get past this little obstacle. im using python 3 on windows vista___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] send issue
On 03/22/2013 11:29 PM, Lolo Lolo wrote: using a socket im trying to send a message between connections. it was a string and my python complained: > "TypeError: must be bytes or buffer, not str" .. so i put a b infront of the string. now this works fine but the problem is after recieving this message, i need to send it back with an int included, like: > message = 'Thankyou!, processed connection number %d' % connections connections being an int. > again this is a string, but puttng a b infront of that strong wont work, it returns: > TypeError: unsupported operand type(s) for %: 'bytes' and 'int' > > i tried everything but i cant seem to get past this little obstacle. im using python 3 on windows vista > > > ___ > You can use bytes() function: bytes('%d' % 3, 'utf-8') b'3' -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Whenever you find yourself on the side of the majority, it is time to pause and reflect. Mark Twain ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Overriding equality tests in Python
Hi list. I'll preface this by saying that I am very grateful for all of you, and thank you in advance to anyone that answers. I'm currently working on a roulette simulator, because it seemed like fun. I found out I needed a way to compare two different outcomes, and it was suggested to me that I should override the __eq__ and __ne__ methods. Said and done, I did: class Outcome(): def __init__(self, name): #Ignoring odds for now self.name = name def __eq__(self, other): '''returns True if Outcome.name matches other.name''': if self.name == other.name: return True def __ne__(self, other): '''returns True if Outcome.name does not match other.name''' if self.name != other.name: return True Now, this works, as far as this is concerned: >>> a = Outcome('Bob') >>> b = Outcome('Ray') >>> c = Outcome('Bob') >>> a == b >>> a == c True >>> a != b True >>> However, if I were to create a class without the __eq__ and __ne__ definitions, what is to prevent me from doing: a.name == b.name ? Or am I missing something in my implementation of the overrides? Is there a reason why I shouldn't do .name comparisons? -- best regards, Robert S. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] send issue
>You can use bytes() function: bytes('%d' % 3, 'utf-8') >b'3' >-m thanks this has solved everything. can i ask if this is an issue only in python 3 where sockets cant send strings? the docs state the argument is a string, but i believe that was for 2.7. I knew nothing about b'' or bytes() before today. thanks again___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Overriding equality tests in Python
On 03/23/2013 12:08 AM, Robert Sjoblom wrote: Hi list. I'll preface this by saying that I am very grateful for all > of you, and thank you in advance to anyone that answers. > > I'm currently working on a roulette simulator, because it seemed like > fun. I found out I needed a way to compare two different outcomes, and > it was suggested to me that I should override the __eq__ and __ne__ > methods. Said and done, I did: > class Outcome(): > def __init__(self, name): #Ignoring odds for now > self.name = name > > def __eq__(self, other): > '''returns True if Outcome.name matches other.name''': > if self.name == other.name: return True > def __ne__(self, other): > '''returns True if Outcome.name does not match other.name''' > if self.name != other.name: return True > > Now, this works, as far as this is concerned: a = Outcome('Bob') b = Outcome('Ray') c = Outcome('Bob') a == b a == c > True a != b > True > However, if I were to create a class without the __eq__ and __ne__ > definitions, what is to prevent me from doing: a.name == b.name ? Or > am I missing something in my implementation of the overrides? Is there > a reason why I shouldn't do .name comparisons? > Firstly, in __eq__, you can do: return self.name == other.name Second, you are right that you can also compare attributes directly. But the meaning is different, if I'm reading your program, a == b tells me "object a is equal to b for the purpose of this program", a.name == b.name tells me, name attrs are equal. a == b is also a shorter and more readable expression. __eq__ is also used in constructs like: if a in mylist: ... __eq__ is probably used for other things, too; the basic idea is that it tells Python that objects are equal, and Python can use this information in various circumstances. -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Each religion, by the help of more or less myth, which it takes more or less seriously, proposes some method of fortifying the human soul and enabling it to make its peace with its destiny. George Santayana ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor