Re: [Tutor] Tutor Digest, Vol 174, Issue 2
I am running only one line of code "import requests" Error I am getting is below Traceback (most recent call last): File "/Users/saketmehrotra/Documents/Flaskask.py", line 4, in import requests File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/__init__.py", line 95, in from urllib3.contrib import pyopenssl File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/urllib3/contrib/pyopenssl.py", line 80, in ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD, AttributeError: 'module' object has no attribute 'PROTOCOL_SSLv On Wed, Aug 1, 2018 at 9:30 PM, wrote: > Send Tutor mailing list submissions to > tutor@python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-requ...@python.org > > You can reach the person managing the list at > tutor-ow...@python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > Today's Topics: > >1. Re: SSL Error (Alan Gauld) > > > -- Forwarded message -- > From: Alan Gauld > To: tutor@python.org > Cc: > Bcc: > Date: Wed, 1 Aug 2018 09:13:07 +0100 > Subject: Re: [Tutor] SSL Error > On 01/08/18 05:07, Saket Mehrotra wrote: > > Hi > > > > I am also not using any Open SSL package. > > I have just added " import requests" in py file. And when I run the > module > > I get the SSL package error ,not sure why. > > Then you really need to send the complete error message > and the code that generates it - the full function > definition at least. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > > > ___ > Tutor maillist - Tutor@python.org > https://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Removing duplicates
I'm trying to get a list of tuples to be a float, a numerator, and a denominator for all the fractions: halves, thirds, fourths etc up to ninths. 1/2 returns the same float as 2/4, 3/6, 4/8. I would like to keep only the 1/2. When I try (line 18) to "pop" from the list I get a "TypeError: integer argument expected, got float". When I try (line 18) to "remove" from the list, nothing happens: nothing is removed and I do not receive an error message. What do you think is a good way to solve this? Thank you as always. import math fractions = [(0, 0, 0)] for i in range(1, 10): for j in range(1, 10): if i < j: x = i/j if x not in fractions: fractions.append((x, i, j)) sortedFrac = sorted(fractions) print(sortedFrac) for i in range(len(sortedFrac)): try: if sortedFrac[i][0] == sortedFrac[i-1][0]: # so if the float equals the previous float sortedFrac.pop(sortedFrac[i][0]) # remove the second float else: sortedFrac.append(sortedFrac[i][0]) except ValueError: continue -- Roger Lea Scherer 623.255.7719 *Strengths:* Input, Strategic, Responsibility, Learner, Ideation ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Removing duplicates
On 1 August 2018 at 21:38, Roger Lea Scherer wrote: > > I'm trying to get a list of tuples to be a float, a numerator, and a > denominator for all the fractions: halves, thirds, fourths etc up to > ninths. 1/2 returns the same float as 2/4, 3/6, 4/8. I would like to keep > only the 1/2. When I try (line 18) to "pop" from the list I get a "TypeError: > integer argument expected, got float". When I try (line 18) to "remove" > from the list, nothing happens: nothing is removed and I do not receive an > error message. > > What do you think is a good way to solve this? > > Thank you as always. > > import math > > fractions = [(0, 0, 0)] > > for i in range(1, 10): > for j in range(1, 10): > if i < j: > x = i/j > if x not in fractions: > fractions.append((x, i, j)) > sortedFrac = sorted(fractions) > > print(sortedFrac) > > for i in range(len(sortedFrac)): > try: > if sortedFrac[i][0] == sortedFrac[i-1][0]: # so if the float equals > the previous float > sortedFrac.pop(sortedFrac[i][0]) # remove the second > float > else: > sortedFrac.append(sortedFrac[i][0]) > except ValueError: > continue Comparing floats for equality can be flakey. Sometimes two floats that should be equal will not compare equal e.g.: >>> 0.01 + 0.1 - 0.1 == 0.01 False This happens in this case because of intermediate rounding errors. I don't think that should affect you since you are doing precisely one floating point operation i/j to calculate each of your floats but unless you have a very solid understanding of binary floating point I would recommend that you shouldn't compare floating point values as in a==b. For this particular problem I would use integer arithmetic or I would use the fractions module. Doing this with integers you should normalise the numerator and denominator by dividing out their GCD. The fractions module takes care of this for you internally. https://docs.python.org/3.7/library/fractions.html Otherwise in general to remove duplicates you would be better of with a set rather than a list. If you only put x in the set and not i and j then the set will automatically take care of duplicates: https://docs.python.org/3.7/tutorial/datastructures.html#sets -- Oscar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Removing duplicates
Oscar Benjamin wrote: > On 1 August 2018 at 21:38, Roger Lea Scherer wrote: >> >> I'm trying to get a list of tuples to be a float, a numerator, and a >> denominator for all the fractions: halves, thirds, fourths etc up to >> ninths. 1/2 returns the same float as 2/4, 3/6, 4/8. I would like to keep >> only the 1/2. When I try (line 18) to "pop" from the list I get a >> "TypeError: >> integer argument expected, got float". When I try (line 18) to "remove" >> from the list, nothing happens: nothing is removed and I do not receive >> an error message. >> >> What do you think is a good way to solve this? >> >> Thank you as always. >> >> import math >> >> fractions = [(0, 0, 0)] >> >> for i in range(1, 10): >> for j in range(1, 10): >> if i < j: >> x = i/j >> if x not in fractions: >> fractions.append((x, i, j)) >> sortedFrac = sorted(fractions) >> >> print(sortedFrac) >> >> for i in range(len(sortedFrac)): >> try: >> if sortedFrac[i][0] == sortedFrac[i-1][0]: # so if the float >> equals >> the previous float >> sortedFrac.pop(sortedFrac[i][0]) # remove the >> second >> float >> else: >> sortedFrac.append(sortedFrac[i][0]) >> except ValueError: >> continue > > Comparing floats for equality can be flakey. Sometimes two floats that > should be equal will not compare equal e.g.: > 0.01 + 0.1 - 0.1 == 0.01 > False Do you know if there's a way to construct an example where i/k != (n*i)/(n*k) with preferrably small integers i, k, and n? Python's integer division algorithm defeats my naive attempts ;) I had to resort to i/k == i/(k + 1) >>> k = 10**18 >>> 1/k == 1/(k+1) True > This happens in this case because of intermediate rounding errors. I > don't think that should affect you since you are doing precisely one > floating point operation i/j to calculate each of your floats but > unless you have a very solid understanding of binary floating point I > would recommend that you shouldn't compare floating point values as in > a==b. > > For this particular problem I would use integer arithmetic or I would > use the fractions module. Doing this with integers you should > normalise the numerator and denominator by dividing out their GCD. The > fractions module takes care of this for you internally. > https://docs.python.org/3.7/library/fractions.html > > Otherwise in general to remove duplicates you would be better of with > a set rather than a list. If you only put x in the set and not i and j > then the set will automatically take care of duplicates: > https://docs.python.org/3.7/tutorial/datastructures.html#sets And if you want to keep i and j you can use a dict: fractions = {} for i in range(1, 10): for j in range(1, 10): if i < j: x = i/j if x not in fractions: fractions[x] = x, i, j sorted_unique_fractions = sorted(fractions.values()) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] try, except syntax
MAC OS X 10.13.6 Anaconda python 3.6.5 Anaconda IPython 6.4.0 I am having difficulty in using the try, except form. I copy and paste a minimal program to illustrate my problem. #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 2 15:41:15 2018 @author: sydney """ uvc = 2 msg = "Bad argument provided, the value of uvc must be a float." try: type(uvc) == float except TypeError as e: print(e, msg) try: 0.0 > uvc < 1.0 except ValueError: print("Bad argument provided. The value of uvc must be " "greater than 0.0 and less than 1.0.") if type(uvc) != float: raise TypeError("Bad argument provided. And this is also old test." " The value of UVC must be a float. This is old test") if uvc < 0.0 or uvc > 1.0: raise ValueError("Bad argument provided. The value of uvc must be " "greater than 0.0 and less than 1.0. This is old test") My problem is this. The two, 'if statements' at the end of the little program work as intended. And I have been using them in a larger program for some time and they have been checked regularly and they work as intended. I am now rewriting a class, as recommended by both Alan and Steven, in which I have previously used these formulations. This time, I thought that perhaps it would be more "pythonic" to write them as try, except. But I cannot find the correct format. I have read and reread the books and the documentation, but I am clearly stupid today. Either I do not need this change or I have written the try, except incorrectly. I am sure that I am making an elementary mistake. Will someone please show tell me whether I should use try, except instead of if ... and then what is the correct syntax. Thanks as always. -- _ Professor Sydney Shall Department of Haematology/Oncology Phone: +(0)2078489200 E-Mail: sydney.shall [Correspondents outside the College should add @kcl.ac.uk] ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Removing duplicates
On 2 August 2018 at 13:49, Peter Otten <__pete...@web.de> wrote: > Oscar Benjamin wrote: >> >> Comparing floats for equality can be flakey. Sometimes two floats that >> should be equal will not compare equal e.g.: >> > 0.01 + 0.1 - 0.1 == 0.01 >> False > > Do you know if there's a way to construct an example where > > i/k != (n*i)/(n*k) > > with preferrably small integers i, k, and n? There wouldn't be for small integers. The simplest possible way for Python to implement the division is to convert both numerator and denominator to float before dividing with floating point. For integers up to ~10**16 the conversion to float will be exact. IEEE 754 requires that the divisions would always give the same result since it should give the true result correctly rounded: both divisions should give the same result if the true ratio of the floats is the same. Actually looking here: https://github.com/python/cpython/blob/3.7/Objects/longobject.c#L3835 that is exactly what happens for small integers. Also it looks as if the algorithm for large integers is designed to compute the true result correctly rounded as well. As it mentions in the code though "results may be subject to double rounding on x86 machines that operate with the x87 FPU set to 64-bit precision." What that means is that on some 32 bit CPUs that don't have SSE2 you may see results that are rounded differently. So leaving aside older hardware I don't think there will be a case where i/k != (n*i)/(n*k). All the same I prefer not to use floating point for exact calculations and I would always recommend that a beginner think of floating point operations as inexact. > Python's integer division > algorithm defeats my naive attempts ;) I haven't tried to properly understand the code in long_true_divide but it definitely looks like whoever wrote it knew what they were doing :) Cheers, Oscar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] try, except syntax
On 2 August 2018 at 15:29, Shall, Sydney wrote: > > try: > type(uvc) == float > except TypeError as e: > print(e, msg) Let's try this interactively: >>> uvc = 2 >>> type(uvc) >>> type(uvc) == float False So calling type(uvc) doesn't raise an error. It returns the type "int". You then compare this with the type "float" and they are not equal so the comparison results in False. No exception is raised by this code because there hasn't been an error anywhere. If no exception is raised then you cannot catch an exception with try/except. You should use try/except around some code that would raise an exception if given the wrong sort of input e.g.: numstring = input('Enter a number') try: number = int(numstring) except ValueError: print('Not a decimal number: %r' % numstring) In your case do you even need to do this type check? If you're catching the exception then you could also just not catch the exception so that the user sees the error message. The answer to this depends on what kind of user you have. If a user isn't directly touching the code then it shouldn't be possible for them to change the type of uvc so this exception won't occur and you don't need to check for it. If the user is both editing and running the code (e.g. if you are the only user) then it's usually okay to let them see the normal error message that Python will print out so again you don't need to check for it. On the other hand if the user does something that won't *already* lead to an exception but would result in your code doing something meaningless (such as giving a negative number) then that is a good time for you to check something and raise an exception yourself. -- Oscar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] try, except syntax
try... except is meant to catch errors: places where your program would otherwise crash. It does NOT work as a truth check. In your example: > try: > type(uvc) == float > except TypeError as e: > print(e, msg) > > "type(uvc)==float" resolves to a standalone True or False, not an exception. What you want in that case is an assertion: > try: > assert type(uvc)==float > except AssertionError as e: > print(e, msg) An assertion says "The following statement is True. If it isn't, I'm going to throw an exception." They're especially useful when writing tests, and should be part of your flow-control toolbox. In your last two examples, > if type(uvc) != float: > raise TypeError("Bad argument provided. And this is also old test." > " The value of UVC must be a float. This is old test") > if uvc < 0.0 or uvc > 1.0: > raise ValueError("Bad argument provided. The value of uvc must be " > "greater than 0.0 and less than 1.0. This is old > test") I assume you must either already be using try/except, or else never getting incorrect input; if you raise an exception but don't catch it, the program terminates. I would wrap those thusly: > try: > if type(uvc) != float: > raise TypeError("Bad argument provided. And this is also old test." > " The value of UVC must be a float. This is old > test") > if uvc < 0.0 or uvc > 1.0: > raise ValueError("Bad argument provided. The value of uvc must be " >"greater than 0.0 and less than 1.0. This is old > test") > except Error as e: > print(e,msg) Generally, however, my approach is to use if/then for normal program flow, and wrap those in try/except for cases where e.g. user error may cause crashes. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Getting current listbox item index and bind it to button (Tkinter)
Hi, in my code i have the curselection in my enter_meaning function, and it works well and prints the result which comes from db to the text widget. When user searches in entrybox the list lowers down to 1 item, how can i get the index of that item and bind it to the button so it will print the result like curselection does but with pressing the Enter key on keyboard? I tried writing the search_word function and binded it to the button, but it doesn't work, please help i'm still a beginner. import sqlite3 as sqlite import tkinter as tk from tkinter import ttk # GUI Widgets class EsperantoDict: def __init__(self, master): master.title("EsperantoDict") master.iconbitmap("Esperanto.ico") master.resizable(False, False) master.configure(background='#EAFFCD') self.style = ttk.Style() self.search_var = tk.StringVar() self.search_var.trace("w", lambda name, index, mode: self.update_list()) self.style = ttk.Style() self.style.configure("TFrame", background='#EAFFCD') self.style.configure("TButton", background='#C6FF02') self.style.configure("TLabel", background='#EAFFCD') self.frame_header = ttk.Frame(master, relief=tk.FLAT) self.frame_header.config(style="TFrame") self.frame_header.pack(side=tk.TOP, padx=5, pady=5) self.logo = tk.PhotoImage(file=r'C:\EsperantoDict\eo.png') self.small_logo = self.logo.subsample(10, 10) ttk.Label(self.frame_header, image=self.small_logo).grid(row=0, column=0, stick="ne", padx=5, pady=5, rowspan=2) ttk.Label(self.frame_header, text='EsperantoDict', font=('Arial', 18, 'bold')).grid(row=0, column=1) self.frame_content = ttk.Frame(master) self.frame_content.config(style="TFrame") self.frame_content.pack() self.entry_search = ttk.Entry(self.frame_content, textvariable=self.search_var, width=30) self.entry_search.bind('', self.entry_delete) self.entry_search.bind('', self.entry_insert) self.entry_search.grid(row=0, column=0, padx=5) self.entry_search.focus() self.entry_search.bind("", self.edit_input) self.button_search = ttk.Button(self.frame_content, text="Search") self.photo_search = tk.PhotoImage(file=r'C:\EsperantoDict\search.png') self.small_photo_search = self.photo_search.subsample(3, 3) self.button_search.config(image=self.small_photo_search, compound=tk.LEFT, style="TButton") self.button_search.grid(row=0, column=2, columnspan=1, sticky='nw', padx=5) self.button_search.bind('', self.search_word) self.listbox = tk.Listbox(self.frame_content, height=30, width=30) self.listbox.grid(row=1, column=0, padx=5) self.scrollbar = ttk.Scrollbar(self.frame_content, orient=tk.VERTICAL, command=self.listbox.yview) self.scrollbar.grid(row=1, column=1, sticky='nsw') self.listbox.config(yscrollcommand=self.scrollbar.set) self.listbox.bind('<>', self.enter_meaning) self.textbox = tk.Text(self.frame_content, relief=tk.GROOVE, width=60, height=30, borderwidth=2) self.textbox.config(wrap='word') self.textbox.grid(row=1, column=2, sticky='w', padx=5) # SQLite self.db = sqlite.connect(r'C:\EsperantoDict\test.db') self.cur = self.db.cursor() self.cur.execute("SELECT Esperanto FROM Words ORDER BY Esperanto") for row in self.cur: self.listbox.insert(tk.END, row) self.update_list() def update_list(self): self.listbox.delete(0, tk.END) search_term = self.search_var.get().lower() if search_term == 'type to search': search_term = '' self.cur.execute("SELECT Esperanto FROM Words WHERE LOWER(Esperanto) LIKE ? ORDER BY Esperanto", ('%'+search_term+'%',)) for row in self.cur: item = row[0] self.listbox.insert(tk.END, item) for row in range(0, self.listbox.size(), 2): self.listbox.itemconfigure(row, background="#f0f0ff") def edit_input(self, tag): word_to_esp = {'gx': 'ĝ', 'cx': 'ĉ', 'hx': 'ĥ', 'jx': 'ĵ', 'ux': 'ŭ', 'sx': 'ŝ'} user_input = self.entry_search.get() user_input = user_input.lower() for i in word_to_esp: if user_input.__contains__(i): a = user_input.replace(i, word_to_esp[i]) return self.search_var.set(a) # SQLite def enter_meaning(self, tag): for index in self.listbox.curselection(): esperanto = self.listbox.get(index) results = self.cur.execute("SELECT English FROM Words WHERE Esperanto = ?", (esperanto,)) for row in results: self.textbox.delete(1.0, tk.END) self.textbox.insert(tk.END, row[0]) def entry_delete(self, tag): if self.entry_search.get(): self.entry_search.delete(0, tk.END) s
Re: [Tutor] Getting current listbox item index and bind it to button (Tkinter)
On 02/08/18 21:12, Ali M wrote: > I tried writing the search_word function and binded it to the button, but > it doesn't work, please help i'm still a beginner. > > def search_word(self, tag): > esperanto = self.listbox.selection_set(0) > results = self.cur.execute("SELECT English FROM Words WHERE > Esperanto = ?", (esperanto,)) > for row in results: > self.textbox.delete(1.0, tk.END) > self.textbox.insert(tk.END, row[0]) The last bit looks suspicious. You delete the contents of textbox each time round the loop. Surely you only want to delete it once before the loop? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] try, except syntax
On 02/08/18 15:29, Shall, Sydney wrote: > uvc = 2 > msg = "Bad argument provided, the value of uvc must be a float." > > try: > type(uvc) == float > except TypeError as e: > print(e, msg) The try block contains an expression that will always evaluate to True or False and thus never raise an exception. Since the expression is never stored or used(in an if or while say) the block does nothing useful. > try: > 0.0 > uvc < 1.0 > except ValueError: > print("Bad argument provided. The value of uvc must be " > "greater than 0.0 and less than 1.0.") This also has an expression but it will never generate a ValueError since its only testing if uvc is between the two values. Again it will either be True or False provided the value of uvc is of a numeric type If not it will generate a TypeError. So rather than testing for a ValueError which will never happen, you should be testing for a TypeError. Exceptions are about handling the unexpected, not about managing flow control in your normal execution path. > if type(uvc) != float: > raise TypeError("Bad argument provided. And this is also old test." > " The value of UVC must be a float. This is old test") Raising the error is fine but it will cause your program to stop. Is that what you want? But mostly in Python we don't check types before using them we use TypeError to catch the mistake when it happens. we are not using try/except to look for wrong types, we just catch the error if it occurs. Mostly we hope it won't. try: your expected normal code here except SomeError catch anything that you hope won't happen but might. > I am now rewriting a class, as recommended by both Alan and Steven, in > which I have previously used these formulations. > > today. Either I do not need this change or I have written the try, > except incorrectly. I am sure that I am making an elementary mistake. Maybe both. If you really do need to do the checks as part of your normal logic then continue using the if style. But if you just think there's a possibility of a wrong value/type being passed then write your code as if there were no errors but wrap it in a try/except block. But only if you can actually do something when the error occurs, otherwise you might as well let Python deal with it and print a traceback. The key thing about try/except is that you should be able to delete it and your code (ie. the try block) should carry on working albeit with an occasional traceback when an error occurs. The traceback tells you which errors you can catch, but they are only worth catching if you can do something about them. (Which might include logging them or printing a more friendly message before exiting) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] try, except syntax
On Thu, Aug 02, 2018 at 12:19:41PM -0700, Marc Tompkins wrote: > What you want in that case is an assertion: > > try: > assert type(uvc)==float > except AssertionError as e: > print(e, msg) > > An assertion says "The following statement is True. If it isn't, I'm going > to throw an exception." They're especially useful when writing tests, and > should be part of your flow-control toolbox. Absolutely not! Sorry Marc, but that's *terrible* advice (sorry I don't have the delicacy to sugar coat that this morning, I've been railing against the misuse of assert for what sometimes seems like a thousand years...), it is a misuse of assert and buggy as well. https://import-that.dreamwidth.org/676.html -- Steve ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor