Re: [Tutor] change values in an array
questions anon wrote: > I am trying to do something really simple. > I have a numpy array and if any values in the array are 255 I want to > change them to 1. > but I can't seem to get anything to work! Note that numpy is a specialist topic, and for everything but the basics the numpy mailing list is the best place to ask questions about it. > > If I use: > > for i, value in enumerate(mask_arr): > if value==255: > mask_arr[i]=1 > > I get this error: > > Traceback (most recent call last): > File "d:/timeseries_mask.py", line 51, in > if value==255: > ValueError: The truth value of an array with more than one element is > ambiguous. Use a.any() or a.all() > > and if I try to add a.any() to my code: > > for i, value in enumerate(mask_arr): > if value.any()==255: > mask_arr[i]=1 > > my array does not change at all. > Any feedback will be greatly appreciated You seem to have a multidimensional array, i. e. value is still an array >>> import numpy >>> a = numpy.array([[1, 2], [3, 4]]) >>> for value in a: print value ... [1 2] [3 4] >>> if a[0]: pass ... Traceback (most recent call last): File "", line 1, in ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() If you want to access the values of an n-dimensional array using a standard Python approach you have to use n nested for-loops: >>> for i, row in enumerate(a): ... for k, value in enumerate(row): ... if value == 1: ... a[i, k] = 42 ... >>> a array([[42, 2], [ 3, 4]]) As that is not very efficient numpy offers an alternative: >>> a[a == 42] = 123 >>> a array([[123, 2], [ 3, 4]]) or using the names from your example: mask_arr[mask_arr == 255] = 1 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] how to understand unhashable type: 'list'
list1 [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61', '70', '61', '34'], ['34', '58', '34', '58']] >>> weight={} >>> weight{list1[0]}=1 SyntaxError: invalid syntax >>> weight[list1[0]]=1 Traceback (most recent call last): File "", line 1, in weight[list1[0]]=1 TypeError: unhashable type: 'list' >>> I wonder how to count the occurence of the list of lists. Thanks, ^_^ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to understand unhashable type: 'list'
On 2011/11/17 11:59 AM, lina wrote: list1 [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61', '70', '61', '34'], ['34', '58', '34', '58']] weight={} weight{list1[0]}=1 SyntaxError: invalid syntax weight[list1[0]]=1 Traceback (most recent call last): File "", line 1, in weight[list1[0]]=1 TypeError: unhashable type: 'list' I wonder how to count the occurence of the list of lists. Thanks, ^_^ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor sum(1 if type(elem) == list else 0 for elem in list1) not work for you if all you want to do is count how many lists you have in your main list ? -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to understand unhashable type: 'list'
On Thu, Nov 17, 2011 at 6:09 PM, Christian Witts wrote: > On 2011/11/17 11:59 AM, lina wrote: > > list1 > [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61', > '70', '61', '34'], ['34', '58', '34', '58']] > > weight={} > weight{list1[0]}=1 > > SyntaxError: invalid syntax > > weight[list1[0]]=1 > > Traceback (most recent call last): > File "", line 1, in > weight[list1[0]]=1 > TypeError: unhashable type: 'list' > > I wonder how to count the occurence of the list of lists. > > Thanks, ^_^ > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > sum(1 if type(elem) == list else 0 for elem in list1) not work for you if > all you want to do is count how many lists you have in your main list ? not count how many sublists in the main list. wanna count the occurence of the sublists, I mean, something like >>> dictionary[list1[1]]=occurence Traceback (most recent call last): File "", line 1, in dictionary[list1[1]]=1 TypeError: unhashable type: 'list' >>> > -- dictionary[list1[1]]=1 Traceback (most recent call last): File "", line 1, in dictionary[list1[1]]=1 TypeError: unhashable type: 'list' >>> > Christian Witts > Python Developer > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to understand unhashable type: 'list'
On 2011/11/17 12:26 PM, lina wrote: On Thu, Nov 17, 2011 at 6:09 PM, Christian Witts wrote: On 2011/11/17 11:59 AM, lina wrote: list1 [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61', '70', '61', '34'], ['34', '58', '34', '58']] weight={} weight{list1[0]}=1 SyntaxError: invalid syntax weight[list1[0]]=1 Traceback (most recent call last): File "", line 1, in weight[list1[0]]=1 TypeError: unhashable type: 'list' I wonder how to count the occurence of the list of lists. Thanks, ^_^ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor sum(1 if type(elem) == list else 0 for elem in list1) not work for you if all you want to do is count how many lists you have in your main list ? not count how many sublists in the main list. wanna count the occurence of the sublists, I mean, something like dictionary[list1[1]]=occurence Traceback (most recent call last): File "", line 1, in dictionary[list1[1]]=1 TypeError: unhashable type: 'list' dictionary[list1[1]]=1 Traceback (most recent call last): File "", line 1, in dictionary[list1[1]]=1 TypeError: unhashable type: 'list' For that you'll need to convert your list to a hash-able type if you want to use dictionaries for your store, easiest would probably to use the string representation for it so you could do >>> list1 = [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61', '70', '61', '34'], ['34', '58', '34', '58']] >>> weight = {} >>> for elem in list1: ... if elem.__repr__() in weight: ... weight[elem.__repr__()] += 1 ... else: ... weight[elem.__repr__()] = 1 ... >>> weight {"['34', '58', '34', '58']": 1, "['61', '70', '61', '34']": 1, "['61', '34', '61 ', '34']": 1, "['61', '35', '61', '70', '61']": 1} or >>> from collections import defaultdict >>> list1 = [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61', '7 0', '61', '34'], ['34', '58', '34', '58']] >>> weight = defaultdict(int) >>> for elem in list1: ... weight[elem.__repr__()] += 1 ... >>> weight defaultdict(, {"['34', '58', '34', '58']": 1, "['61', '70', '61', '34']": 1, "['61', '34', '61', '34']": 1, "['61', '35', '61', '70', '61']": 1}) Hope that helps. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] ProgressBar - Python and Powershell
Hi All, I am using Python 2.7, windows Env. I have an Installer written in Python(45%) and Powershell(55%) which is used to install Virtual Machines at specific locations. It is single threaded. I am trying to implement a ProgressBar for this installer. So that the user will come to know the progress of the installation. I am using pypi progressbar module. The top script is in python which inturns calls powershell scripts using subprocess.call() and proceeds with the installation. I am taking a shared file between python and powershell, so that diff functions can update their %age completion level in to the file. Ex. Func1() updates it to 5%, func2() will add its own 5% to it.. and so on. At the start of the (main.py) script I am creating a thread whose sole purpose would be to keep "READ" a temp file for a new entry in it. Based on this entry I can have my thread update the progressbar on the console. My questions are: 1. Can I have a better shared mechanism between python and powershell.? As I am using a file here. Reading + writing in python and writing only in powershell. ! 2. Does this thread mechanism work.? I am yet to implement and test it.! :P What can be the possible shortfalls.? Thanks Nikunj Bangalore - India ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to understand unhashable type: 'list'
lina wrote: list1 [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61', '70', '61', '34'], ['34', '58', '34', '58']] You have a list of lists. weight={} weight{list1[0]}=1 SyntaxError: invalid syntax In Python, {} are used for dicts, and in Python 3, sets. They aren't used for anything else. obj{...} is illegal syntax. weight[list1[0]]=1 Traceback (most recent call last): File "", line 1, in weight[list1[0]]=1 TypeError: unhashable type: 'list' You are trying to store a list as a key inside a dict. This cannot be done because lists (like all mutable types) can't be hashed. If your list of lists is small, say, less than a few thousand items, it would be fast enough to do this: counts = [] seen = [] for sublist in list1: if sublist in seen: # No need to do it again. continue seen.append(sublist) counts.append( (sublist, list1.count(sublist)) ) If I run this code on your list1, I get these counts: [(['61', '34', '61', '34'], 1), (['61', '35', '61', '70', '61'], 1), (['61', '70', '61', '34'], 1), (['34', '58', '34', '58'], 1)] That is, each list is unique. However, if you have many thousands of items, the above may be too slow. It is slow because of all the linear searches: "sublist in seen" searches seen for the sublist, one item at a time, and "list1.count(sublist)" searches list1 for sublist, also one item at a time. If there are many items, this will be slow. To speed it up, you can do this: (1) Keep the seen list sorted, and use binary search instead of linear search. See the bisect module for help. (2) Sort list1, and write your own smarter count() function that doesn't have to travel along the entire list. All that involves writing a lot of code though. Probably much faster would be to make a temporary copy of list1, with the inner lists converted to tuples: list2 = [tuple(l) for l in list1] counts = {} for t in list2: counts[t] = 1 + counts.get(t, 0) for t, n in counts.items(): print list(t), n -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] (no subject)
Hi all, I'm new to programming (thus Python), so after reading the basics, I wanted to practise what I've learnt . I've come across a beginners exercise which is to programme rot13. I've written some code but it doesn't seem to work Here it is: def rot13(s):char_low = ()result = ""if not s.isalpha(): return charchar_low = char_low.lower()if char_low <= 'm': dist = 13else:dist = -13char = chr(ord(char) + dist) def rot13_char(ch): return ''.join( rot13(s) for char in ch ) Any idea where i'm wrong? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
On Thu, Nov 17, 2011 at 2:14 PM, Nidian Job-Smith wrote: > Hi all, > > I'm new to programming (thus Python), so after reading the > basics, I wanted to practise what I've learnt . I've come across a > beginners exercise which is to programme rot13. > > I've written some code but it doesn't seem to work > > Here it is: > > > def rot13(s): > char_low = () > result = "" > if not s.isalpha(): > return char > char_low = char_low.lower() > if char_low <= 'm': > dist = 13 > else: > dist = -13 > char = chr(ord(char) + dist) > > def rot13_char(ch): > return ''.join( rot13(s) for char in ch ) > > > Any idea where i'm wrong? > Please, when posting a program that has problems to this list, do not just say that "it doesn't work". Tell us what is wrong: * If you get a syntax error, tell us that, and tell us where it is claimed the syntax error is * if you get an error message, give the error message as well as the stack trace provided with it, or at least the last part of that stack trace * If the program does not crash, but behaves different from what you expected, tell us what you expected to get, and what you actually got (for example, "After giving the input 5 and 3 I had expected the program to output 8 and ask for a new pair of numbers, but instead it showed 8 lines of 8 stars, printed 'Thank you for using my program' and ended. Having said that, using your program gave me various problems. The first was in return ''.join( rot13(s) for char in ch ) - I got an error message that the name 's' was not defined. Reason: the variable before the for should be the same as after, so you should either say 'rot13(s) for s in ch' or 'rot13(char) for char in ch' Most of your other problems had the same cause: If you want to use something (a thing, a number, a letter, whatever), use the same name as you used when you defined that thing. -- André Engels, andreeng...@gmail.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to understand unhashable type: 'list'
> ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > sum(1 if type(elem) == list else 0 for elem in list1) not work for you if > all you want to do is count how many lists you have in your main list ? > > not count how many sublists in the main list. > > wanna count the occurence of the sublists, > > I mean, something like > > dictionary[list1[1]]=occurence > > Traceback (most recent call last): > File "", line 1, in > dictionary[list1[1]]=1 > TypeError: unhashable type: 'list' > > dictionary[list1[1]]=1 > > Traceback (most recent call last): > File "", line 1, in > dictionary[list1[1]]=1 > TypeError: unhashable type: 'list' > > > For that you'll need to convert your list to a hash-able type if you want to > use dictionaries for your store, easiest would probably to use the string > representation for it so you could do > list1 = [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61', '70', '61', '34'], ['34', '58', '34', '58']] weight = {} for elem in list1: > ... if elem.__repr__() in weight: This is cool. May I ask which role the __repr__ plays here? > ... weight[elem.__repr__()] += 1 > ... else: > ... weight[elem.__repr__()] = 1 > ... weight > {"['34', '58', '34', '58']": 1, "['61', '70', '61', '34']": 1, "['61', '34', > '61 > ', '34']": 1, "['61', '35', '61', '70', '61']": 1} > > or > from collections import defaultdict list1 = [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61', '7 > 0', '61', '34'], ['34', '58', '34', '58']] weight = defaultdict(int) for elem in list1: > ... weight[elem.__repr__()] += 1 > ... weight > defaultdict(, {"['34', '58', '34', '58']": 1, "['61', '70', > '61', '34']": 1, "['61', '34', '61', '34']": 1, "['61', '35', '61', '70', > '61']": 1}) > > Hope that helps. > > -- > > Christian Witts > Python Developer > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to understand unhashable type: 'list'
On Thu, Nov 17, 2011 at 8:17 PM, Steven D'Aprano wrote: > lina wrote: >> >> list1 >> [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61', >> '70', '61', '34'], ['34', '58', '34', '58']] > > You have a list of lists. > > > weight={} > weight{list1[0]}=1 >> >> SyntaxError: invalid syntax > > In Python, {} are used for dicts, and in Python 3, sets. They aren't used > for anything else. obj{...} is illegal syntax. > > > weight[list1[0]]=1 >> >> Traceback (most recent call last): >> File "", line 1, in >> weight[list1[0]]=1 >> TypeError: unhashable type: 'list' > > You are trying to store a list as a key inside a dict. This cannot be done > because lists (like all mutable types) can't be hashed. I checked online dictionary, still confused about hashed. is it equal to mix together or mess together? > > If your list of lists is small, say, less than a few thousand items, it > would be fast enough to do this: > > counts = [] > seen = [] > for sublist in list1: > if sublist in seen: > # No need to do it again. > continue > seen.append(sublist) > counts.append( (sublist, list1.count(sublist)) ) Thanks, can I print the counts based on its value? > > > If I run this code on your list1, I get these counts: > > [(['61', '34', '61', '34'], 1), (['61', '35', '61', '70', '61'], 1), (['61', > '70', '61', '34'], 1), (['34', '58', '34', '58'], 1)] > > > That is, each list is unique. > > However, if you have many thousands of items, the above may be too slow. It > is slow because of all the linear searches: "sublist in seen" searches seen > for the sublist, one item at a time, and "list1.count(sublist)" searches > list1 for sublist, also one item at a time. If there are many items, this > will be slow. > > To speed it up, you can do this: > > (1) Keep the seen list sorted, and use binary search instead of linear > search. See the bisect module for help. > > (2) Sort list1, and write your own smarter count() function that doesn't > have to travel along the entire list. > > > All that involves writing a lot of code though. Probably much faster would > be to make a temporary copy of list1, with the inner lists converted to > tuples: > > > list2 = [tuple(l) for l in list1] > counts = {} > for t in list2: > counts[t] = 1 + counts.get(t, 0) > > for t, n in counts.items(): > print list(t), n > > > -- > Steven > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to understand unhashable type: 'list'
lina wrote: May I ask which role the __repr__ plays here? ... weight[elem.__repr__()] += 1 ... else: ... weight[elem.__repr__()] = 1 ... You should never call elem.__repr__(), any more than you would call elem.__len__() or elem.__str__(). (Well, technically there *are* rare uses for calling such double underscore special methods directly, but this is not one of them!) Instead, you should call repr(elem), len(elem), str(elem). The purpose here is to convert the sublist, elem, which is unhashable, into something which is hashable. Strings are hashable, and so if you use repr() to convert it into a string, you can use it in a dictionary. I don't see any advantage to using repr() instead of str(). Given the data you are working with, there is no difference: py> str([['1', '2'], ['33', '44']]) "[['1', '2'], ['33', '44']]" py> repr([['1', '2'], ['33', '44']]) "[['1', '2'], ['33', '44']]" In my opinion, turning objects into strings unnecessarily is not good practice. Better to use a tuple than a string. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
Nidian Job-Smith wrote: Hi all, I'm new to programming (thus Python), so after reading the basics, I wanted to practise what I've learnt . I've come across a beginners exercise which is to programme rot13. I've written some code but it doesn't seem to work Here it is: def rot13(s):char_low = ()result = ""if not s.isalpha():return charchar_low = char_low.lower()if char_low <= 'm':dist = 13else:dist = -13char = chr(ord(char) + dist) def rot13_char(ch): return ''.join( rot13(s) for char in ch ) Any idea where i'm wrong? Hi Nidian, If possible, please send code as plain text emails, not so-called "rich-text" (actually HTML), as it tends to mangle the formatting and make it almost impossible to decipher for some people. Also, please choose a meaningful subject line, to make it easier for people to follow the conversation. Some comments on your code, if I have re-created the formatting correctly. (1) You seem to have mixed up strings and characters. You have a function called "rot13" with an argument called "s" (for "string"), but it is intended to operate on a single character. On the other hand, you have a function called "rot13_char" with an argument "ch" (for "character"), but it operates on an entire string! You should reverse them: rot13(s) => apply rot13 to an entire string, s rot13_char(c) => apply rot13 to a single character, c (2) You have a lot of inconsistent variable names. For example, in your version of "rot13_char" (which actually operates on an entire string, not a character), you have: def rot13_char(ch): return ''.join( rot13(s) for char in ch ) Inside the join(), you have a loop "for char in ch" (for character in character???) but then you refer to "s". This should be written as: def rot13(string): return ''.join(rot13_char(char) for char in string) Likewise in the "rot13" function (better named rot13_char), you inconsistently refer to variables by different names. You must be consistent. Does that give you enough hints to continue? If not, ask any more questions you like! -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to understand unhashable type: 'list'
On 2011/11/17 03:56 PM, lina wrote: ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor sum(1 if type(elem) == list else 0 for elem in list1) not work for you if all you want to do is count how many lists you have in your main list ? not count how many sublists in the main list. wanna count the occurence of the sublists, I mean, something like dictionary[list1[1]]=occurence Traceback (most recent call last): File "", line 1, in dictionary[list1[1]]=1 TypeError: unhashable type: 'list' dictionary[list1[1]]=1 Traceback (most recent call last): File "", line 1, in dictionary[list1[1]]=1 TypeError: unhashable type: 'list' For that you'll need to convert your list to a hash-able type if you want to use dictionaries for your store, easiest would probably to use the string representation for it so you could do list1 = [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61', '70', '61', '34'], ['34', '58', '34', '58']] weight = {} for elem in list1: ... if elem.__repr__() in weight: This is cool. May I ask which role the __repr__ plays here? __repr__ is the string representation of a Python object [1] so I'm using it to create something that is hash-able to be used as the dictionary key value. [1] http://docs.python.org/library/functions.html#repr -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to understand unhashable type: 'list'
Hi Lina On 17 November 2011 14:04, lina wrote: > >> Traceback (most recent call last): > >> File "", line 1, in > >>weight[list1[0]]=1 > >> TypeError: unhashable type: 'list' > > > > You are trying to store a list as a key inside a dict. This cannot be > done > > because lists (like all mutable types) can't be hashed. > > I checked online dictionary, still confused about hashed. is it equal > to mix together or mess together? > No you need to think programming/computer science where hash/hashing has a different meaning. See wikipedia: http://en.wikipedia.org/wiki/Hash_function http://en.wikipedia.org/wiki/Hash_table Also see the description for "hashable" in the Python glossary: http://docs.python.org/glossary.html#hashable Basically hashing is a way to convert something (often a string) into an identifying number (not neccesarily but usually unique) in order to use this number as a token for the original thing. Aside, you can infer that that because the "dict" code complains about hashing implies that dicts themselves are essentially implemented as hash tables... ;) HTH, Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to understand unhashable type: 'list'
Thanks for all. Everything new to me is so amazing. Well, still a remaining question, how to sort based on the value of the key. Actually I googled hours ago, wanna see more ways of doing it. Best regards, > > On 17 November 2011 14:04, lina wrote: >> >> >> Traceback (most recent call last): >> >> File "", line 1, in >> >> weight[list1[0]]=1 >> >> TypeError: unhashable type: 'list' >> > >> > You are trying to store a list as a key inside a dict. This cannot be >> > done >> > because lists (like all mutable types) can't be hashed. >> >> I checked online dictionary, still confused about hashed. is it equal >> to mix together or mess together? > > No you need to think programming/computer science where hash/hashing has > a different meaning. See wikipedia: > http://en.wikipedia.org/wiki/Hash_function > http://en.wikipedia.org/wiki/Hash_table > > Also see the description for "hashable" in the Python glossary: > http://docs.python.org/glossary.html#hashable > > Basically hashing is a way to convert something (often a string) into an > identifying number (not neccesarily but usually unique) in order to use this > number as a token for the original thing. Aside, you can infer that that > because the "dict" code complains about hashing implies that dicts > themselves are essentially implemented as hash tables... ;) > > HTH, > > Walter > > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to understand unhashable type: 'list'
lina wrote: You are trying to store a list as a key inside a dict. This cannot be done because lists (like all mutable types) can't be hashed. I checked online dictionary, still confused about hashed. is it equal to mix together or mess together? Almost. In ordinary English, a hash is a mixed up mess. For example, "hash browns" are fried mashed potato. In computing, a hash got its name by analogy with "mixed up". A hash is short for "hash table". An ordinary table might look something like this: Position Value 1 "Fred" 2 "Barney" 3 "George" 4 "Betty" 5 "Mary" 6 *unused* 7 *unused* 8 *unused* 9 *unused* To find whether "Mary" is in the table, you have to start at position 1, and inspect each value to see whether it equals "Mary": for position 1 to 9: if value at position == "Mary": print FOUND If there are many items, this will be slow. But here's a faster way, using a "hash table": Position Value 1 *unused* 2 "Barney" 3 *unused* 4 "Betty" 5 *unused* 6 *unused* 7 "Fred" 8 "Mary" 9 "George" Take the string "Mary", and mix it up into a "hash value" between 1 and 9. In this case, you will get 8. Look in position 8, and you will find "Mary". Take the string "Susan" and mix it up into a hash value. In this case, you might get 3. Since position 3 is actually unused, you know that "Susan" is not in the hash table. All the hard work is done in the "mixing" of the string. This is called a hash function, and Python already has one: py> hash("Mary") -1963774307 py> hash("Susan") 92926151 If you change just one letter of the string, the hash can change a lot: py> hash("abcdef") -33722981 py> hash("bbcdef") -508939398 But lists are not hashable, because they are mutable (can be changed): py> hash([1, 2, 3]) Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'list' Python dictionaries are hash tables. You could have a million items in a dict, and to check whether "Mary" is one of them with a list would require you to check all one million items. But with a dict, Python hashes the string to get a number, then reduces that number to fit within the range of positions in the dict, then looks immediately in the right spot to find "Mary". -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Clock in tkinter?
From: Wayne Werner Sent: Wednesday, November 16, 2011 8:38 PM To: Mic Cc: tutor@python.org Subject: Re: [Tutor] Clock in tkinter? On Wed, Nov 16, 2011 at 11:44 AM, Mic wrote: I wonder if you have any suggestions regarding how to place widgets in my window. Even though I try to arrange them as orderly as possible they get placed at all different kind of places in the window. I use the grid method and place them in the window by using row=something and column=something. It just doesn’t look good. It looks okay I suppose, but not as good as I want it to look. http://twitpic.com/2t4n9q/full http://twitpic.com/2t4n9p/full Those images might help you understand a little bit more about the grid layout. So if I got it right. Inside the constructor (__init__) I should declare: self.the_time=’’ Then, if I understood it right, I should also place the function call there? self.update_time() as you refered to? Your constructor should look something like this: def __init__(self): #Your call to super self.the_time = '' # your other code self.update_time() I don't know for sure that it will work, but I expect that it will. HTH, Wayne Okay, to begin with, I hope I am replying correctly now. I will work to get my code into the constructor instead of having them in the global scope. Thanks for the pictures, I have now manged to organize the widgets in a much better way. I wonder, how do I add a background picture to my GUI window? So far, I thought I could make a label that is as large as the entire window, and then add a picture to it. The other widgets are supposed to be placed on top of the picture. But I am lost on how to accomplish this. Can you point me in the right direction to solve this? Mic___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] binary file query
-Original Message- From: Shirkhedkar, Dhanashri [mailto:dhanashri.shirkhed...@honeywell.com] Sent: Wednesday, November 16, 2011 10:58 PM To: Prasad, Ramit Subject: RE: binary file query Thanks for replying. It means that no need to use the 'Struct' module for binary file read, right? === Please reply to the list (or use reply-all). It really depends on your file. The struct module says, "This module performs conversions between Python values and C structs represented as Python strings." If your file is not a C-struct data then no need to use the struct module. For every other kind of binary data, use a library suited to that file if it exists. Otherwise you can read the raw data by just opening the file in binary mode as I shows in my previous email. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Clock in tkinter?
On Thu, Nov 17, 2011 at 8:57 AM, Mic wrote: > > > Okay, to begin with, I hope I am replying correctly now. > Better, though there was quite a lot of my email that you could have removed. > > I wonder, how do I add a background picture to my GUI window? > > So far, I thought I could make a label that is as large as the > entire window, and then add a picture to it. The other widgets > are supposed to be placed on top of the picture. > > But I am lost on how to accomplish this. Can you point me in the > right direction to solve this? > If you want to do this, I would recommend using the place (as opposed to pack or grid) manager inside of a frame widget. Use that to place your image, and another frame that contains your other widgets - I would use the pack or grid layout inside this other frame, though. HTH, Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to understand unhashable type: 'list'
On Thu, Nov 17, 2011 at 10:44 PM, Steven D'Aprano wrote: > lina wrote: > >>> You are trying to store a list as a key inside a dict. This cannot be >>> done >>> because lists (like all mutable types) can't be hashed. >> >> I checked online dictionary, still confused about hashed. is it equal >> to mix together or mess together? > > Almost. > > In ordinary English, a hash is a mixed up mess. For example, "hash browns" > are fried mashed potato. > > In computing, a hash got its name by analogy with "mixed up". A hash is > short for "hash table". > > An ordinary table might look something like this: > > > Position Value > 1 "Fred" > 2 "Barney" > 3 "George" > 4 "Betty" > 5 "Mary" > 6 *unused* > 7 *unused* > 8 *unused* > 9 *unused* > > > To find whether "Mary" is in the table, you have to start at position 1, and > inspect each value to see whether it equals "Mary": > > for position 1 to 9: > if value at position == "Mary": print FOUND > > > If there are many items, this will be slow. But here's a faster way, using a > "hash table": > > Position Value > 1 *unused* > 2 "Barney" > 3 *unused* > 4 "Betty" > 5 *unused* > 6 *unused* > 7 "Fred" > 8 "Mary" > 9 "George" > > Take the string "Mary", and mix it up into a "hash value" between 1 and 9. > In this case, you will get 8. Look in position 8, and you will find "Mary". > > Take the string "Susan" and mix it up into a hash value. In this case, you > might get 3. Since position 3 is actually unused, you know that "Susan" is > not in the hash table. > > > All the hard work is done in the "mixing" of the string. This is called a > hash function, and Python already has one: > > py> hash("Mary") > -1963774307 > py> hash("Susan") > 92926151 > > > If you change just one letter of the string, the hash can change a lot: > > > py> hash("abcdef") > -33722981 > py> hash("bbcdef") > -508939398 > > > But lists are not hashable, because they are mutable (can be changed): > > py> hash([1, 2, 3]) > Traceback (most recent call last): > File "", line 1, in > TypeError: unhashable type: 'list' > > > Python dictionaries are hash tables. You could have a million items in a > dict, and to check whether "Mary" is one of them with a list would require > you to check all one million items. But with a dict, Python hashes the > string to get a number, then reduces that number to fit within the range of > positions in the dict, then looks immediately in the right spot to find > "Mary". > Really appreciated for your detailed explaination. Right now I wanna check which are not hash-able, for strings, set, and tuple (which I don't understand). Seems string is hash-able. Just another quick Q: >>> basket ['apple', 'pineapple', 'apple', 'pear'] >>> hash(basket[1]) -8771120720059735049 >>> hash(basket[2]) 6709291584508918021 >>> print(id(basket)) 29215848 >>> print(id(basket[1])) 27389096 What are those numbers means? Sorry, > > > -- > Steven > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to understand unhashable type: 'list'
lina wrote: Right now I wanna check which are not hash-able, for strings, set, and tuple (which I don't understand). Mutable objects are those that can be changed in place: lists, sets, dicts are all mutable, because you can change them: >>> mylist = [1, 2, 3] >>> mylist[1] = 200 >>> print mylist [1, 200, 3 Mutable objects are not hashable. Immutable objects are those that cannot be changed in place: you have to create a new object. Tuples, frozensets, strings, ints, floats are all immutable. They are hashable. Seems string is hash-able. Just another quick Q: basket ['apple', 'pineapple', 'apple', 'pear'] hash(basket[1]) -8771120720059735049 hash(basket[2]) 6709291584508918021 The number doesn't mean anything. It's just a number. It gets used by dictionaries for fast searching, but that's all. This might help you understand. Here is a very simple hash function that takes a string and mixes it up to make a number. It isn't very good, it is a terrible hash function, but it is simple! The Python one is better, but this will give you an idea of how they work: def my_hash(string): num = 102345 # some random number I just made up for c in string: num = (num*17 + ord(c)*9) % 3200 return num Designing a good hash function is very hard. print(id(basket)) 29215848 print(id(basket[1])) 27389096 The id() of an object is just an identity number. Do you have a passport or driver's licence? Or a social security number? That is like your ID. It identifies you. Nobody else can have the same ID at the same time. In CPython, IDs are large numbers, and they are re-usable. If you delete an object, another object can get the same ID later on. In Jython and IronPython, IDs start counting at 1 and increase with every object created. Used IDs are never reused. IDs aren't important. In 15 years of using Python, I don't think I have needed to care about the ID of an object once. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Rot13
Hi all, I'm new to programming (thus Python), so after reading the basics, I wanted to practise what I've learnt . I've come across a beginners exercise which is to write the code for rot13. I've written some code but it doesn't seem to work When I run it I get this error: NameError: global name 'rot13_char' is not defined Here it is: def rot13(s): char_low = () result = "" if not s.isalpha(): return char char_low = char_low.lower() if char_low <= 'm': dist = 13 else: dist = -13 char = chr(ord(char) + dist) def rot13(string): return ''.join( rot13_char(char)for char in string ) Any ideas where i'm wrong? Huge thanks, Nidian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Rot13
Sorry about the code format in last E-mail. I'll attach the code in notepad, as my e-mail doesnt seem to like sending plain text.. > From: nidia...@hotmail.com > To: st...@pearwood.info; tutor@python.org > Date: Thu, 17 Nov 2011 17:45:11 + > Subject: [Tutor] Rot13 > > > Hi all, > > I'm new to programming (thus Python), so after reading the basics, I wanted > to practise what I've learnt . > I've come across a beginners exercise which is to write the code for rot13. > I've written some code but it doesn't seem to work > When I run it I get this error: > > > NameError: global name 'rot13_char' is not defined > > > Here it is: > > > > def rot13(s):char_low = ()result = ""if not s.isalpha(): > return charchar_low = char_low.lower()if char_low <= 'm': >dist = 13else:dist = -13char = chr(ord(char) + > dist) def rot13(string): return ''.join( rot13_char(char)for > char in string ) > > > > > Any ideas where i'm wrong? > > Huge thanks, > Nidian > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor def rot13(s): """ >>> type(rot13("bob")) >>> len(rot13("foobar")) 6 >>> rot13("abc") 'nop' >>> rot13("XYZ") 'KLM' >>> rot13('5 The Parade') '5 Gur Cnenqr' >>> rot13('5 Gur Cnenqr') '5 The Parade' """ char_low = () result = "" if not s.isalpha(): return char char_low = char_low.lower() if char_low <= 'm': dist = 13 else: dist = -13 char = chr(ord(char) + dist) def rot13(string): return ''.join( rot13_low(char)for char in string ) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Rot13
Nidian Job-Smith wrote: When I run it I get this error: NameError: global name 'rot13_char' is not defined [...] Any ideas where i'm wrong? You have a function called "rot13", and *another* function called "rot13", which will over-write the first one. But you have no function called "rot13_char". -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] python telnet
From: Rayon [mailto:ra...@gtt.co.gy] Sent: 17 November 2011 14:04 To: 'tutor@python.org' Subject: python telnet I am trying to use winpexpect to connect a telnet session. I keep getting this error. raise ExceptionPexpect, 'Command not found: %s' % self.command ExceptionPexpect: Command not found: telnet ###code### from winpexpect import winspawn child = winspawn('telnet 192.168.0.55:210') help me plz Regards Rayon ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Rot13
On 11/17/2011 12:54 PM, Nidian Job-Smith wrote: Sorry about the code format in last E-mail. I'll attach the code in notepad, as my e-mail doesnt seem to like sending plain text.. But attachments aren't visible to everyone on the list, and even when they are, some people are (rightfully) paranoid about arbitrarily opening attachments. You don't name your email program, but if it cannot handle text messages, perhaps you should look for another. There are many free email programs. For example, I use Thunderbird. I know it works under Windows, since I used to use it that way. But I'm currently using it under Linux. From: nidia...@hotmail.com To: st...@pearwood.info; tutor@python.org Date: Thu, 17 Nov 2011 17:45:11 + Subject: [Tutor] Rot13 Hi all, I'm new to programming (thus Python), so after reading the basics, I wanted to practise what I've learnt . I've come across a beginners exercise which is to write the code for rot13. I've written some code but it doesn't seem to work When I run it I get this error: NameError: global name 'rot13_char' is not defined That's not the whole error message/ How can you get this error when the file you attached never used that name ? Be sure and use cut 'n paste when telling about an error message. If you don't know how, ask, but be sure and give your environment specifics. Further, the file you attached wouldn't even try to run anything, so it couldn't get any such error, even if we concede a typo in the name. When I run it (after renaming it from a .txt extension to a .py one), I get the following: davea@think:~/temppython$ mv rot13_code-1.txt rot13_code-1.py davea@think:~/temppython$ python rot13_code-1.py davea@think:~/temppython$ Now, if I add a couple of lines to it to test it out: print rot13("abc") print rot13("XyzzY") Then I indeed get an error: davea@think:~/temppython$ python rot13_code-1.py Traceback (most recent call last): File "rot13_code-1.py", line 32, in print rot13("abc") File "rot13_code-1.py", line 30, in rot13 return ''.join( rot13_low(char)for char in string ) File "rot13_code-1.py", line 30, in return ''.join( rot13_low(char)for char in string ) NameError: global name 'rot13_low' is not defined Guess what, you had two functions with the same name. So the first one disappears. Apparently you wanted to name it rot13_low(): def rot13_low(s): Now, when I run it, I get: davea@think:~/temppython$ python rot13_code-1.py Traceback (most recent call last): File "rot13_code-1.py", line 32, in print rot13("abc") File "rot13_code-1.py", line 30, in rot13 return ''.join( rot13_low(char)for char in string ) File "rot13_code-1.py", line 30, in return ''.join( rot13_low(char)for char in string ) File "rot13_code-1.py", line 22, in rot13_low char_low = char_low.lower() AttributeError: 'tuple' object has no attribute 'lower' No idea why you created a tuple called char_low. My guess is that you meant the formal parameter of the first function to be char_low, since calling it s would be misleading. It's intended to be a single character, not a string. Anyway, you can presumably see the process. Look at the whole error traceback, and if you can't see what it means, ask for help. BTW, the docstring you have for the first function belongs in the second one. That first function doesn't deal with strings. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] local variable referenced before assignment
hi all,keep getting the above error, can't understand or fix it, can anyone help. def exchange():euro=1dollar=1.35base=50amount = input ('how much do you want to change')if amount>base: totalreturn=amount*dollarelse:print 'not enough'return totalreturn print exchange() Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] local variable referenced before assignment
Post the error stack. Sent from my BlackBerry wireless device from MTN -Original Message- From: ADRIAN KELLY Sender: tutor-bounces+delegbede=dudupay@python.org Date: Thu, 17 Nov 2011 18:47:07 To: Subject: [Tutor] local variable referenced before assignment ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] local variable referenced before assignment
On Thu, Nov 17, 2011 at 1:53 PM, wrote: > Post the error stack. > Sent from my BlackBerry wireless device from MTN > > -Original Message- > From: ADRIAN KELLY > Sender: tutor-bounces+delegbede=dudupay@python.org > Date: Thu, 17 Nov 2011 18:47:07 > To: > Subject: [Tutor] local variable referenced before assignment > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > if amount>base: totalreturn=amount*dollar else: print 'not enough' return totalreturn Notice if amount isn't more than base totalreturn is not created, so the else clause executes and totalreturn doesn't exist -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] local variable referenced before assignment
On 11/17/2011 01:47 PM, ADRIAN KELLY wrote: hi all,keep getting the above error, can't understand or fix it, can anyone help. def exchange():euro=1dollar=1.35base=50amount = input ('how much do you want to change')if amount>base:totalreturn=amount*dollar else:print 'not enough'return totalreturn print exchange() You've been doing better, but this one has lost its formatting entirely. Are you posting in text mode? That's not the entire error message. If you examined the entire traceback, it'd identify the line with the problem, and the particular variable that's being used before it's been defined. But since the function is small, i can guess my way through. The variable is apparently "totalreturn". And when you go through the else clause you completely miss the assignment to it. When you have a mechanism like: if x > y: newval = 49 else: print "error message" #newval = -5 return newval Without that second assignment, you'll get "the above error" whenever the else condition prevails. newval has no value, and in fact doesn't exist if you go through the else clause. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to understand unhashable type: 'list'
Steven D'Aprano wrote: > Immutable objects are those that cannot be changed in place: you have to > create a new object. Tuples, frozensets, strings, ints, floats are all > immutable. They are hashable. Tuples are special: there are hashable and unhashable tuples. To be hashable all items in a tuple have to be hashable: >>> a = 1, 2 >>> hash(a) 3713081631934410656 >>> b = 1, [] >>> hash(b) Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'list' Instances of custom classes are special, too; by default they are hashable and mutable. That is possible without messing things up too much because instead of the instance's data they use its id() to calculate the hash value (and object equality). This is obvious in older Python versions like Python 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class A: pass ... >>> a = A() >>> id(a) 140312106243352 >>> hash(a) 140312106243352 >>> id(a) == hash(a) True but the principle also applies in 2.7 and 3.1 and above. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Clock in tkinter?
If you're going to put a function inside your class (since you're using self in there, I'm sure that's what you meant to do), you should change it to: def change_value_the_time(self): and call it with self.display_time.after(20, self.change_value_the_time) But your program also has unnecessary code. First, since you have a class then instead of using a global, you should simply declare `self.the_time = ''` in your __init__ for your class. Personally, I would have written the function more like this: def update_time(self): self.display_time.config(text=time.strftime('%H:%M:%S'), font='40') self.after(20, self.update_time) Then at the end of my __init__ function I would call self.update_time() I'm not sure how that will work with your current setup, though. - I have now worked to stop using the global scope and instead put my prior global variable into the constructor in the class. I believe that I have managed to do that now. Do you believe that this is correctly done? #Trying putting the_time'' in constructor instead of #putting it in the global scope to shorten code. from tkinter import* import time import os class Window(Frame): def __init__(self,master): super (Window,self).__init__(master) self.grid() self.the_time='' self.create_widgets() self.update_time() def create_widgets(self): #Create a hello Button: self.hellobttn=Button(self, text="Hey") self.hellobttn.grid(row=0, column=1) #Create a label that displays time. self.display_time=Label(self, text=self.the_time) self.display_time.grid(row=1, column=1) def update_time(self): self.display_time.config(text=time.strftime('%H:%M:%S'), font='40') self.after(20, self.update_time) root=Tk() root.title("Test") root.geometry("200x200") app=Window(root) root.mainloop() I get no error while doing this, and the program works fine. I have another question. Say that I have a class and I want to make 100 objects. Then it could look like this: #How to shorten this? #Create the class. class Chairs(object): def __init__(self, age, weight): self.age=age self.weight=weight def __str__(self): rep=self.age+self.weight return rep #Create the objects chair1=Chairs("10","20") chair2=Chairs("10","20") chair3=Chairs("10","20") chair4=Chairs("10","20") chair5=Chairs("10","20") chair6=Chairs("10","20") chair7=Chairs("10","20") chair8=Chairs("10","20") chair9=Chairs("10","20") #And so on How do I shorten this? I have thought of using a for sling. I have looked in my programming book and on the internet, but I don’t know how to make this shorter. The arguements (“10”, “20”) should be the same for every object, which should make it easier than if they were different each time? Right now, it feels like a lot of my code in my other programs could be made dramatically shorter. Thanks! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] local variable referenced before assignment
you are spot on. thanks very much i understand the problem now and its been solved. very clear help thanks, adrian > Date: Thu, 17 Nov 2011 14:01:19 -0500 > From: d...@davea.name > To: kellyadr...@hotmail.com > CC: tutor@python.org > Subject: Re: [Tutor] local variable referenced before assignment > > On 11/17/2011 01:47 PM, ADRIAN KELLY wrote: > > hi all,keep getting the above error, can't understand or fix it, can anyone > > help. > > def exchange():euro=1dollar=1.35base=50amount = input ('how > > much do you want to change')if amount>base: > > totalreturn=amount*dollarelse:print 'not enough'return > > totalreturn > > print exchange() > > > > > You've been doing better, but this one has lost its formatting > entirely. Are you posting in text mode? > > That's not the entire error message. If you examined the entire > traceback, it'd identify the line with the problem, and the particular > variable that's being used before it's been defined. > > > But since the function is small, i can guess my way through. The > variable is apparently "totalreturn". And when you go through the else > clause you completely miss the assignment to it. When you have a > mechanism like: > > if x > y: >newval = 49 > else: >print "error message" >#newval = -5 > return newval > > Without that second assignment, you'll get "the above error" whenever > the else condition prevails. newval has no value, and in fact doesn't > exist if you go through the else clause. > > > -- > > DaveA > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Clock in tkinter?
On Thu, Nov 17, 2011 at 1:17 PM, Mic wrote: > I have now worked to stop using the global scope and instead put my > prior global variable into > the constructor in the class. I believe that I have managed to do that now. > > Do you believe that this is correctly done? > > > #Trying putting the_time'' in constructor instead of > #putting it in the global scope to shorten code. > > > def update_time(self): > self.display_time.config(text=time.strftime('%H:%M:%S'), font='40') >self.after(20, self.update_time) > Since you're using the shorter version of the function you no longer need self.the_time, so you can go ahead and remove that variable. > > I have another question. > It would have been fine (and even preferred) to create a new email here with a title something like "How do I shorten this code?" > > Say that I have a class and I want to make 100 objects. > Then it could look like this: > > class Chairs(object): > > > #Create the objects > chair1=Chairs("10","20") > chair2=Chairs("10","20") > chair3=Chairs("10","20") > > How do I shorten this? I have thought of using a for sling. I have looked > in my programming > book and on the internet, but I don’t know how to make this shorter. The > arguements (“10”, “20”) > should be the same for every object, which should make it easier than if > they were different each time? > If you ever write a line of code more than once, it's a good sign that you have what's called a code smell. This example is very smelly code ;) What you should do instead is have a collection of chairs: chairs = [] for _ in range(100): # the underscore `_` indicates that you don't care about the value chairs.append(Chairs("10","20)) You can do that even shorter with a list comprehension, but I'll leave that exercise up to you :) HTH, Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] please help - stuck for hours
i have tried everything, i am trying to build in a loop to my 2 functions which worked fine up until my latest sorti. please have a look if you can.. def exchange(cash_in):euro=1dollar=1.35base=50if cash_in>base: totalreturn=cash_in*dollarelse:totalreturn=0return totalreturn def main():amount=""while amount<50:print 'Sorry, cannot convert an amount under €50 'amount = input('how much do you want to change:')else:total=exchange(amount)print 'Your exchange comes to: ',total main() Traceback (most recent call last): File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 27, in main() File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 19, in main total=exchange(amount) File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 7, in exchangetotalreturn=cash_in*dollarTypeError: can't multiply sequence by non-int of type 'float'>>> ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] infinite loop
#i am nearly there guys..please loop at the infinite loop i am getting here..PLEASE!!#ADRIAN def exchange(cash_in):euro=1dollar=float(1.35)base=50if cash_in>base:totalreturn=cash_in*dollarelse:totalreturn=0 return totalreturn amount=float()def main():amount = float(raw_input('how much do you want to change:'))while amount<50:print 'Sorry, cannot convert an amount under €50 'else:total=exchange(amount)print 'Your exchange comes to: ',total main() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] please help - stuck for hours
On Thu, Nov 17, 2011 at 3:19 PM, ADRIAN KELLY wrote: > i have tried everything, i am trying to build in a loop to my 2 functions > which worked fine up until my latest sorti. > > please have a look if you can.. > > def exchange(cash_in): > euro=1 > dollar=1.35 > base=50 > if cash_in>base: > totalreturn=cash_in*dollar > else: > totalreturn=0 > return totalreturn > > > def main(): > amount="" > while amount<50: > print 'Sorry, cannot convert an amount under €50 ' > amount = input('how much do you want to change:') > else: > total=exchange(amount) > print 'Your exchange comes to: ',total > > > main() > > > > Traceback (most recent call last): > File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 27, > in > main() > File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 19, > in main > total=exchange(amount) > File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 7, in > exchange > totalreturn=cash_in*dollar > TypeError: can't multiply sequence by non-int of type 'float' > Thank you for posting the full traceback - this last line tells you the exact problem - you're trying to multiply a sequence by a float (in this case your sequence is a string). The line right above that tells you the what you tried to do: multiply `cash_in` by `dollar`. Take a look at your code and what do you see? Well, you set `dollar = 1.35`, and you don't change the value elsewhere so that's certainly a float. What about cash_in? Well if you work your way backwards through the traceback you see that it was called with the parameter "amount". Where is amount set? Ah, on that line: amount = input() This line is extremely problematic. First, I see by your print statement that you're using Python 2.x, so input is actually executing arbitrary code. What you *want* is raw_input which returns a string and is much MUCH safer. I don't know what your input value was, but I suspect that you did something like '30' (with the quotes), because otherwise it would evaluate to an integer. It's also possible that you used `amount`, which would evaluate to "" since you already declared it. None of these things are good. Change your initial assignment to : amount = 0 and the input line to: amount = float(raw_input("How much would you like to exchange? ")) This will first get a string from the user and then convert it to a float - which I suspect you'll want, since you're dealing with monetary values. HTH, Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] infinite loop
On Thu, Nov 17, 2011 at 3:29 PM, ADRIAN KELLY wrote: > def main(): > amount = float(raw_input('how much do you want to change:')) > while amount<50: > print 'Sorry, cannot convert an amount under €50 ' > > When do you reassign amount? HTH, Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] please help - stuck for hours
Where do you intend the variable cash_in to come from? The system doesn't know what cash_in is beyond that you mentioned it and that makes it impossible to multiply it with dollar which is a float type. If cash_in is supposed to be an input from the user, you probably should make it an int type right away before doing the multiplication. Hope this helps. Cheers. Sent from my BlackBerry wireless device from MTN -Original Message- From: ADRIAN KELLY Sender: tutor-bounces+delegbede=dudupay@python.org Date: Thu, 17 Nov 2011 21:19:45 To: Subject: [Tutor] please help - stuck for hours ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] please help - stuck for hours
thanks very much, great response really really appreciated it and now i understand. i hate to ask again but can you see why it won't print the 'enter and amount over 50' in the right place?? # -*- coding: cp1252 -*-def exchange(cash_in):euro=1dollar=1.35 base=50if cash_in>base:totalreturn=cash_in*dollarelse: totalreturn=0return totalreturn def main():amount=0while amount<50:amount = input('how much do you want to change:')print 'enter an amount over €50: 'else: total=exchange(amount)print 'Your exchange comes to: ',total main() Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 From: waynejwer...@gmail.com Date: Thu, 17 Nov 2011 15:35:29 -0600 Subject: Re: [Tutor] please help - stuck for hours To: kellyadr...@hotmail.com CC: tutor@python.org On Thu, Nov 17, 2011 at 3:19 PM, ADRIAN KELLY wrote: i have tried everything, i am trying to build in a loop to my 2 functions which worked fine up until my latest sorti. please have a look if you can.. def exchange(cash_in):euro=1dollar=1.35 base=50if cash_in>base:totalreturn=cash_in*dollar else:totalreturn=0return totalreturn def main(): amount=""while amount<50:print 'Sorry, cannot convert an amount under €50 ' amount = input('how much do you want to change:')else: total=exchange(amount)print 'Your exchange comes to: ',total main() Traceback (most recent call last): File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 27, in main() File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 19, in main total=exchange(amount) File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 7, in exchangetotalreturn=cash_in*dollar TypeError: can't multiply sequence by non-int of type 'float' Thank you for posting the full traceback - this last line tells you the exact problem - you're trying to multiply a sequence by a float (in this case your sequence is a string). The line right above that tells you the what you tried to do: multiply `cash_in` by `dollar`. Take a look at your code and what do you see? Well, you set `dollar = 1.35`, and you don't change the value elsewhere so that's certainly a float. What about cash_in? Well if you work your way backwards through the traceback you see that it was called with the parameter "amount". Where is amount set? Ah, on that line: amount = input() This line is extremely problematic. First, I see by your print statement that you're using Python 2.x, so input is actually executing arbitrary code. What you *want* is raw_input which returns a string and is much MUCH safer. I don't know what your input value was, but I suspect that you did something like '30' (with the quotes), because otherwise it would evaluate to an integer. It's also possible that you used `amount`, which would evaluate to "" since you already declared it. None of these things are good. Change your initial assignment to : amount = 0 and the input line to: amount = float(raw_input("How much would you like to exchange? ")) This will first get a string from the user and then convert it to a float - which I suspect you'll want, since you're dealing with monetary values.HTH,Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] please help - stuck for hours
On Thu, Nov 17, 2011 at 4:32 PM, ADRIAN KELLY wrote: > > thanks very much, great response really really appreciated it and now i > understand. i hate to ask again but can you see why it won't print the > 'enter and amount over 50' in the right place?? > Computers are unfailingly stupid machines. They will do whatever wrong thing you tell them to do every single time. > > def main(): > amount=0 > while amount<50: > amount = input('how much do you want to change:') > print 'enter an amount over €50: ' > else: > total=exchange(amount) > print 'Your exchange comes to: ',total > Sometimes it helps writing out the logic in steps before you translate it to code. In this case my guess is that these are the steps you want: 1. Get a value from the user (you're still using input - stop that, it's dangerous! input is only a good function in 3.x where it replaces raw_input) 2. If the value is less than 50, tell the user to enter an amount > 50 and repeat step 1 3. Otherwise, exchange the amount and display that. Right now, these are the steps that you're doing: 1. Get a value from the user 2. Display the error message 3. If the value is < 50, go to 1 4. exchange the amount 5. display the amount. HTH, Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] please help - stuck for hours
i know i should use input but when i changed to raw_input it wouldn't recognise the word print on the next line. honestly i have tried everything to get this working..i am 6 hrs at one program Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 From: waynejwer...@gmail.com Date: Thu, 17 Nov 2011 16:53:59 -0600 Subject: Re: [Tutor] please help - stuck for hours To: kellyadr...@hotmail.com CC: tutor@python.org On Thu, Nov 17, 2011 at 4:32 PM, ADRIAN KELLY wrote: thanks very much, great response really really appreciated it and now i understand. i hate to ask again but can you see why it won't print the 'enter and amount over 50' in the right place?? Computers are unfailingly stupid machines. They will do whatever wrong thing you tell them to do every single time. def main():amount=0while amount<50:amount = input('how much do you want to change:') print 'enter an amount over €50: 'else: total=exchange(amount)print 'Your exchange comes to: ',total Sometimes it helps writing out the logic in steps before you translate it to code. In this case my guess is that these are the steps you want: 1. Get a value from the user (you're still using input - stop that, it's dangerous! input is only a good function in 3.x where it replaces raw_input) 2. If the value is less than 50, tell the user to enter an amount > 50 and repeat step 1 3. Otherwise, exchange the amount and display that. Right now, these are the steps that you're doing: 1. Get a value from the user 2. Display the error message 3. If the value is < 50, go to 1 4. exchange the amount 5. display the amount. HTH,Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] urgent help!!!!!!!!!!!
i know i'm stupid but i have tried everything to get one line of text working, i have written out pseudo and read every website.now i am getting this error Traceback (most recent call last): File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex4 - Copy.py", line 24, in main() File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex4 - Copy.py", line 14, in main while amount<50:UnboundLocalError: local variable 'amount' referenced before assignment>>> def exchange(cash_in):euro=1dollar=1.35base=50if cash_in>base: totalreturn=cash_in*dollarelse:totalreturn=0return totalreturn amount=0def main():while amount<50:amount = raw_input(float('how much do you want to change:'))if amount<50:total=0print 'enter an amount over 50: 'else:total=exchange(amount)print 'Your exchange comes to: ',total Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 From: waynejwer...@gmail.com Date: Thu, 17 Nov 2011 16:53:59 -0600 Subject: Re: [Tutor] please help - stuck for hours To: kellyadr...@hotmail.com CC: tutor@python.org On Thu, Nov 17, 2011 at 4:32 PM, ADRIAN KELLY wrote: thanks very much, great response really really appreciated it and now i understand. i hate to ask again but can you see why it won't print the 'enter and amount over 50' in the right place?? Computers are unfailingly stupid machines. They will do whatever wrong thing you tell them to do every single time. def main():amount=0while amount<50:amount = input('how much do you want to change:') print 'enter an amount over €50: 'else: total=exchange(amount)print 'Your exchange comes to: ',total Sometimes it helps writing out the logic in steps before you translate it to code. In this case my guess is that these are the steps you want: 1. Get a value from the user (you're still using input - stop that, it's dangerous! input is only a good function in 3.x where it replaces raw_input) 2. If the value is less than 50, tell the user to enter an amount > 50 and repeat step 1 3. Otherwise, exchange the amount and display that. Right now, these are the steps that you're doing: 1. Get a value from the user 2. Display the error message 3. If the value is < 50, go to 1 4. exchange the amount 5. display the amount. HTH,Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] binary file query
On 17/11/11 14:55, Prasad, Ramit wrote: It means that no need to use the 'Struct' module for binary file read, right? Its not necessary but if the data does not already have a file handling module then the struct module is a very convenient way of accessing the data. It really depends on your file. The struct module says, "This module performs conversions between Python values and C structs represented as Python strings." If your file is not a C-struct data then no need to use the struct module. No *need* but, often convenient, regardless of whether the data was written by a C struct or not.(*) It is a way to interpret binary data in terms of fundamental data types such as ints, floats, strings etc. Trying to convert raw bytes representing floats into a floating point number without using struct would be an interesting exercise. Using struct it's trivial. Struct works with any kind of basic binary data provided you know what the byte sequence represents. Where it breaks down is when it represents more complex concepts like references to objects and even graphical bitmaps etc. That's where dedicated file handling modules come into play. (*)The struct docs acknowledge this with the following comment: "To handle platform-independent data formats or omit implicit pad bytes, use standard size and alignment instead of native size and alignment: see Byte Order, Size, and Alignment for details." -- 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
Re: [Tutor] urgent help!!!!!!!!!!!
My mail client stripped new lines, at least on this machine, so I will just top-post this. Sorry! Your problem is that you say: amount=0 def main()... You then try to use amount in main, but main has no amount in it. Either move "amount=0" inside main, or put a global reference: amount=0 def main(): global amount ... On 11/17/11, ADRIAN KELLY wrote: > > i know i'm stupid but i have tried everything to get one line of text > working, i have written out pseudo and read every website.now i am > getting this error > Traceback (most recent call last): File "F:\VTOS > ATHLONE\PYTHON_VTOS\foreign exchange\f_ex4 - Copy.py", line 24, in > main() File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex4 - > Copy.py", line 14, in mainwhile amount<50:UnboundLocalError: local > variable 'amount' referenced before assignment>>> > > > def exchange(cash_in):euro=1dollar=1.35base=50if > cash_in>base:totalreturn=cash_in*dollarelse: > totalreturn=0return totalreturn > amount=0def main():while amount<50:amount = raw_input(float('how > much do you want to change:'))if amount<50:total=0print > 'enter an amount over 50: 'else:total=exchange(amount) > print 'Your exchange comes to: ',total > > > > > Adrian Kelly > 1 Bramble Close > > Baylough > > Athlone > > County Westmeath > > 0879495663 > > > From: waynejwer...@gmail.com > Date: Thu, 17 Nov 2011 16:53:59 -0600 > Subject: Re: [Tutor] please help - stuck for hours > To: kellyadr...@hotmail.com > CC: tutor@python.org > > On Thu, Nov 17, 2011 at 4:32 PM, ADRIAN KELLY > wrote: > > > > > > > > > thanks very much, great response really really appreciated it and now i > understand. i hate to ask again but can you see why it won't print the > 'enter and amount over 50' in the right place?? > > > Computers are unfailingly stupid machines. They will do whatever wrong thing > you tell them to do every single time. > > def main():amount=0while amount<50:amount = > input('how much do you want to change:') > > print 'enter an amount over €50: 'else: > total=exchange(amount)print 'Your exchange comes to: ',total > > > Sometimes it helps writing out the logic in steps before you translate it to > code. In this case my guess is that these are the steps you want: > 1. Get a value from the user (you're still using input - stop that, it's > dangerous! input is only a good function in 3.x where it replaces > raw_input) > >2. If the value is less than 50, tell the user to enter an amount > 50 > and repeat step 1 > 3. Otherwise, exchange the amount and display that. > Right now, these are the steps that you're doing: > > > 1. Get a value from the user > 2. Display the error message > 3. If the value is < 50, go to 1 > 4. exchange the amount > > > 5. display the amount. > HTH,Wayne -- Have a great day, Alex (msg sent from GMail website) mehg...@gmail.com; http://www.facebook.com/mehgcap ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python telnet
Rayon wrote: I am trying to use winpexpect to connect a telnet session. I keep getting this error. raise ExceptionPexpect, 'Command not found: %s' % self.command ExceptionPexpect: Command not found: telnet Please copy and paste the entire traceback, not just the last couple of lines. But judging by just the small bit you show, it looks like "telnet" is not a command that winpexpect understands, so it raises an error "command not found". Perhaps it is a bug in winpexpect. Are you using the latest version? Do you actually have telnet available on your system? If not, then you can't expect winpexpect to use something which isn't there. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] please help - stuck for hours
On 17/11/11 23:12, ADRIAN KELLY wrote: i know i should use input but when i changed to raw_input In Python v3 use input() In python v2 input() is dangerous, use raw_input() instead. > ... it wouldn't recognise the word print on the next line. Show us the exact code and error. You may be missing a parenthesis, or maybe you are just expecting the wrong behaviour... It won't execute the print until after it has read your input. everything to get this working.. i am 6 hrs at one program Heh, I've got one I've been working on for over 10 years, 6 hours is nothing! :-) -- 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
Re: [Tutor] infinite loop
On 17/11/11 21:29, ADRIAN KELLY wrote: amount=float() You don;t need this line because you assign a value to amount immediately you run main() def main(): amount = float(raw_input('how much do you want to change:')) while amount<50: print 'Sorry, cannot convert an amount under €50 ' To get a while loop to terminate you must change something about the test condition. In this case the test value 50 is a constant so it needs to be amount that changes. But you only print a message... You need to read a new amount. else: total=exchange(amount) print 'Your exchange comes to: ',total You don't really want/need the else: line. It's not wrong but its more normal to see it done like this: while loop body here next statement with no explicit else. In fact, thinking about it, I've never found a use for the while/else construct, has anyone else? -- 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
Re: [Tutor] urgent help!!!!!!!!!!!
def exchange(cash_in): euro=1 dollar=1.35 base=50 if cash_in>base: totalreturn=cash_in*dollar else: totalreturn=0 return totalreturn amount=0 # this would be better placed inside the main function. def main(): while amount<50: amount = raw_input(float('how much do you want to change:')) # This should be # amount = float( raw_input('how much do you want to change:' ) ) if amount<50: total=0 print 'enter an amount over 50: ' else: total=exchange(amount) print 'Your exchange comes to: ',total Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to understand unhashable type: 'list'
On 17/11/11 15:30, lina wrote: tuple (which I don't understand). You mean you don't understand the term 'tuple'? Basically its just a collection of data. You can get a triple - 3 items, a quadruple - 4 items, quintiple - 5 items etc The generic term for a collection of N items is a tuple. triple, quadruple, etc are all specific types of tuple. It's a math thing... In python a tuple is just lie a list except you can't change it - ie. it is immutable. This makes it perfect for using as a key in a dictionary when you'd like to use a list... As an aside some folks like to distinguish between tuples and lists by suggesting that tuples can hold collections of different types of data: t = (1,'two', 3.0) whereas lists should only hold items of the same type. L = [1,2,3] But that's a semantic nicety, Python doesn't make any such distinction. And for dictionary keys (1,2,3) is the only way to do it... -- 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] Encoding
Hi all, In my programme I am encoding what the user has in-putted. What the user inputs will in a string, which might a mixture of letters and numbers. However I only want the letters to be encoded. Does any-one how I can only allow the characters to be encoded ?? Big thanks, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] The Perennial 3.2 vs 2.7
Okay, so I am about to take up the banner of learning Python again. I had started with 3.2 and I have a book that I like. But all of the things that I want to use Python for appear to be 2.x specific. Will I be setting myself up for failure if I continue learning 3 and then try to write programs in 2.x? Note that I am an experienced programmer, albeit in curly-brace languages (Perl, Java, C#, HTML/CSS/JavaScript), so that will probably count in my favor. But y'all would know better than I if there are significant issues that I will need to overcome conceptually. -- Mark :) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The Perennial 3.2 vs 2.7
On Nov 17, 2011 8:28 PM, "Mark Lybrand" wrote: > > Okay, so I am about to take up the banner of learning Python again. I had started with 3.2 and I have a book that I like. But all of the things that I want to use Python for appear to be 2.x specific. Will I be setting myself up for failure if I continue learning 3 and then try to write programs in 2.x? Note that I am an experienced programmer, albeit in curly-brace languages (Perl, Java, C#, HTML/CSS/JavaScript), so that will probably count in my favor. But y'all would know better than I if there are significant issues that I will need to overcome conceptually. The main differences are syntactic. If you add these lines to the top of your 2.7 files then you won't have much else to worry about. from __future__ import print_function, unicode_literals, division, absolute_import range, input = xrange, raw_input There may be some other differences but those should take care of the larger ones. HTH, Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Encoding
On 11/17/2011 8:45 PM, Nidian Job-Smith wrote: Hi all, In my programme I am encoding what the user has in-putted. What the user inputs will in a string, which might a mixture of letters and numbers. However I only want the letters to be encoded. Does any-one how I can only allow the characters to be encoded ?? Your question makes no sense to me. Please explain what you mean by encoding letters? An example of input and output might also help. Be sure to reply-all. -- 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
[Tutor] Doctest error!
Hi all, When i run a doctest on this piece of code (shown at bottom) i get this error message [from the doctest]: Trying: rot13('5 The Parade') Expecting: '5 Gur Cnenqr' ** File "F:\Uni\Rot13_1.py", line 12, in Rot13_1.rot13 Failed example: rot13('5 The Parade') Expected: '5 Gur Cnenqr' Got: 'B-aur-]n\x7fnqr' Trying: rot13('5 Gur Cnenqr') Expecting: '5 The Parade' ** File "F:\Uni\Rot13_1.py", line 14, in Rot13_1.rot13 Failed example: rot13('5 Gur Cnenqr') Expected: '5 The Parade' Got: 'B-T\x82\x7f-P{r{~\x7f' An one have any idea why? (I'm guessing its to do with the numbers) code: def rot13(s): """ >>> type(rot13("bob")) >>> len(rot13("foobar")) 6 >>> rot13("abc") 'nop' >>> rot13("XYZ") 'KLM' >>> rot13('5 The Parade') '5 Gur Cnenqr' >>> rot13('5 Gur Cnenqr') '5 The Parade' """ result = '' # initialize output to empty for char in s: # iterate over string if int: char_low = s.lower() if char_low<= 'm': dist = 13 else: dist = -13 char = chr(ord(char) + dist) result+=char return result ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Doctest error!
On 11/18/2011 10:29 AM, John wrote: Hi all, When i run a doctest on this piece of code (shown at bottom) i get this error message [from the doctest]: Trying: rot13('5 The Parade') Expecting: '5 Gur Cnenqr' ** File "F:\Uni\Rot13_1.py", line 12, in Rot13_1.rot13 Failed example: rot13('5 The Parade') Expected: '5 Gur Cnenqr' Got: 'B-aur-]n\x7fnqr' Trying: rot13('5 Gur Cnenqr') Expecting: '5 The Parade' ** File "F:\Uni\Rot13_1.py", line 14, in Rot13_1.rot13 Failed example: rot13('5 Gur Cnenqr') Expected: '5 The Parade' Got: 'B-T\x82\x7f-P{r{~\x7f' An one have any idea why? (I'm guessing its to do with the numbers) code: def rot13(s): """ >>> type(rot13("bob")) >>> len(rot13("foobar")) 6 >>> rot13("abc") 'nop' >>> rot13("XYZ") 'KLM' >>> rot13('5 The Parade') '5 Gur Cnenqr' >>> rot13('5 Gur Cnenqr') '5 The Parade' """ result = '' # initialize output to empty for char in s: # iterate over string if int: char_low = s.lower() if char_low<= 'm': dist = 13 else: dist = -13 char = chr(ord(char) + dist) result+=char return result The line "if int:" is clearly wrong. Did you write this code yourself, or was it typed in from a listing somewhere? I'd assume that you wanted to do some check on the char value. But if int will always be true. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] infinite loop
On 11/17/2011 04:29 PM, ADRIAN KELLY wrote: #i am nearly there guys..please loop at the infinite loop i am getting here..PLEASE!!#ADRIAN def exchange(cash_in):euro=1dollar=float(1.35)base=50if cash_in>base:totalreturn=cash_in*dollarelse:totalreturn=0 return totalreturn amount=float()def main():amount = float(raw_input('how much do you want to change:'))while amount<50:print 'Sorry, cannot convert an amount under €50 'else:total=exchange(amount)print 'Your exchange comes to: ',total main() Till you learn how to post in text mode, I and many others will be unable to read your messages. See how the lines above are all running together? But congratulations on picking a good subject for this one. Others like "please help" are useless subject lines. While I've got your attention, please put your response after the material you're quoting. Not before. And use standard quoting techniques so people can tell your portions apart from the rest. (That last point will probably address itself when you switch to non-html messages) -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Doctest error!
> Date: Thu, 17 Nov 2011 22:49:33 -0500 > From: d...@davea.name > To: nidia...@hotmail.com > CC: tutor@python.org > Subject: Re: [Tutor] Doctest error! > > On 11/18/2011 10:29 AM, John wrote: > > > > Hi all, > > When i run a doctest on this piece of code (shown at bottom) i get > > this error message [from the doctest]: > > > > > > > > Trying: > > rot13('5 The Parade') > > Expecting: > > '5 Gur Cnenqr' > > ** > > File "F:\Uni\Rot13_1.py", line 12, in Rot13_1.rot13 > > Failed example: > > rot13('5 The Parade') > > Expected: > > '5 Gur Cnenqr' > > Got: > > 'B-aur-]n\x7fnqr' > > Trying: > > rot13('5 Gur Cnenqr') > > Expecting: > > '5 The Parade' > > ** > > File "F:\Uni\Rot13_1.py", line 14, in Rot13_1.rot13 > > Failed example: > > rot13('5 Gur Cnenqr') > > Expected: > > '5 The Parade' > > Got: > > 'B-T\x82\x7f-P{r{~\x7f' > > > > > > > > An one have any idea why? (I'm guessing its to do with the numbers) > > > > > > code: > > > > def rot13(s): > > > > """ > > >>> type(rot13("bob")) > > > > >>> len(rot13("foobar")) > > 6 > > >>> rot13("abc") > > 'nop' > > >>> rot13("XYZ") > > 'KLM' > > >>> rot13('5 The Parade') > > '5 Gur Cnenqr' > > >>> rot13('5 Gur Cnenqr') > > '5 The Parade' > > """ > > result = '' # initialize output to empty > > for char in s: # iterate over string > > if int: > > char_low = s.lower() > > if char_low<= 'm': > > dist = 13 > > else: > > dist = -13 > > char = chr(ord(char) + dist) > > result+=char > > return result > > The line "if int:" is clearly wrong. Did you write this code > yourself, or was it typed in from a listing somewhere? I'd assume that > you wanted to do some check on the char value. But if int will always > be true. > > > > > -- > > DaveA I want it to look in s, and only perform this code on the letters in s(not numbers): char_low = s.lower() if char_low <= 'm': dist = 13 else: dist = -13 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Doctest error!
On 11/17/2011 10:56 PM, Nidian Job-Smith wrote: Date: Thu, 17 Nov 2011 22:49:33 -0500 From: d...@davea.name To: nidia...@hotmail.com CC: tutor@python.org Subject: Re: [Tutor] Doctest error! On 11/18/2011 10:29 AM, John wrote: Hi all, When i run a doctest on this piece of code (shown at bottom) i get this error message [from the doctest]: Trying: rot13('5 The Parade') Expecting: '5 Gur Cnenqr' ** File "F:\Uni\Rot13_1.py", line 12, in Rot13_1.rot13 Failed example: rot13('5 The Parade') Expected: '5 Gur Cnenqr' Got: 'B-aur-]n\x7fnqr' Trying: rot13('5 Gur Cnenqr') Expecting: '5 The Parade' ** File "F:\Uni\Rot13_1.py", line 14, in Rot13_1.rot13 Failed example: rot13('5 Gur Cnenqr') Expected: '5 The Parade' Got: 'B-T\x82\x7f-P{r{~\x7f' An one have any idea why? (I'm guessing its to do with the numbers) code: def rot13(s): """ type(rot13("bob")) len(rot13("foobar")) 6 rot13("abc") 'nop' rot13("XYZ") 'KLM' rot13('5 The Parade') '5 Gur Cnenqr' rot13('5 Gur Cnenqr') '5 The Parade' """ result = '' # initialize output to empty for char in s: # iterate over string if int: char_low = s.lower() if char_low<= 'm': dist = 13 else: dist = -13 char = chr(ord(char) + dist) result+=char return result The line "if int:" is clearly wrong. Did you write this code yourself, or was it typed in from a listing somewhere? I'd assume that you wanted to do some check on the char value. But if int will always be true. -- DaveA I want it to look in s, and only perform this code on the letters in s(not numbers): char_low = s.lower()if char_low<= 'm':dist = 13else:dist = -13 Your formatting is messed up, and I can now see there at least one other bug in it anyway. The method to check if a particular character is alphabetic is str.isalpha(). See if you can see what variable to call that on. Hint: it's not s, since you want to check one character at a time in your loop. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The Perennial 3.2 vs 2.7
Forwarding on to the list... (hit reply to all next time) On Thu, Nov 17, 2011 at 8:45 PM, Mark Lybrand wrote: > so, use my 2.7 and not my 3.2 for my study? Or use my 3.2 for study and > then do what I have to in 2.7 after including those lines? > > Thanks for the quick reply by the way. I am still struggling with the loss > od curly braces :) > Honestly it probably doesn't matter. Many 3rd party libraries have now been ported to Python 3.x, so unless you have a particular library you're interested in, I would start with 3.2 until you find something you can't do. As far as the curly braces go... just think about everything that isn't really programming, but telling the compiler something. Get rid of it, and you probably have Python... and you can always try: from __future__ import braces ;) HTH, Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor