From cs at cskk.id.au Sun Aug 2 05:38:30 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 2 Aug 2020 19:38:30 +1000 Subject: [Tutor] Issue with Python module downloads from Library for a beginner Python coder. In-Reply-To: <1823668942.8336565.1596350188957@mail.yahoo.com> References: <1823668942.8336565.1596350188957@mail.yahoo.com> Message-ID: <20200802093830.GA5785@cskk.homeip.net> Diverting replies to tutor at python.org, a better place for all this. It looks like the error is in graphics.py, not in your file. Your line: from graphics import * is syntacticly correct. Something has mangled the line breaks in your traceback, which here appears as: When I write a different line -? (from import graphics *), this is the output: from graphics import *Traceback (most recent call last):? File "", line 1, in ? ? from graphics import *? File "C:\Users\sarvesh\AppData\Local\Programs\Python\Python38-32\graphics.py", line 1? ? Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32? ? ? ? ? ?^SyntaxError: invalid syntax To me it appears that the syntax error in in graphics.py at line 1. I'd normally expect such a traceback to look more like this: File "", line 1, in ? ? from graphics import * File "C:\Users\sarvesh\AppData\Local\Programs\Python\Python38-32\graphics.py", line 1 ? Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32 ? ?^SyntaxError: invalid syntax In particular, the "^" would point to the place in the code where Python _noticed_ the syntax error. Is it possible that graphics.py contains that "Python 3.8.5 ...." text? So the traceback I've invented above says that _your_ import failed, but that was because of a failure in the file you were trying to import. BTW, it looks to me like your Python programmes (graphics.py and whatever other file you might be making) are inside the Python install. Normally you'd keep these elsewhere, for example in a folder such as: C:\Users\sarvesh\my-programmes Cheers, Cameron Simpson On 02Aug2020 06:36, Sarvesh Poddar wrote: >I am currently using Python 3.8.5 with IDLE environment that comes >pre-installed with the Python application. I am using the book "An >Introduction to computer science" by John Zelle as my reference. >The problem I am facing is "There is a python program named "graphics.py" that is used as reference in the book and I downloaded the python file from internet?(link to the file -?https://mcsp.wartburg.edu/zelle/python/graphics.py). I have kept this module in (C:\Users\sarvesh\AppData\Local\Programs\Python\Python38-32) and this is were my Python files also lie in C drive. The problem is that I am not able to import graphics.py file and when I try to do that following is the error I receive, >Traceback (most recent call last): >? File "", line 1, in ? ? import graphics >? File "C:\Users\sarvesh\AppData\Local\Programs\Python\Python38-32\graphics.py", line 1 >? ? Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32? ? ? ? ? ?^SyntaxError: invalid syntax >?I have installed, uninstalled and then re-installed Python 3.8.5 multiple times but the problem remains. I did a thorough internet search and most of them suggested using sys path and following is the result, > >import sys>>> sys.path['', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\Lib\\idlelib', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages'] >When I write a different line -? (from import graphics *), this is the output: >from graphics import *Traceback (most recent call last):? File >"", line 1, in ? ? from graphics import *? File >"C:\Users\sarvesh\AppData\Local\Programs\Python\Python38-32\graphics.py", >line 1? ? Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) >[MSC v.1926 32 bit (Intel)] on win32? ? ? ? ? ?^SyntaxError: invalid >syntax From mats at wichmann.us Sun Aug 2 09:26:45 2020 From: mats at wichmann.us (Mats Wichmann) Date: Sun, 2 Aug 2020 07:26:45 -0600 Subject: [Tutor] Issue with Python module downloads from Library for a beginner Python coder. In-Reply-To: <20200802093830.GA5785@cskk.homeip.net> References: <1823668942.8336565.1596350188957@mail.yahoo.com> <20200802093830.GA5785@cskk.homeip.net> Message-ID: <1ec330e5-ee3b-93e3-5c91-3c0595578632@wichmann.us> On 8/2/20 3:38 AM, Cameron Simpson wrote: > Diverting replies to tutor at python.org, a better place for all this. > > It looks like the error is in graphics.py, not in your file. > Your line: > > from graphics import * > > is syntacticly correct. Something has mangled the line breaks in your > traceback, which here appears as: > > When I write a different line -? (from import graphics *), this is the output: > from graphics import *Traceback (most recent call last):? File > "", line 1, in ? ? from graphics import *? File > "C:\Users\sarvesh\AppData\Local\Programs\Python\Python38-32\graphics.py", > line 1? ? Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) > [MSC v.1926 32 bit (Intel)] on win32? ? ? ? ? ?^SyntaxError: invalid > syntax > > To me it appears that the syntax error in in graphics.py at line 1. I'd > normally expect such a traceback to look more like this: > > File "", line 1, in > ? ? from graphics import * > File "C:\Users\sarvesh\AppData\Local\Programs\Python\Python38-32\graphics.py", line 1 > ? Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32 > ? ?^SyntaxError: invalid syntax > > In particular, the "^" would point to the place in the code where Python > _noticed_ the syntax error. Is it possible that graphics.py contains > that "Python 3.8.5 ...." text? > > So the traceback I've invented above says that _your_ import failed, but > that was because of a failure in the file you were trying to import. > > BTW, it looks to me like your Python programmes (graphics.py and > whatever other file you might be making) are inside the Python install. > Normally you'd keep these elsewhere, for example in a folder such as: > > C:\Users\sarvesh\my-programmes > > Cheers, > Cameron Simpson > > On 02Aug2020 06:36, Sarvesh Poddar wrote: >> I am currently using Python 3.8.5 with IDLE environment that comes >> pre-installed with the Python application. I am using the book "An >> Introduction to computer science" by John Zelle as my reference. >> The problem I am facing is "There is a python program named "graphics.py" that is used as reference in the book and I downloaded the python file from internet?(link to the file -?https://mcsp.wartburg.edu/zelle/python/graphics.py). I have kept this module in (C:\Users\sarvesh\AppData\Local\Programs\Python\Python38-32) and this is were my Python files also lie in C drive. The problem is that I am not able to import graphics.py file and when I try to do that following is the error I receive, >> Traceback (most recent call last): >> ? File "", line 1, in ? ? import graphics >> ? File "C:\Users\sarvesh\AppData\Local\Programs\Python\Python38-32\graphics.py", line 1 >> ? ? Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32? ? ? ? ? ?^SyntaxError: invalid syntax >> ?I have installed, uninstalled and then re-installed Python 3.8.5 multiple times but the problem remains. I did a thorough internet search and most of them suggested using sys path and following is the result, It looks very much like the file your are importing is a literal save of an interactive session, not an actual Python source file, since from the error message, it seems to begin with the regular stanza that appears on Windows for when you start Python (or an IDLE shell, for that matter). >> >> import sys>>> sys.path['', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\Lib\\idlelib', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages'] >> When I write a different line -? (from import graphics *), this is the output: >>from graphics import *Traceback (most recent call last):? File >> "", line 1, in ? ? from graphics import *? File >> "C:\Users\sarvesh\AppData\Local\Programs\Python\Python38-32\graphics.py", >> line 1? ? Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) >> [MSC v.1926 32 bit (Intel)] on win32? ? ? ? ? ?^SyntaxError: invalid >> syntax From sarvesh.poddar at yahoo.com Sun Aug 2 02:36:28 2020 From: sarvesh.poddar at yahoo.com (Sarvesh Poddar) Date: Sun, 2 Aug 2020 06:36:28 +0000 (UTC) Subject: [Tutor] Issue with Python module downloads from Library for a beginner Python coder. References: <1823668942.8336565.1596350188957.ref@mail.yahoo.com> Message-ID: <1823668942.8336565.1596350188957@mail.yahoo.com> Hi, I am currently using Python 3.8.5 with IDLE environment that comes pre-installed with the Python application. I am using the book "An Introduction to computer science" by John Zelle as my reference. The problem I am facing is "There is a python program named "graphics.py" that is used as reference in the book and I downloaded the python file from internet?(link to the file -?https://mcsp.wartburg.edu/zelle/python/graphics.py). I have kept this module in (C:\Users\sarvesh\AppData\Local\Programs\Python\Python38-32) and this is were my Python files also lie in C drive. The problem is that I am not able to import graphics.py file and when I try to do that following is the error I receive, Traceback (most recent call last): ? File "", line 1, in ? ? import graphics ? File "C:\Users\sarvesh\AppData\Local\Programs\Python\Python38-32\graphics.py", line 1 ? ? Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32? ? ? ? ? ?^SyntaxError: invalid syntax ?I have installed, uninstalled and then re-installed Python 3.8.5 multiple times but the problem remains. I did a thorough internet search and most of them suggested using sys path and following is the result, import sys>>> sys.path['', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\Lib\\idlelib', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages'] When I write a different line -? (from import graphics *), this is the output: from graphics import *Traceback (most recent call last):? File "", line 1, in ? ? from graphics import *? File "C:\Users\sarvesh\AppData\Local\Programs\Python\Python38-32\graphics.py", line 1? ? Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32? ? ? ? ? ?^SyntaxError: invalid syntax Please do let me know if I am missing out something very basic. Thanks and I look forward. On Saturday, 1 August, 2020, 07:54:19 am IST, boB Stepp wrote: On Thu, Jul 30, 2020 at 9:24 AM Sarvesh Poddar via Python-list wrote: > I re-installed Python in my Windows system as the earlier one was not able to import modules... You do not provide much detail to diagnose what your problem(s) is(are).? By the "earlier one" is it the same version as the one you re-installed?? Were you able to run IDLE with the "earlier one"?? By not being able to import modules do you mean modules from Python's standard library?? Or do you mean installing third party libraries using pip? > ...But now I am not able to open IDLE after multiple tries. Have you looked in your start menu in the list of installed programs for Python?? If it is there did you expand it and see if there is an entry for IDLE?? How have you been trying (unsuccessfully) to open IDLE? -- boB From bob at mellowood.ca Sun Aug 2 12:59:47 2020 From: bob at mellowood.ca (Bob van der Poel) Date: Sun, 2 Aug 2020 09:59:47 -0700 Subject: [Tutor] Issue with Python module downloads from Library for a beginner Python coder. In-Reply-To: <1823668942.8336565.1596350188957@mail.yahoo.com> References: <1823668942.8336565.1596350188957.ref@mail.yahoo.com> <1823668942.8336565.1596350188957@mail.yahoo.com> Message-ID: Do you have tkinter installed? The graphics.py module needs it to run. On Sat, Aug 1, 2020 at 11:36 PM Sarvesh Poddar via Python-list < python-list at python.org> wrote: > Hi, > I am currently using Python 3.8.5 with IDLE environment that comes > pre-installed with the Python application. I am using the book "An > Introduction to computer science" by John Zelle as my reference. > The problem I am facing is "There is a python program named "graphics.py" > that is used as reference in the book and I downloaded the python file from > internet (link to the file - > https://mcsp.wartburg.edu/zelle/python/graphics.py). I have kept this > module in (C:\Users\sarvesh\AppData\Local\Programs\Python\Python38-32) and > this is were my Python files also lie in C drive. The problem is that I am > not able to import graphics.py file and when I try to do that following is > the error I receive, > Traceback (most recent call last): > File "", line 1, in import graphics > File > "C:\Users\sarvesh\AppData\Local\Programs\Python\Python38-32\graphics.py", > line 1 > Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 > 32 bit (Intel)] on win32 ^SyntaxError: invalid syntax > I have installed, uninstalled and then re-installed Python 3.8.5 multiple > times but the problem remains. I did a thorough internet search and most of > them suggested using sys path and following is the result, > > import sys>>> sys.path['', > 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\Lib\\idlelib', > 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', > 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', > 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', > 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32', > 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages'] > When I write a different line - (from import graphics *), this is the > output: > from graphics import *Traceback (most recent call last): File > "", line 1, in from graphics import * File > "C:\Users\sarvesh\AppData\Local\Programs\Python\Python38-32\graphics.py", > line 1 Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC > v.1926 32 bit (Intel)] on win32 ^SyntaxError: invalid syntax > Please do let me know if I am missing out something very basic. > Thanks and I look forward. On Saturday, 1 August, 2020, 07:54:19 am > IST, boB Stepp wrote: > > On Thu, Jul 30, 2020 at 9:24 AM Sarvesh Poddar via Python-list > wrote: > > > I re-installed Python in my Windows system as the earlier one was not > able to import modules... > > You do not provide much detail to diagnose what your problem(s) > is(are). By the "earlier one" is it the same version as the one you > re-installed? Were you able to run IDLE with the "earlier one"? By > not being able to import modules do you mean modules from Python's > standard library? Or do you mean installing third party libraries > using pip? > > > ...But now I am not able to open IDLE after multiple tries. > > Have you looked in your start menu in the list of installed programs > for Python? If it is there did you expand it and see if there is an > entry for IDLE? How have you been trying (unsuccessfully) to open > IDLE? > > > -- > boB > > -- > https://mail.python.org/mailman/listinfo/python-list > -- **** Listen to my FREE CD at http://www.mellowood.ca/music/cedars **** Bob van der Poel ** Wynndel, British Columbia, CANADA ** EMAIL: bob at mellowood.ca WWW: http://www.mellowood.ca From sarvesh.poddar at yahoo.com Mon Aug 3 00:33:00 2020 From: sarvesh.poddar at yahoo.com (Sarvesh Poddar) Date: Mon, 3 Aug 2020 04:33:00 +0000 (UTC) Subject: [Tutor] Issue with Python module downloads from Library for a beginner Python coder. In-Reply-To: References: <1823668942.8336565.1596350188957.ref@mail.yahoo.com> <1823668942.8336565.1596350188957@mail.yahoo.com> Message-ID: <986131814.8505917.1596429180308@mail.yahoo.com> Hi Bob, Yes I have Tkinter and it came with the Python package with installation. I have copied the module content here, just for understanding. I installed the module in Tkinter folder to check again although it still states that module name does not exist. Can anyone please give a brief on how to change the path were Python makes the search. I think the problem is Python is not able to find the path for the module. # graphics.py"""Simple object oriented graphics library The library is designed to make it very easy for novice programmers toexperiment with computer graphics in an object oriented fashion. It iswritten by John Zelle for use with the book "Python Programming: AnIntroduction to Computer Science" (Franklin, Beedle & Associates). LICENSE: This is open-source software released under the terms of theGPL (http://www.gnu.org/licenses/gpl.html). PLATFORMS: The package is a wrapper around Tkinter and should run onany platform where Tkinter is available. INSTALLATION: Put this file somewhere where Python can see it. OVERVIEW: There are two kinds of objects in the library. The GraphWinclass implements a window where drawing can be done and variousGraphicsObjects are provided that can be drawn into a GraphWin. As asimple example, here is a complete program to draw a circle of radius10 centered in a 100x100 window: --------------------------------------------------------------------from graphics import * def main():? ? win = GraphWin("My Circle", 100, 100)? ? c = Circle(Point(50,50), 10)? ? c.draw(win)? ? win.getMouse() # Pause to view result? ? win.close()? ? # Close window when done main()--------------------------------------------------------------------GraphWin objects support coordinate transformation through thesetCoords method and pointer-based input through getMouse. The library provides the following graphical objects:? ? Point? ? Line? ? Circle? ? Oval? ? Rectangle? ? Polygon? ? Text? ? Entry (for text-based input)? ? Image Various attributes of graphical objects can be set such asoutline-color, fill-color and line-width. Graphical objects alsosupport moving and hiding for animation effects. The library also provides a very simple class for pixel-based imagemanipulation, Pixmap. A pixmap can be loaded from a file and displayedusing an Image object. Both getPixel and setPixel methods are providedfor manipulating the image. DOCUMENTATION: For complete documentation, see Chapter 4 of "PythonProgramming: An Introduction to Computer Science" by John Zelle,published by Franklin, Beedle & Associates.? Also seehttp://mcsp.wartburg.edu/zelle/python for a quick reference"""# Version 3.3.1.rhit 1/19/2008:?#? ? ?Added support to poll for keypresses (changes tagged with "MB")#? ? ?Matt Boutell, Rose-Hulman Institute of Technology.?# Version 3.3.rhit 11/21/07#? ? ?Added __repr__ methods to most leaf classes.? Thanks to?#? ? ? ? ?Amanda Stephan, Rose-Hulman Institute of Technology.# Version 4.0.1 10/08/2009#? ? ?* Modified the autoflush on GraphWin to default to True#? ? ?* Autoflush check on close, setBackground#? ? ?* Fixed getMouse to flush pending clicks at entry# Version 4.0 08/2009#? ? ?* Reverted to non-threaded version. The advantages (robustness,#? ? ? ? ?efficiency, ability to use with other Tk code, etc.) outweigh#? ? ? ? ?the disadvantage that interactive use with IDLE is slightly more#? ? ? ? ?cumbersome.#? ? ?* Modified to run in either Python 2.x or 3.x (same file).#? ? ?* Added Image.getPixmap()#? ? ?* Added update() -- stand alone function to cause any pending#? ? ? ? ? ?graphics changes to display.## Version 3.4 10/16/07#? ? ?Fixed GraphicsError to avoid "exploded" error messages.# Version 3.3 8/8/06#? ? ?Added checkMouse method to GraphWin# Version 3.2.3#? ? ?Fixed error in Polygon init spotted by Andrew Harrington#? ? ?Fixed improper threading in Image constructor# Version 3.2.2 5/30/05#? ? ?Cleaned up handling of exceptions in Tk thread. The graphics package#? ? ?now raises an exception if attempt is made to communicate with#? ? ?a dead Tk thread.# Version 3.2.1 5/22/05#? ? ?Added shutdown function for tk thread to eliminate race-condition#? ? ? ? error "chatter" when main thread terminates#? ? ?Renamed various private globals with _# Version 3.2 5/4/05#? ? ?Added Pixmap object for simple image manipulation.# Version 3.1 4/13/05#? ? ?Improved the Tk thread communication so that most Tk calls#? ? ? ? do not have to wait for synchonization with the Tk thread.#? ? ? ? (see _tkCall and _tkExec)# Version 3.0 12/30/04#? ? ?Implemented Tk event loop in separate thread. Should now work#? ? ? ? interactively with IDLE. Undocumented autoflush feature is#? ? ? ? no longer necessary. Its default is now False (off). It may#? ? ? ? be removed in a future version.#? ? ?Better handling of errors regarding operations on windows that#? ? ? ?have been closed.#? ? ?Addition of an isClosed method to GraphWindow class. # Version 2.2 8/26/04#? ? ?Fixed cloning bug reported by Joseph Oldham.#? ? ?Now implements deep copy of config info.# Version 2.1 1/15/04#? ? ?Added autoflush option to GraphWin. When True (default) updates on#? ? ? ? the window are done after each action. This makes some graphics#? ? ? ? intensive programs sluggish. Turning off autoflush causes updates#? ? ? ? to happen during idle periods or when flush is called.# Version 2.0#? ? ?Updated Documentation#? ? ?Made Polygon accept a list of Points in constructor#? ? ?Made all drawing functions call TK update for easier animations#? ? ? ? ? and to make the overall package work better with#? ? ? ? ? Python 2.3 and IDLE 1.0 under Windows (still some issues).#? ? ?Removed vestigial turtle graphics.#? ? ?Added ability to configure font for Entry objects (analogous to Text)#? ? ?Added setTextColor for Text as an alias of setFill#? ? ?Changed to class-style exceptions#? ? ?Fixed cloning of Text objects # Version 1.6#? ? ?Fixed Entry so StringVar uses _root as master, solves weird#? ? ? ? ? ? interaction with shell in Idle#? ? ?Fixed bug in setCoords. X and Y coordinates can increase in#? ? ? ? ? ?"non-intuitive" direction.#? ? ?Tweaked wm_protocol so window is not resizable and kill box closes. # Version 1.5#? ? ?Fixed bug in Entry. Can now define entry before creating a#? ? ?GraphWin. All GraphWins are now toplevel windows and share#? ? ?a fixed root (called _root). # Version 1.4#? ? ?Fixed Garbage collection of Tkinter images bug.#? ? ?Added ability to set text atttributes.#? ? ?Added Entry boxes. import time, os, sys try:? # import as appropriate for 2.x vs. 3.x? ?import tkinter as tkexcept:? ?import Tkinter as tk ########################################################################### Module Exceptions class GraphicsError(Exception):? ? """Generic error class for graphics module exceptions."""? ? def __init__(self, args=None):? ? ? ? self.args=args OBJ_ALREADY_DRAWN = "Object currently drawn"UNSUPPORTED_METHOD = "Object doesn't support operation"BAD_OPTION = "Illegal option value"DEAD_THREAD = "Graphics thread quit unexpectedly" _root = tk.Tk()_root.withdraw() def update():? ? _root.update() ############################################################################# Graphics classes start here? ? ? ??class GraphWin(tk.Canvas): ? ? """A GraphWin is a toplevel window for displaying graphics.""" ? ? def __init__(self, title="Graphics Window",? ? ? ? ? ? ? ? ?width=200, height=200, autoflush=True):? ? ? ? master = tk.Toplevel(_root)? ? ? ? master.protocol("WM_DELETE_WINDOW", self.close)? ? ? ? tk.Canvas.__init__(self, master, width=width, height=height)? ? ? ? self.master.title(title)? ? ? ? self.title = title? ? ? ? self.pack()? ? ? ? master.resizable(0,0)? ? ? ? self.foreground = "black"? ? ? ? self.items = []? ? ? ? self.mouseX = None? ? ? ? self.mouseY = None? ? ? ? self.key = None? ? ? ? ? ? ? ? ? ? ?#MB: added? ? ? ? self.bind("", self._onClick)? ? ? ? master.bind("", self._onKeyPress) #MB: added? ? ? ? self.height = height? ? ? ? self.width = width? ? ? ? self.autoflush = autoflush? ? ? ? self._mouseCallback = None? ? ? ? self._keyCallback = None #MB: added? ? ? ? self.trans = None? ? ? ? self.closed = False? ? ? ? if autoflush: _root.update() ? ? def __repr__(self):? ? ? ? return "GraphWin("+ '"' + self.title + '"' + "," + str(self.getWidth()) + "," + str(self.getHeight()) +","+ str(self.autoflush) + ")" ? ? # Including str explicitly overrides tk.Canvas's str method? ? def __str__(self):? ? ? ? return self.__repr__() ? ? def __checkOpen(self):? ? ? ? if self.closed:? ? ? ? ? ? raise GraphicsError("window is closed") ? ? def setBackground(self, color):? ? ? ? """Set background color of the window"""? ? ? ? self.__checkOpen()? ? ? ? self.config(bg=color)? ? ? ? self.__autoflush()? ? ? ??? ? def setCoords(self, x1, y1, x2, y2):? ? ? ? """Set coordinates of window to run from (x1,y1) in the? ? ? ? lower-left corner to (x2,y2) in the upper-right corner."""? ? ? ? self.trans = Transform(self.width, self.height, x1, y1, x2, y2) ? ? def close(self):? ? ? ? """Close the window""" ? ? ? ? if self.closed: return? ? ? ? self.closed = True? ? ? ? self.master.destroy()? ? ? ? self.__autoflush() ? ? def isClosed(self):? ? ? ? return self.closed ? ? def __autoflush(self):? ? ? ? if self.autoflush:? ? ? ? ? ? _root.update() ? ??? ? def plot(self, x, y, color="black"):? ? ? ? """Set pixel (x,y) to the given color"""? ? ? ? self.__checkOpen()? ? ? ? xs,ys = self.toScreen(x,y)? ? ? ? self.create_line(xs,ys,xs+1,ys, fill=color)? ? ? ? self.__autoflush()? ? ? ??? ? def plotPixel(self, x, y, color="black"):? ? ? ? """Set pixel raw (independent of window coordinates) pixel? ? ? ? (x,y) to color"""? ? ? ? self.__checkOpen()? ? ? ? self.create_line(x,y,x+1,y, fill=color)? ? ? ? self.__autoflush()? ? ? ? def flush(self):? ? ? ? """Update drawing to the window"""? ? ? ? self.__checkOpen()? ? ? ? self.update_idletasks() ? ? ? ??? ? def getMouse(self):? ? ? ? """Wait for mouse click and return Point object representing? ? ? ? the click"""? ? ? ? self.update()? ? ? # flush any prior clicks? ? ? ? self.mouseX = None? ? ? ? self.mouseY = None? ? ? ? while self.mouseX == None or self.mouseY == None:? ? ? ? ? ? self.update()? ? ? ? ? ? if self.isClosed(): raise GraphicsError("getMouse in closed window")? ? ? ? ? ? time.sleep(.1) # give up thread? ? ? ? x,y = self.toWorld(self.mouseX, self.mouseY)? ? ? ? self.mouseX = None? ? ? ? self.mouseY = None? ? ? ? return Point(x,y) ? ? def checkMouse(self):? ? ? ? """Return mouse click last mouse click or None if mouse has? ? ? ? not been clicked since last call"""? ? ? ? if self.isClosed():? ? ? ? ? ? raise GraphicsError("checkMouse in closed window")? ? ? ? self.update()? ? ? ? if self.mouseX != None and self.mouseY != None:? ? ? ? ? ? x,y = self.toWorld(self.mouseX, self.mouseY)? ? ? ? ? ? self.mouseX = None? ? ? ? ? ? self.mouseY = None? ? ? ? ? ? return Point(x,y)? ? ? ? else:? ? ? ? ? ? return None # MB: added? ? ? ? ? ??? ? def checkKey(self):? ? ? ? """Return key or None if no key has? ? ? ? been pressed since last call"""? ? ? ? if self.isClosed():? ? ? ? ? ? raise GraphicsError("checkKey in closed window")? ? ? ? self.update()? ? ? ? if self.key != None:? ? ? ? ? ? keyToReturn = self.key? ? ? ? ? ? self.key = None? ? ? ? ? ? return keyToReturn? ? ? ? else:? ? ? ? ? ? return None# MB: end? ? ? ? ? ??? ? def getHeight(self):? ? ? ? """Return the height of the window"""? ? ? ? return self.height? ? ? ??? ? def getWidth(self):? ? ? ? """Return the width of the window"""? ? ? ? return self.width? ??? ? def toScreen(self, x, y):? ? ? ? trans = self.trans? ? ? ? if trans:? ? ? ? ? ? return self.trans.screen(x,y)? ? ? ? else:? ? ? ? ? ? return x,y? ? ? ? ? ? ? ? ? ? ??? ? def toWorld(self, x, y):? ? ? ? trans = self.trans? ? ? ? if trans:? ? ? ? ? ? return self.trans.world(x,y)? ? ? ? else:? ? ? ? ? ? return x,y? ? ? ??? ? def setMouseHandler(self, func):? ? ? ? self._mouseCallback = func? ? ? ??? ? def _onClick(self, e):? ? ? ? self.mouseX = e.x? ? ? ? self.mouseY = e.y? ? ? ? if self._mouseCallback:? ? ? ? ? ? self._mouseCallback(Point(e.x, e.y))? ? ? #MB: added? ? def _onKeyPress(self, e):? ? ? ? self.key = e.keysym? ? #MB: end? class Transform: ? ? """Internal class for 2-D coordinate transformations"""? ??? ? def __init__(self, w, h, xlow, ylow, xhigh, yhigh):? ? ? ? # w, h are width and height of window? ? ? ? # (xlow,ylow) coordinates of lower-left [raw (0,h-1)]? ? ? ? # (xhigh,yhigh) coordinates of upper-right [raw (w-1,0)]? ? ? ? # xspan and yspan have now been stored to allow for repr calculations? ? ? ? self.xspan = (xhigh-xlow)? ? ? ? self.yspan = (yhigh-ylow)? ? ? ? self.xbase = xlow? ? ? ? self.ybase = yhigh? ? ? ? self.xscale = self.xspan/float(w-1)? ? ? ? self.yscale = self.yspan/float(h-1)? ? ? ??? ? def screen(self,x,y):? ? ? ? # Returns x,y in screen (actually window) coordinates? ? ? ? xs = (x-self.xbase) / self.xscale? ? ? ? ys = (self.ybase-y) / self.yscale? ? ? ? return int(xs+0.5),int(ys+0.5)? ? ? ??? ? def world(self,xs,ys):? ? ? ? # Returns xs,ys in world coordinates? ? ? ? x = xs*self.xscale + self.xbase? ? ? ? y = self.ybase - ys*self.yscale? ? ? ? return x,y ? ? def __repr__(self):? ? ? ? w = (self.xscale+self.xspan)/self.xscale? ? ? ? h = (self.yscale+self.yspan)/self.yscale? ? ? ? ylow = self.ybase - self.yspan? ? ? ? xhigh = self.xspan + self.xbase? ? ? ? return "Transform("+ str(w) + "," + str(h) + "," + str(self.xbase) + "," + str(ylow) + "," + str(xhigh) + "," + str(self.ybase) + ")" # Default values for various item configuration options. Only a subset of#? ?keys may be present in the configuration dictionary for a given itemDEFAULT_CONFIG = {"fill":"", ? "outline":"black", ? "width":"1", ? "arrow":"none", ? "text":"", ? "justify":"center",? ? ? ? ? ? ? ? ? "font": ("helvetica", 12, "normal")} class GraphicsObject: ? ? """Generic base class for all of the drawable objects"""? ? # A subclass of GraphicsObject should override _draw and? ? #? ?and _move methods.? ??? ? def __init__(self, options):? ? ? ? # options is a list of strings indicating which options are? ? ? ? # legal for this object.? ? ? ??? ? ? ? # When an object is drawn, canvas is set to the GraphWin(canvas)? ? ? ? #? ? object where it is drawn and id is the TK identifier of the? ? ? ? #? ? drawn shape.? ? ? ? self.canvas = None? ? ? ? self.id = None ? ? ? ? # config is the dictionary of configuration options for the widget.? ? ? ? config = {}? ? ? ? for option in options:? ? ? ? ? ? config[option] = DEFAULT_CONFIG[option]? ? ? ? self.config = config? ? ? ??? ? def setFill(self, color):? ? ? ? """Set interior color to color"""? ? ? ? self._reconfig("fill", color)? ? ? ??? ? def setOutline(self, color):? ? ? ? """Set outline color to color"""? ? ? ? self._reconfig("outline", color)? ? ? ??? ? def setWidth(self, width):? ? ? ? """Set line weight to width"""? ? ? ? self._reconfig("width", width) ? ? def draw(self, graphwin): ? ? ? ? """Draw the object in graphwin, which should be a GraphWin? ? ? ? object.? A GraphicsObject may only be drawn into one? ? ? ? window. Raises an error if attempt made to draw an object that? ? ? ? is already visible.""" ? ? ? ? if self.canvas and not self.canvas.isClosed(): raise GraphicsError(OBJ_ALREADY_DRAWN)? ? ? ? if graphwin.isClosed(): raise GraphicsError("Can't draw to closed window")? ? ? ? self.canvas = graphwin? ? ? ? self.id = self._draw(graphwin, self.config)? ? ? ? if graphwin.autoflush:? ? ? ? ? ? _root.update() ? ? def undraw(self): ? ? ? ? """Undraw the object (i.e. hide it). Returns silently if the? ? ? ? object is not currently drawn."""? ? ? ??? ? ? ? if not self.canvas: return? ? ? ? if not self.canvas.isClosed():? ? ? ? ? ? self.canvas.delete(self.id)? ? ? ? ? ? if self.canvas.autoflush:? ? ? ? ? ? ? ? _root.update()? ? ? ? self.canvas = None? ? ? ? self.id = None ? ? def move(self, dx, dy): ? ? ? ? """move object dx units in x direction and dy units in y? ? ? ? direction"""? ? ? ??? ? ? ? self._move(dx,dy)? ? ? ? canvas = self.canvas? ? ? ? if canvas and not canvas.isClosed():? ? ? ? ? ? trans = canvas.trans? ? ? ? ? ? if trans:? ? ? ? ? ? ? ? x = dx/ trans.xscale?? ? ? ? ? ? ? ? y = -dy / trans.yscale? ? ? ? ? ? else:? ? ? ? ? ? ? ? x = dx? ? ? ? ? ? ? ? y = dy? ? ? ? ? ? self.canvas.move(self.id, x, y)? ? ? ? ? ? if canvas.autoflush:? ? ? ? ? ? ? ? _root.update()? ? ? ? ? ?? ? def _reconfig(self, option, setting):? ? ? ? # Internal method for changing configuration of the object? ? ? ? # Raises an error if the option does not exist in the config? ? ? ? #? ? dictionary for this object? ? ? ? if option not in self.config:? ? ? ? ? ? raise GraphicsError(UNSUPPORTED_METHOD)? ? ? ? options = self.config? ? ? ? options[option] = setting? ? ? ? if self.canvas and not self.canvas.isClosed():? ? ? ? ? ? self.canvas.itemconfig(self.id, options)? ? ? ? ? ? if self.canvas.autoflush:? ? ? ? ? ? ? ? _root.update() ? ? def _draw(self, canvas, options):? ? ? ? """draws appropriate figure on canvas with options provided? ? ? ? Returns Tk id of item drawn"""? ? ? ? pass # must override in subclass ? ? def _move(self, dx, dy):? ? ? ? """updates internal state of object to move it dx,dy units"""? ? ? ? pass # must override in subclass? ??? ? def __repr__(self):? ? ? ? return "GraphicsObject(" + str(self.config) + ")"? ? ? ? ?class Point(GraphicsObject):? ? def __init__(self, x, y):? ? ? ? GraphicsObject.__init__(self, ["outline", "fill"])? ? ? ? self.setFill = self.setOutline? ? ? ? self.x = x? ? ? ? self.y = y? ? ? ??? ? def _draw(self, canvas, options):? ? ? ? x,y = canvas.toScreen(self.x,self.y)? ? ? ? return canvas.create_rectangle(x,y,x+1,y+1,options)? ? ? ??? ? def _move(self, dx, dy):? ? ? ? self.x = self.x + dx? ? ? ? self.y = self.y + dy? ? ? ??? ? def clone(self):? ? ? ? other = Point(self.x,self.y)? ? ? ? other.config = self.config.copy()? ? ? ? return other? ??? ? def __repr__(self):? ? ? ? return "Point(" + str(self.x) + "," + str(self.y) + ")"? ??? ? def getX(self): return self.x? ? def getY(self): return self.y class _BBox(GraphicsObject):? ? # Internal base class for objects represented by bounding box? ? # (opposite corners) Line segment is a degenerate case.? ??? ? def __init__(self, p1, p2, options=["outline","width","fill"]):? ? ? ? GraphicsObject.__init__(self, options)? ? ? ? self.p1 = p1.clone()? ? ? ? self.p2 = p2.clone() ? ? def _move(self, dx, dy):? ? ? ? self.p1.x = self.p1.x + dx? ? ? ? self.p1.y = self.p1.y + dy? ? ? ? self.p2.x = self.p2.x + dx? ? ? ? self.p2.y = self.p2.y? + dy? ? ? ? ? ? ? ??? ? def getP1(self): return self.p1.clone() ? ? def getP2(self): return self.p2.clone()? ??? ? def getCenter(self):? ? ? ? p1 = self.p1? ? ? ? p2 = self.p2? ? ? ? return Point((p1.x+p2.x)/2.0, (p1.y+p2.y)/2.0)? ??? ? def __repr__(self):? ? ? ? p1 = self.p1? ? ? ? p2 = self.p2? ? ? ? return repr(p1)+","+repr(p2)? ??class Rectangle(_BBox):? ??? ? def __init__(self, p1, p2):? ? ? ? _BBox.__init__(self, p1, p2)? ??? ? def _draw(self, canvas, options):? ? ? ? p1 = self.p1? ? ? ? p2 = self.p2? ? ? ? x1,y1 = canvas.toScreen(p1.x,p1.y)? ? ? ? x2,y2 = canvas.toScreen(p2.x,p2.y)? ? ? ? return canvas.create_rectangle(x1,y1,x2,y2,options)? ? ? ??? ? def clone(self):? ? ? ? other = Rectangle(self.p1, self.p2)? ? ? ? other.config = self.config.copy()? ? ? ? return other? ??? ? def __repr__(self):? ? ? ? return "Rectangle("+repr(self.p1)+","+repr(self.p2)+")"? ? ? ??class Oval(_BBox):? ??? ? def __init__(self, p1, p2):? ? ? ? _BBox.__init__(self, p1, p2)? ? ? ??? ? def clone(self):? ? ? ? other = Oval(self.p1, self.p2)? ? ? ? other.config = self.config.copy()? ? ? ? return other? ?? ? def _draw(self, canvas, options):? ? ? ? p1 = self.p1? ? ? ? p2 = self.p2? ? ? ? x1,y1 = canvas.toScreen(p1.x,p1.y)? ? ? ? x2,y2 = canvas.toScreen(p2.x,p2.y)? ? ? ? return canvas.create_oval(x1,y1,x2,y2,options)? ??? ? def __repr__(self):? ? ? ? return "Oval("+repr(self.p1)+","+repr(self.p2)+")"? ??class Circle(Oval):? ??? ? def __init__(self, center, radius):? ? ? ? p1 = Point(center.x-radius, center.y-radius)? ? ? ? p2 = Point(center.x+radius, center.y+radius)? ? ? ? Oval.__init__(self, p1, p2)? ? ? ? self.radius = radius? ? ? ??? ? def clone(self):? ? ? ? other = Circle(self.getCenter(), self.radius)? ? ? ? other.config = self.config.copy()? ? ? ? return other? ? ? ??? ? def getRadius(self):? ? ? ? return self.radius? ??? ? def __repr__(self):? ? ? ? center = Point(self.p1.x+self.radius,self.p1.y+self.radius)? ? ? ? return "Circle(" + repr(center) + ","+str(self.radius)+")"? ? ? ? ? ? ??class Line(_BBox):? ??? ? def __init__(self, p1, p2):? ? ? ? _BBox.__init__(self, p1, p2, ["arrow","fill","width"])? ? ? ? self.setFill(DEFAULT_CONFIG['outline'])? ? ? ? self.setOutline = self.setFill? ?? ? def clone(self):? ? ? ? other = Line(self.p1, self.p2)? ? ? ? other.config = self.config.copy()? ? ? ? return other ? ? def _draw(self, canvas, options):? ? ? ? p1 = self.p1? ? ? ? p2 = self.p2? ? ? ? x1,y1 = canvas.toScreen(p1.x,p1.y)? ? ? ? x2,y2 = canvas.toScreen(p2.x,p2.y)? ? ? ? return canvas.create_line(x1,y1,x2,y2,options)? ? ? ??? ? def setArrow(self, option):? ? ? ? if not option in ["first","last","both","none"]:? ? ? ? ? ? raise GraphicsError(BAD_OPTION)? ? ? ? self._reconfig("arrow", option)? ? ? ??? ? def __repr__(self):? ? ? ? return "Line("+repr(self.p1)+","+repr(self.p2)+")" class Polygon(GraphicsObject):? ??? ? def __init__(self, *points):? ? ? ? # if points passed as a list, extract it? ? ? ? if len(points) == 1 and type(points[0] == type([])):? ? ? ? ? ? points = points[0]? ? ? ? self.points = list(map(Point.clone, points))? ? ? ? GraphicsObject.__init__(self, ["outline", "width", "fill"])? ? ? ??? ? def clone(self):? ? ? ? other = Polygon(*self.points)? ? ? ? other.config = self.config.copy()? ? ? ? return other ? ? def getPoints(self):? ? ? ? return list(map(Point.clone, self.points)) ? ? def _move(self, dx, dy):? ? ? ? for p in self.points:? ? ? ? ? ? p.move(dx,dy)? ?? ? def _draw(self, canvas, options):? ? ? ? args = [canvas]? ? ? ? for p in self.points:? ? ? ? ? ? x,y = canvas.toScreen(p.x,p.y)? ? ? ? ? ? args.append(x)? ? ? ? ? ? args.append(y)? ? ? ? args.append(options)? ? ? ? return GraphWin.create_polygon(*args)?? ??? ? def __repr__(self):? ? ? ? points = self.points? ? ? ? s = "Polygon("+repr(points[0])? ? ? ? for i,p in enumerate(points):? ? ? ? ? ? if (i==0):? ? ? ? ? ? ? ? i=1? ? ? ? ? ? ? ? continue? ? ? ? ? ? s = s + ","+repr(p)? ? ? ? return s + ")" class Text(GraphicsObject):? ??? ?def __init__(self, p, text):? ? ? GraphicsObject.__init__(self, ["justify","fill","text","font"])? ? ? self.setText(text)? ? ? self.anchor = p.clone()? ? ? self.setFill(DEFAULT_CONFIG['outline'])? ? ? self.setOutline = self.setFill? ? ? ?def __repr__(self):? ? ? return "Text(" + repr(self.anchor) + "," + "\"" + self.getText() + "\")" ? ?def _draw(self, canvas, options):? ? ? p = self.anchor? ? ? x,y = canvas.toScreen(p.x,p.y)? ? ? return canvas.create_text(x,y,options)? ? ? ?def _move(self, dx, dy):? ? ? self.anchor.move(dx,dy)? ? ? ?def clone(self):? ? ? other = Text(self.anchor, self.config['text'])? ? ? other.config = self.config.copy()? ? ? return other ? ?def setText(self,text):? ? ? self._reconfig("text", text)? ? ? ?def getText(self):? ? ? return self.config["text"]? ? ? ? ? ?def getAnchor(self):? ? ? return self.anchor.clone() ? ?def setFace(self, face):? ? ? if face in ['helvetica','arial','courier','times roman']:? ? ? ? ?f,s,b = self.config['font']? ? ? ? ?self._reconfig("font",(face,s,b))? ? ? else:? ? ? ? ?raise GraphicsError(BAD_OPTION) ? ?def setSize(self, size):? ? ? if 5 <= size <= 36:? ? ? ? ?f,s,b = self.config['font']? ? ? ? ?self._reconfig("font", (f,size,b))? ? ? else:? ? ? ? ?raise GraphicsError(BAD_OPTION) ? ?def setStyle(self, style):? ? ? if style in ['bold','normal','italic', 'bold italic']:? ? ? ? ?f,s,b = self.config['font']? ? ? ? ?self._reconfig("font", (f,s,style))? ? ? else:? ? ? ? ?raise GraphicsError(BAD_OPTION) ? ?def setTextColor(self, color):? ? ? self.setFill(color) class Entry(GraphicsObject): ? ? def __init__(self, p, width):? ? ? ? GraphicsObject.__init__(self, [])? ? ? ? self.anchor = p.clone()? ? ? ? #print self.anchor? ? ? ? self.width = width? ? ? ? self.text = tk.StringVar(_root)? ? ? ? self.text.set("")? ? ? ? self.fill = "gray"? ? ? ? self.color = "black"? ? ? ? self.font = DEFAULT_CONFIG['font']? ? ? ? self.entry = None ? ? def __repr__(self):? ? ? ? return "Entry(" + repr(self.anchor) + "," + str(self.width) + ")" ? ? def _draw(self, canvas, options):? ? ? ? p = self.anchor? ? ? ? x,y = canvas.toScreen(p.x,p.y)? ? ? ? frm = tk.Frame(canvas.master)? ? ? ? self.entry = tk.Entry(frm,? ? ? ? ? ? ? ? ? ? ? ? ? ? ? width=self.width,? ? ? ? ? ? ? ? ? ? ? ? ? ? ? textvariable=self.text,? ? ? ? ? ? ? ? ? ? ? ? ? ? ? bg = self.fill,? ? ? ? ? ? ? ? ? ? ? ? ? ? ? fg = self.color,? ? ? ? ? ? ? ? ? ? ? ? ? ? ? font=self.font)? ? ? ? self.entry.pack()? ? ? ? #self.setFill(self.fill)? ? ? ? return canvas.create_window(x,y,window=frm) ? ? def getText(self):? ? ? ? return self.text.get() ? ? def _move(self, dx, dy):? ? ? ? self.anchor.move(dx,dy) ? ? def getAnchor(self):? ? ? ? return self.anchor.clone() ? ? def clone(self):? ? ? ? other = Entry(self.anchor, self.width)? ? ? ? other.config = self.config.copy()? ? ? ? other.text = tk.StringVar()? ? ? ? other.text.set(self.text.get())? ? ? ? other.fill = self.fill? ? ? ? return other ? ? def setText(self, t):? ? ? ? self.text.set(t) ? ? ? ? ? ??? ? def setFill(self, color):? ? ? ? self.fill = color? ? ? ? if self.entry:? ? ? ? ? ? self.entry.config(bg=color) ? ? def _setFontComponent(self, which, value):? ? ? ? font = list(self.font)? ? ? ? font[which] = value? ? ? ? self.font = tuple(font)? ? ? ? if self.entry:? ? ? ? ? ? self.entry.config(font=self.font) ? ? def setFace(self, face):? ? ? ? if face in ['helvetica','arial','courier','times roman']:? ? ? ? ? ? self._setFontComponent(0, face)? ? ? ? else:? ? ? ? ? ? raise GraphicsError(BAD_OPTION) ? ? def setSize(self, size):? ? ? ? if 5 <= size <= 36:? ? ? ? ? ? self._setFontComponent(1,size)? ? ? ? else:? ? ? ? ? ? raise GraphicsError(BAD_OPTION) ? ? def setStyle(self, style):? ? ? ? if style in ['bold','normal','italic', 'bold italic']:? ? ? ? ? ? self._setFontComponent(2,style)? ? ? ? else:? ? ? ? ? ? raise GraphicsError(BAD_OPTION) ? ? def setTextColor(self, color):? ? ? ? self.color=color? ? ? ? if self.entry:? ? ? ? ? ? self.entry.config(fg=color) class Image(GraphicsObject): ? ? idCount = 0? ? imageCache = {} # tk photoimages go here to avoid GC while drawn?? ??? ? def __init__(self, p, pixmap):? ? ? ? GraphicsObject.__init__(self, [])? ? ? ? self.anchor = p.clone()? ? ? ? self.imageId = Image.idCount? ? ? ? Image.idCount = Image.idCount + 1? ? ? ? if type(pixmap) == type(""):? ? ? ? ? ? self.img = tk.PhotoImage(file=pixmap, master=_root)? ? ? ? else:? ? ? ? ? ? self.img = pixmap.image? ? ? ? ? ? ? ? def __repr__(self):? ? ? ? return "Image("+repr(self.anchor)+","+repr(self.img)+")"? ??? ? def _draw(self, canvas, options):? ? ? ? p = self.anchor? ? ? ? x,y = canvas.toScreen(p.x,p.y)? ? ? ? self.imageCache[self.imageId] = self.img # save a reference??? ? ? ? return canvas.create_image(x,y,image=self.img)? ??? ? def _move(self, dx, dy):? ? ? ? self.anchor.move(dx,dy)? ? ? ??? ? def undraw(self):? ? ? ? del self.imageCache[self.imageId]? # allow gc of tk photoimage? ? ? ? GraphicsObject.undraw(self) ? ? def getAnchor(self):? ? ? ? return self.anchor.clone()? ? ? ? def clone(self):? ? ? ? imgCopy = Pixmap(self.img.copy())? ? ? ? other = Image(self.anchor, imgCopy)? ? ? ? other.config = self.config.copy()? ? ? ? return other ? ? def getPixmap(self):? ? ? ? pm = Pixmap(0,0)? ? ? ? pm.image = self.img? ? ? ? return pm class Pixmap:? ? """Pixmap represents an image as a 2D array of color values.? ? A Pixmap can be made from a file (gif or ppm): ? ? ? ?pic = Pixmap("myPicture.gif")? ? ? ?? ? or initialized to a given size (initially transparent): ? ? ? ?pic = Pixmap(512, 512) ? ? """ ? ? def __init__(self, *args):? ? ? ? self.fileName=""? ? ? ? if len(args) == 1: # a file name or pixmap? ? ? ? ? ? self.fileName=args[0]? ? ? ? ? ? if type(args[0]) == type(""):? ? ? ? ? ? ? ? #self.image = _tkCall(tk.PhotoImage, file=args[0], master=_root)? ? ? ? ? ? ? ? self.image = tk.PhotoImage(file=args[0], master=_root)? ? ? ? ? ? else:? ? ? ? ? ? ? ? self.image = args[0]? ? ? ? else: # arguments are width and height? ? ? ? ? ? width, height = args? ? ? ? ? ? #self.image = _tkCall(tk.PhotoImage, master=_root, width=width, height=height)? ? ? ? ? ? self.image = tk.PhotoImage(master=_root, width=width, height=height)? ??? ? def __repr__(self):? ? ? ? if (self.fileName==""):? ? ? ? ? ? return "Pixmap("+ tk.StringVar(self.image.width) + "," + tk.StringVar(self.image.height) +")"? ? ? ? return "Pixmap(\"" + self.fileName +"\")"? ? ? ??? ? def getWidth(self):? ? ? ? """Returns the width of the image in pixels"""? ? ? ? return self.image.width() #_tkCall(self.image.width) ? ? def getHeight(self):? ? ? ? """Returns the height of the image in pixels"""? ? ? ? return self.image.height() #_tkCall(self.image.height) ? ? def getPixel(self, x, y):? ? ? ? """Returns a list [r,g,b] with the RGB color values for pixel (x,y)? ? ? ? r,g,b are in range(256) ? ? ? ? """? ? ? ??? ? ? ? value = self.image.get(x,y) #_tkCall(self.image.get, x,y)? ? ? ? if type(value) ==? type(0):? ? ? ? ? ? return [value, value, value]? ? ? ? else:? ? ? ? ? ? return list(map(int, value.split()))? ? ? def setPixel(self, x, y, rgbTuple):? ? ? ? """Sets pixel (x,y) to the color given by r,g,b values in rgbTuple.? ? ? ? r,g,b should be in range(256) ? ? ? ? """? ? ? ??? ? ? ? #_tkExec(self.image.put, "{" + color_rgb(*rgbTuple) +"}", (x, y))? ? ? ? self.image.put("{" + color_rgb(*rgbTuple) +"}", (x, y)) ? ? def clone(self):? ? ? ? """Returns a copy of this Pixmap"""? ? ? ? return Pixmap(self.image.copy()) ? ? def save(self, filename):? ? ? ? """Saves the pixmap image to filename.? ? ? ? The format for the save image is determined from the filname extension. ? ? ? ? """? ? ? ??? ? ? ? path, name = os.path.split(filename)? ? ? ? ext = name.split(".")[-1]? ? ? ? #_tkExec(self.image.write, filename, format=ext)? ? ? ? self.image.write( filename, format=ext) ? ? ? ??def color_rgb(r,g,b):? ? """r,g,b are intensities of red, green, and blue in range(256)? ? Returns color specifier string for the resulting color"""? ? return "#%02x%02x%02x" % (r,g,b) def test():? ? win = GraphWin()? ? win.setCoords(0,0,10,10)? ? t = Text(Point(5,5), "Centered Text")? ? t.draw(win)? ? p = Polygon(Point(1,1), Point(5,3), Point(2,7))? ? p.draw(win)? ? e = Entry(Point(5,6), 10)? ? e.draw(win)? ? win.getMouse()? ? p.setFill("red")? ? p.setOutline("blue")? ? p.setWidth(2)? ? s = ""? ? for pt in p.getPoints():? ? ? ? s = s + "(%0.1f,%0.1f) " % (pt.getX(), pt.getY())? ? t.setText(e.getText())? ? e.setFill("green")? ? e.setText("Spam!")? ? e.move(2,0)? ? win.getMouse()? ? p.move(2,3)? ? s = ""? ? for pt in p.getPoints():? ? ? ? s = s + "(%0.1f,%0.1f) " % (pt.getX(), pt.getY())? ? t.setText(s)? ? win.getMouse()? ? p.undraw()? ? e.undraw()? ? t.setStyle("bold")? ? win.getMouse()? ? t.setStyle("normal")? ? win.getMouse()? ? t.setStyle("italic")? ? win.getMouse()? ? t.setStyle("bold italic")? ? win.getMouse()? ? t.setSize(14)? ? win.getMouse()? ? t.setFace("arial")? ? t.setSize(20)? ? win.getMouse()? ? win.close() if __name__ == "__main__":? ? test() On Sunday, 2 August, 2020, 10:30:33 pm IST, Bob van der Poel wrote: Do you have tkinter installed? The graphics.py module needs it to run. On Sat, Aug 1, 2020 at 11:36 PM Sarvesh Poddar via Python-list wrote: ?Hi, I am currently using Python 3.8.5 with IDLE environment that comes pre-installed with the Python application. I am using the book "An Introduction to computer science" by John Zelle as my reference. The problem I am facing is "There is a python program named "graphics.py" that is used as reference in the book and I downloaded the python file from internet?(link to the file -?https://mcsp.wartburg.edu/zelle/python/graphics.py). I have kept this module in (C:\Users\sarvesh\AppData\Local\Programs\Python\Python38-32) and this is were my Python files also lie in C drive. The problem is that I am not able to import graphics.py file and when I try to do that following is the error I receive, Traceback (most recent call last): ? File "", line 1, in ? ? import graphics ? File "C:\Users\sarvesh\AppData\Local\Programs\Python\Python38-32\graphics.py", line 1 ? ? Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32? ? ? ? ? ?^SyntaxError: invalid syntax ?I have installed, uninstalled and then re-installed Python 3.8.5 multiple times but the problem remains. I did a thorough internet search and most of them suggested using sys path and following is the result, import sys>>> sys.path['', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\Lib\\idlelib', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages'] When I write a different line -? (from import graphics *), this is the output: from graphics import *Traceback (most recent call last):? File "", line 1, in ? ? from graphics import *? File "C:\Users\sarvesh\AppData\Local\Programs\Python\Python38-32\graphics.py", line 1? ? Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32? ? ? ? ? ?^SyntaxError: invalid syntax Please do let me know if I am missing out something very basic. Thanks and I look forward.? ? On Saturday, 1 August, 2020, 07:54:19 am IST, boB Stepp wrote:? ?On Thu, Jul 30, 2020 at 9:24 AM Sarvesh Poddar via Python-list wrote: > I re-installed Python in my Windows system as the earlier one was not able to import modules... You do not provide much detail to diagnose what your problem(s) is(are).? By the "earlier one" is it the same version as the one you re-installed?? Were you able to run IDLE with the "earlier one"?? By not being able to import modules do you mean modules from Python's standard library?? Or do you mean installing third party libraries using pip? > ...But now I am not able to open IDLE after multiple tries. Have you looked in your start menu in the list of installed programs for Python?? If it is there did you expand it and see if there is an entry for IDLE?? How have you been trying (unsuccessfully) to open IDLE? -- boB -- https://mail.python.org/mailman/listinfo/python-list -- **** Listen to my FREE CD at http://www.mellowood.ca/music/cedars **** Bob van der Poel ** Wynndel, British Columbia, CANADA ** EMAIL: bob at mellowood.ca WWW: ? http://www.mellowood.ca From sarvesh.poddar at yahoo.com Mon Aug 3 01:00:12 2020 From: sarvesh.poddar at yahoo.com (Sarvesh Poddar) Date: Mon, 3 Aug 2020 05:00:12 +0000 (UTC) Subject: [Tutor] Issue with Python module downloads from Library for a beginner Python coder. In-Reply-To: References: <1823668942.8336565.1596350188957.ref@mail.yahoo.com> <1823668942.8336565.1596350188957@mail.yahoo.com> Message-ID: <1393966639.8513726.1596430812445@mail.yahoo.com> Hello Dennis, Sorry for my copy-paste error and thanks for highlighting the same. I will make sure that from next time I will maintain the line breaks. I tried opening it in CMD and it did open with the skewed triangle figure although I am still not able to use it in my IDLE environment. Unfortunately, I am not able to move ahead with my Python classes because of this, as it specifically asks to import the module before proceeding. I saved the file in tkinter folder now and receive the same problem, >>> import graphicsTraceback (most recent call last):? File "", line 1, in ? ? import graphicsModuleNotFoundError: No module named 'graphics' Location of the file - C:\Program Files (x86)\Lib\tkinter Didn't work out. On Monday, 3 August, 2020, 12:47:26 am IST, Dennis Lee Bieber wrote: On Sun, 2 Aug 2020 06:36:28 +0000 (UTC), Sarvesh Poddar via Python-list declaimed the following: > Hi, >I am currently using Python 3.8.5 with IDLE environment that comes pre-installed with the Python application. I am using the book "An Introduction to computer science" by John Zelle as my reference. >The problem I am facing is "There is a python program named "graphics.py" that is used as reference in the book and I downloaded the python file from internet?(link to the file -?https://mcsp.wartburg.edu/zelle/python/graphics.py). I have kept this module in (C:\Users\sarvesh\AppData\Local\Programs\Python\Python38-32) and this is were my Python files also lie in C drive. The problem is that I am not able to import graphics.py file and when I try to do that following is the error I receive, >Traceback (most recent call last): >? File "", line 1, in ? ? import graphics >? File "C:\Users\sarvesh\AppData\Local\Programs\Python\Python38-32\graphics.py", line 1 >? ? Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32? ? ? ? ? ?^SyntaxError: invalid syntax >?I have installed, uninstalled and then re-installed Python 3.8.5 multiple times but the problem remains. I did a thorough internet search and most of them suggested using sys path and following is the result, > ??? In future, you might want to ensure your cut&paste and/or posting client, maintains line breaks -- many of your pastes seem to "unwrap" stuff... >When I write a different line -? (from import graphics *), this is the output: >from graphics import *Traceback (most recent call last):? File "", line 1, in ? ? from graphics import *? File "C:\Users\sarvesh\AppData\Local\Programs\Python\Python38-32\graphics.py", line 1? ? Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32? ? ? ? ? ?^SyntaxError: invalid syntax ... such as the above, which appears to have turned something like 7 lines of output into one long string/paragraph. ??? My only suggestion is to drop OUT of IDLE or whatever, and open a Windows command shell... and try running a script from that shell. I note that this library makes use of Tkinter -- which is also used by IDLE. The two uses may be causing complications. Going to a command shell avoids that. -=-=- C:\Users\Wulfraed\Downloads>type testgraphics.py import graphics print(dir(graphics)) C:\Users\Wulfraed\Downloads>python testgraphics.py ['BAD_OPTION', 'Circle', 'DEFAULT_CONFIG', 'Entry', 'GraphWin', 'GraphicsError', 'GraphicsObject', 'Image', 'Line', 'OBJ_ALREADY_DRAWN', 'Oval', 'Point', 'Polygon', 'Rectangle', 'Text', 'Transform', 'UNSUPPORTED_METHOD', '_BBox', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '__version__', '_root', '_update_lasttime', 'color_rgb', 'os', 'sys', 'test', 'time', 'tk', 'update'] C:\Users\Wulfraed\Downloads> -=-=- ??? Heck... from the command shell, navigate to the directory in which you saved graphics.py and enter -=-=- C:\Users\Wulfraed\Downloads>python graphics.py -=-=- ??? On my system, that pops up a small window with skewed triangle, some text, and a grey input field. -- ??? Wulfraed? ? ? ? ? ? ? ? Dennis Lee Bieber? ? ? ? AF6VN ??? wlfraed at ix.netcom.com? ? http://wlfraed.microdiversity.freeddns.org/ -- https://mail.python.org/mailman/listinfo/python-list From sarvesh.poddar at yahoo.com Mon Aug 3 01:05:26 2020 From: sarvesh.poddar at yahoo.com (Sarvesh Poddar) Date: Mon, 3 Aug 2020 05:05:26 +0000 (UTC) Subject: [Tutor] (Issue resolved!) Issue with Python module downloads from Library for a beginner Python coder. References: <420522126.1382371.1596431126036.ref@mail.yahoo.com> Message-ID: <420522126.1382371.1596431126036@mail.yahoo.com> Hi terry, I am so happy to mention that your suggestion worked! I moved the file from Tkinter to Lib and I am suddenly able to import the file.? Thanks you so much @Bob, @Arjun, @Cameron for your suggestions. I can finally move forward. I hope to contribute to this community in future after gaining enough experience on the Python subject. Looking forward! On Monday, 3 August, 2020, 12:51:28 am IST, Terry Reedy wrote: On 8/2/2020 2:36 AM, Sarvesh Poddar via Python-list wrote: [I downloaded] https://mcsp.wartburg.edu/zelle/python/graphics.py) I have unmangled the traceback and added explanations. > Traceback (most recent call last): >? ?File "", line 1, in > ? ? import graphics You typed this in IDLE Shell in response to the >>> prompt. >? ?File "C:\Users\sarvesh\AppData\Local\Programs\Python\Python38-32\graphics.py", line 1 This says that you put the file in the same directory as python.exe.? It should better be in ".../Lib/site-packages" or in a directory in "/Users/".? None the less, the import worked. >? ? ?Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32 >? ?? ? ? ? ?^ > SyntaxError: invalid syntax This says that the first line of graphics.py begins with "Python 3.8.5..."? This is the startup message printed by python.exe when run in interactive mode, and by IDLE's interactive Shell.? It is text, not python code.? It is not the first line of the file at that link (I checked). Look at the file on your disk and check its first line.? You may have to put '%appdata%' in the directory box if the /User//appdata directory is hidden on your machine. >? ?I have installed, uninstalled and then re-installed Python 3.8.5 multiple times but the problem remains.? > I did a thorough internet search and most of them suggested using sys path and following is the result, This suggestion is for when the import fails because the module is not found.? In your case, it was found and the import process started. > import sys>>> sys.path['', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\Lib\\idlelib', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32', 'C:\\Users\\sarvesh\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages'] > When I write a different line -? (from import graphics *), this is the output: > from graphics import *Traceback (most recent call last):? File "", line 1, in ? ? from graphics import *? File "C:\Users\sarvesh\AppData\Local\Programs\Python\Python38-32\graphics.py", line 1? ? Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32? ? ? ? ? ?^SyntaxError: invalid syntax Same bad first line, same error. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list From zbaban195 at gmail.com Mon Aug 3 16:01:51 2020 From: zbaban195 at gmail.com (Zarek Baban) Date: Mon, 3 Aug 2020 16:01:51 -0400 Subject: [Tutor] Unable to import module Message-ID: To whom it may concern, I am writing some code for exercise purposes and am unable to import the module requests. I have looked at the module list in Idle and saw it didn?t come with it so I was wondering how I would go about installing the module? Thank you. From PyTutor at DancesWithMice.info Mon Aug 3 18:39:14 2020 From: PyTutor at DancesWithMice.info (dn) Date: Tue, 4 Aug 2020 10:39:14 +1200 Subject: [Tutor] Unable to import module In-Reply-To: References: Message-ID: On 04/08/2020 08:01, Zarek Baban wrote: > To whom it may concern, > > I am writing some code for exercise purposes and am unable to import the module requests. I have looked at the module list in Idle and saw it didn?t come with it so I was wondering how I would go about installing the module? Thank you. Please provide some information: - which OpSys - which version of Python - copy-paste the code to perform the input - copy-paste the error messages resulting. -- Regards =dn From cs at cskk.id.au Mon Aug 3 19:04:19 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Tue, 4 Aug 2020 09:04:19 +1000 Subject: [Tutor] Draw table and compare random input In-Reply-To: References: Message-ID: <20200803230419.GA1364@cskk.homeip.net> On 30Jul2020 22:35, Phaik Huen Tan wrote: >I am supposed to draw a table for my random input (12 months of >expenses) >and compared it against the monthly target. I am able to get input from >the user but I am not able to compare each input and display each input by >month individually. Can you please provide guidance on where I did wrong on >my code? I know this post is nearly a week old, but nobody seems to have replied and I've only just noticed it myself. You basic difficulty or missing code is storing the expenditures in order to print them in the table later. Since there are to be exactly 12 months you don't need anything special, just a list of 12 values. For example: expenditures = [0] * 12 which will produce a 12 element list filled with zeroes. Remember that lists count from 0 in Python (and most programming languages), so these elements are indexed 0 through 11 inclusively. Having prepared the list, you would modify your while loop to store each expenditure in the appropriate element of the list. You could set: month_index = 0 # start at January before the loop begins, and store month_exp as the loop goes on: expenditures[month_index] = month_exp month_index += 1 Then down the bottom where you print your table, do the tests in a loop. After the headings are printed, write something like: # count from 0 to 11 using the range() function for month_index in range(12): month_exp = expenditures[month_index] if month_exp >= monthly_target: ... etc etc ... Cheers, Cameron Simpson >Below is my code: > ># This program calculates monthly expenses. ># Create a variable to control the loop. >keep_going = 'Y' >#Calculate monthly target for each of the 12 months using annual IT >expenses of $42500 >monthly_target = 42500/12 >print('Monthly target expenditure is $', format(monthly_target,'.2f')) > > > >while keep_going == 'Y' or keep_going == 'y': > # Initialize an accumulator for site expenditure > total = 0 > # Get the site expenditure > month_exp = int(input('Please enter month expenditure: ')) > if month_exp < 0: > print('Value must be greater than 0') > month_exp = int(input('Enter the correct site expenditure: ')) > # See if the user wants to do enter another one. > keep_going = input('Do you want to enter another ' + > 'month expenditure (Enter Y or y for yes): ') >#Print the table headings >print() >print('Month\t|Expense\t|Over,Under or Exact') >print('-----------------------------------------------') > >if month_exp >= monthly_target: > print("Over") >elif month_exp <= monthly_target: > print("Under") >else: > print("Exact") From o1bigtenor at gmail.com Tue Aug 4 17:39:37 2020 From: o1bigtenor at gmail.com (o1bigtenor) Date: Tue, 4 Aug 2020 16:39:37 -0500 Subject: [Tutor] Assistance request when using python 'calendar' In-Reply-To: References: Message-ID: On Tue, Aug 4, 2020 at 12:40 PM Dennis Lee Bieber wrote: > > On Fri, 31 Jul 2020 11:56:29 -0500, o1bigtenor > declaimed the following: > > Interesting -- according to the date stamp it took four days for this > to propagate up to gmane's mirror of the Tutor list. Your other posts on > comp.lang.python showed up almost immediately. > > >I regularly work in planning through multiple years at once. > >This means that I like to have a lot of stuff available in a calendar > >function. > >Python seems to be locked when I need to display more than 1 year at a > >time. > > > >I don't see a way to display something like 3 years worth of calendar > >starting at a point 23 months from now. > >(I see how to display 1 year at a time but not multiple years.) > > > > Bottom up: Multiple (Jan-Dec) years is done by looping once for each > year and combining the returned data yourself. > > For arbitrary start/end months you will have to loop asking for each > month, and you will have to combine that data into whatever structure makes > it suitable for your output criteria. > > My suggestion (carried over from comp.lang.python) is to use the HTML > calendar class. Each month is generated as an HTML table, and it is easy to > wrap multiple month tables as cells in a larger table structure. Then use a > web browser to view the end result -- the browser even allows horizontal > scrolling if the calendar is wider than the browser window). Very interesting, a program from the mid 1980's called 'cal' is far more flexible and productive. Sorry - - - - the assumption seems to be that this is an occasional kind of thing. Over the weekend (a long weekend here) I actually had to use 3 different iterations of the calendar. It is not uncommon in this task to need to work for over much more than 3 years. As the present iteration only works from today's date as soon as the time frame stumbles forward the calendar must needs be extended. The solutions presented seem to infer that the request is somewhat static. If the entire code base needs to be rewritten each time the span of years desired changes then the tool is obstructing the work rather than assisting in that work's completion. So HTML isn't going to help much. Great idea for a static calendar but likely not as good for a flexible one. > > >Is there a way to do this? > > This appears to be a feature request -- in that you are dissatisfied by > the calendar module as it exists. You haven't shown any code attempting to > develop your solution, nor any exploration of outside sources. > > One of the first things that showed up on Google search is: > https://www.freecodecamp.org/news/introducing-timeboard-a-python-business-calendar-package-a2335898c697/ > Which may be too specific to job scheduling... There are ideas present in said example but it might be easier to re-write perl code written by a now deceased mentor/friend where that code got most of the job done but there are some things that need changing and a few bits of the visuals I desire to change. I have been looking for about 4 years for software usable over a period of at least 2 years. Had found 'cal' but was frustrated that I could only get a display of 3 months in width no matter what terminal screen column count was available because the 80 x 25 terminal is hard wired into 'cal'. So I was looking at how to misdirect cal into believing that it could write to a 220+ column wide terminal. That would have given me the flexibility in use and most of the features I needed. In retrospect maybe I had complained a few too many times about hard limits in programs carrying over some almost 40 years and so it was quite to my surprise when my friend sent me a few pages of source code and said - - - - try it, tell me what doesn't work. So the last version I received was about the 6th (IIRC). This was something he worked on sporadically likely as much for amusement as for the pleasure of doing it. We traded ideas and concepts in a very very large variety of areas and with spring approaching we both got busy with other ideas and projects. He was not able to complete the program. > > https://www.guru99.com/calendar-in-python.html > https://pymotw.com/2/calendar/ are tutorials of the standard calendar > module. As stated in the second link > """ > If you need to produce output in a format other than one of the available > defaults, you can use calendar to calculate the dates and organize the > values into week and month ranges, then iterate over the result yourself. > The weekheader(), monthcalendar(), and yeardays2calendar() methods of > Calendar are especially useful for that sort of work. > """ The second of the above examples has some ideas which need to be extended to get closer to what I need. My research has shown that week numbers is something that is actually quite a foreign concept in many cultures as this just isn't the way things are done. Except - - - - - if I give you a date and ask you for the date some 45 days before and 105 days after - - - - well that's another program and some computations and then when I ask you for the next date - - - - well that's taking a lot of time. If I ask you for the date 6 weeks and 3 days before x and the date 15 weeks later you go to your trusty - - - - not yours but mine - - - - calendar with the week numbers and most anyone can take a week number and subtract 6 (and three days please) and add 15 to the week number. No programming and very very simple steps. > > https://github.com/llazzaro/django-scheduler is for the Django > web-application framework > There are LOTS of calendars like that out there. They mostly all have one huge limitation - - - - they work within one (1) year - - - so when you need 2.5 to 3 - - - - better luck next time - - - - and yes I've looked. Installed I don't know how many business/project management programs and its one of the common joys - - - - as soon as you want to look at a calendar over more than one years time - - - highly unlikely. > > I would also point out that the calendar module is in the Python > library directory, and is a Python source code file (not some compiled > C-language extension), so you can readily study it to work out potential > subclassing. In particular, you may wish to study the .formatyear() methods > of the text and HTML classes. I have spent some time looking for 'official' Python information on sub-classes and their development. Found nothing to date but have only spent some 45 minutes so maybe with more time some to be found - - - maybe. > > Even if you manage to create a subclass which can take a start > year/month and an end year/month, take note that you have no ability to > annotate this data; that is, you can not mark specific dates as having some > event happen on that date. The best you could do is generate an HTML output > and later edit the cells of the HTML tables to contain your annotations. If > you intend to create a full "business planning" application you'll have to > extend calendar to work with something that can hold the annotations > between sessions (save/load logic), probably using raw datetime objects for > each day, and modifying/subclassing calendar so that it can use the > datetime object embedded in your data to determine where to place it on the > output calendar. > Much work to be done and it is ever so fascinating to see how prevalent business thinking is confined into small time frames. But then business is primarily worried about profitability per quarter - - - - - well that is what the senior staff earn their bonuses on - - - - but here - - - I really do need to work across at least 3 and preferably even 5 years but that's considered to be a corner case - - - - . Thanks for the ideas. From alan.gauld at yahoo.co.uk Wed Aug 5 05:22:40 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 5 Aug 2020 10:22:40 +0100 Subject: [Tutor] Assistance request when using python 'calendar' In-Reply-To: References: Message-ID: On 04/08/2020 22:39, o1bigtenor wrote: > Very interesting, a program from the mid 1980's called 'cal' is far > more flexible But remember that cal is a user application. calendar us a programmers building block. You can use calendar to create an application but its not the final item. > Sorry - - - - the assumption seems to be that this is an occasional > kind of thing. I'm not sure what you mean by that? Occasional in what sense? As opposed to what? > The solutions presented seem to infer that the request is somewhat static. > If the entire code base needs to be rewritten each time the span of years > desired changes then the tool is obstructing the work rather than assisting in > that work's completion. So HTML isn't going to help much. Great idea for > a static calendar but likely not as good for a flexible one. You need to explain more about what you are trying to do. You certainly shouldn't need to rewrite any code to accommodate changes to dates. And HTML is just a presentation tool, it doesn't care too much what goes into it. > There are ideas present in said example but it might be easier to re-write > perl code written by a now deceased mentor/friend where that code got most > of the job done but there are some things that need changing and a few bits > of the visuals I desire to change. One of the great things about software is that if the building blocks at hand don't do what you want you can always drop down a level to the more primitive blocks and build exactly what you do want. > I have been looking for about 4 years for software usable You could have written a lot of code to do exactly what you wanted in 4 years. > My research has shown that week numbers is something that is actually > quite a foreign concept in many cultures as this just isn't the way things > are done. Except - - - - - if I give you a date and ask you for the date > some 45 days before and 105 days after - - - - well that's another program Yes, and another module in Pythons case. That's what datetime is for. Calendar is quite a limited module designed for a fairly specific task. If you need more datetime is probably a better option, but you need to do the output formatting yourself. > take a week number and subtract 6 (and three days please) and add > 15 to the week number. No programming and very very simple steps. We are discussing programming modules so you are unlikely to get a solution with "no programming" but you will find the tools such that you can program it such that you users don't need to. > There are LOTS of calendars like that out there. They mostly all have one > huge limitation - - - - they work within one (1) year - - - Which tells us that the vast majority of programmers never need to go beyond that. Certainly in 30+ years writing business level applications I never had a need for any calendar display beyond 1 year. The app could handle multiple different years but display was always limited to 1 year. The fact that most modules support that suggests I am not alone. So if you need something different you probably need to write it yourself. All modules are created to meet someone's need. If your need exceeds what the module can do you will need to do the extra work yourself. And hopefully then make it available to others as a module. >> C-language extension), so you can readily study it to work out potential >> subclassing. In particular, you may wish to study the .formatyear() methods >> of the text and HTML classes. > > I have spent some time looking for 'official' Python information on sub-classes > and their development. Found nothing to date but have only spent some 45 > minutes so maybe with more time some to be found - - - maybe. I don't know where you were looking because the official Python tutorial includes that(Sect 9.5), as does almost every other tutorial - including mine(see .sig). The technique is identical to almost every other OOP language. > Much work to be done and it is ever so fascinating to see how prevalent > business thinking is confined into small time frames. But then business is > primarily worried about profitability per quarter - - - - - well that > is what the > senior staff earn their bonuses on - - - - but here - - - I really do need to > work across at least 3 and preferably even 5 years but that's considered > to be a corner case - - - - . Breaking new ground is always interesting. But also laborious. I remember the first time I had to write an app that worked in local time in sites all round the planet while keeping synchronised to a central time. I naively thought there were 24 time timezones neatly separated by hours, easy. Then discovered there were around 40 arranged in near random patterns with different daylight saving arrangements etc etc. And none of the OS or databases at the time supported any of it, we had to code it from scratch. When you go beyond the norm it is always difficult. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From sheilamocallaghan at gmail.com Wed Aug 5 07:46:09 2020 From: sheilamocallaghan at gmail.com (Nanogram32) Date: Wed, 5 Aug 2020 04:46:09 -0700 Subject: [Tutor] Last post /cal Message-ID: <6F196C1E-458D-4CEF-9499-0F028139B71B@gmail.com> Very interesting but nothing to do with my question. I am trying to open a file in Library. Thanks, Nanogram32 Sent from my iDunno From alan.gauld at yahoo.co.uk Wed Aug 5 11:27:06 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 5 Aug 2020 16:27:06 +0100 Subject: [Tutor] Last post /cal In-Reply-To: <6F196C1E-458D-4CEF-9499-0F028139B71B@gmail.com> References: <6F196C1E-458D-4CEF-9499-0F028139B71B@gmail.com> Message-ID: On 05/08/2020 12:46, Nanogram32 wrote: > Very interesting but nothing to do with my question. What question? I don't see any posts from you in the last few days? > I am trying to open a file in Library. Sorry, which Libary? What OS are you using? How are you trying to open it? >From Python code or from an IDE or from the OS? You need to give us more information about what you are trying to do and how. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From PyTutor at DancesWithMice.info Wed Aug 5 11:37:54 2020 From: PyTutor at DancesWithMice.info (dn) Date: Thu, 6 Aug 2020 03:37:54 +1200 Subject: [Tutor] Assistance request when using python 'calendar' In-Reply-To: References: Message-ID: <55d95cb2-19ac-8755-aff6-e18af36a589d@DancesWithMice.info> On 05/08/2020 09:39, o1bigtenor wrote: >>> I regularly work in planning through multiple years at once. >>> This means that I like to have a lot of stuff available in a calendar >>> function. >>> Python seems to be locked when I need to display more than 1 year at a >>> time. >>> >>> I don't see a way to display something like 3 years worth of calendar >>> starting at a point 23 months from now. >>> (I see how to display 1 year at a time but not multiple years.) >> >> Bottom up: Multiple (Jan-Dec) years is done by looping once for each >> year and combining the returned data yourself. >> >> For arbitrary start/end months you will have to loop asking for each >> month, and you will have to combine that data into whatever structure makes >> it suitable for your output criteria. >> > Very interesting, a program from the mid 1980's called 'cal' is far > more flexible > and productive. > > Over the weekend (a long weekend here) I actually had to use 3 different > iterations of the calendar. It is not uncommon in this task to need to work for > over much more than 3 years. As the present iteration only works from today's > date as soon as the time frame stumbles forward the calendar must needs > be extended. ... >> This appears to be a feature request -- in that you are dissatisfied by >> the calendar module as it exists. You haven't shown any code attempting to >> develop your solution, nor any exploration of outside sources. .. > I have been looking for about 4 years for software usable over a period of at > least 2 years. Had found 'cal' but was frustrated that I could only get a > display of 3 months in width no matter what terminal screen column count > was available because the 80 x 25 terminal is hard wired into 'cal'. So I was > looking at how to misdirect cal into believing that it could write to a 220+ > column wide terminal. That would have given me the flexibility in use and > most of the features I needed. In retrospect maybe I had complained a few > too many times about hard limits in programs carrying over some almost 40 > years and so it was quite to my surprise when my friend sent me a few pages > of source code and said - - - - try it, tell me what doesn't work. So the last > version I received was about the 6th (IIRC). This was something he worked > on sporadically likely as much for amusement as for the pleasure of doing it. > We traded ideas and concepts in a very very large variety of areas and with > spring approaching we both got busy with other ideas and projects. He was > not able to complete the program. ... >> If you need to produce output in a format other than one of the available >> defaults, you can use calendar to calculate the dates and organize the >> values into week and month ranges, then iterate over the result yourself. >> The weekheader(), monthcalendar(), and yeardays2calendar() methods of >> Calendar are especially useful for that sort of work. >> """ > > The second of the above examples has some ideas which need to be > extended to get closer to what I need. > My research has shown that week numbers is something that is actually > quite a foreign concept in many cultures as this just isn't the way things > are done. Except - - - - - if I give you a date and ask you for the date ... > There are LOTS of calendars like that out there. They mostly all have one > huge limitation - - - - they work within one (1) year - - - so when you need > 2.5 to 3 - - - - better luck next time - - - - and yes I've looked. Installed I > don't know how many business/project management programs and its > one of the common joys - - - - as soon as you want to look at a calendar > over more than one years time - - - highly unlikely. >> >> I would also point out that the calendar module is in the Python >> library directory, and is a Python source code file (not some compiled >> C-language extension), so you can readily study it to work out potential >> subclassing. In particular, you may wish to study the .formatyear() methods >> of the text and HTML classes. > > I have spent some time looking for 'official' Python information on sub-classes > and their development. Found nothing to date but have only spent some 45 > minutes so maybe with more time some to be found - - - maybe. > >> >> Even if you manage to create a subclass which can take a start >> year/month and an end year/month, take note that you have no ability to >> annotate this data; that is, you can not mark specific dates as having some >> event happen on that date. The best you could do is generate an HTML output >> and later edit the cells of the HTML tables to contain your annotations. If >> you intend to create a full "business planning" application you'll have to >> extend calendar to work with something that can hold the annotations >> between sessions (save/load logic), probably using raw datetime objects for >> each day, and modifying/subclassing calendar so that it can use the >> datetime object embedded in your data to determine where to place it on the >> output calendar. >> > Much work to be done and it is ever so fascinating to see how prevalent > business thinking is confined into small time frames. But then business is > primarily worried about profitability per quarter - - - - - well that > is what the > senior staff earn their bonuses on - - - - but here - - - I really do need to > work across at least 3 and preferably even 5 years but that's considered > to be a corner case - - - - . This was discussed at some length on the Python-List. The PSL library produces calendars for a 12-month horizon or by the month. Instead of thinking of 40-months as three-years plus four-months. Perhaps think of it as 40 separate months that will be joined into a single, cohesive, unit? (as previously suggested) Now, the limitation is the width of the presentation-screen (which appears to be the specification, so please say if that is not so). The discussion of dates and their presentation is faulty. There is an ISO standard (8601) for dates (https://www.w3.org/QA/Tips/iso-date) - although its presentation may not suit some, eg Arab and Jewish definitions of "weeks" and US resistance to "international" or "world". Specifically, the calendar library offers week-numbers (see previously offered web.ref). Aside: I was amused by @wlfraed's comment about HTML calendars. Some time last century I was introducing a municipality's first Internet and Intranet sites (as they termed the project - it was last century!) and I wanted an Events Calendar. The young HTML 'programmer' I had been given claimed it couldn't be done. So, I spent the next weekend teaching myself HTML and proving him wrong - and a new career-direction was born! Oh, and yes, each date could be a link, to a list of events 'on' that day. The question is rarely, can it possibly be done - but rather: how much effort will it take and do I have the problem-solving ability to achieve the required/desired result? So, with sympathies for your friend, and kudos for the idea of migrating to Python, what have you achieved? Right now the conversation seems to be repeating itself (from Python to Tutor-list). Two of us have suggested taking the output from calendar, no matter how traditional, and post-processing that/bending it to your will. What did you try, and how far did you get? (as above) How about showing us (the core of) some code which produces 'something' - together with a critique of the short-comings. Then we may be able to assist you to make progress... Remember, the way to solve a 'big problem' is to break it down into smaller problems (which are more easily solved)! Suggestions/recommendations to include in a future response: 1) clear summary-list of functional requirements/limitations 2) how to deal with the concept of 'width' (further to above comments about the limits of 80-col screens and your-previous of wider screen-resolution) and relate that back to (mono) font-width or string-lengths, ie how do you relate a calendar ~four years long to physical display limitations? 3) sample code to collect the calendar's first and last year-month, or year-week, extent 4) sample code to calculate the weekNR of the first year-month (if that's the input spec) 5) any other steps you have achieved to-date (perhaps similar to the lines of interactive-console prototyping illustrated elsewhere) -- Regards =dn From canmichael2 at gmail.com Wed Aug 5 23:43:25 2020 From: canmichael2 at gmail.com (Let's Play PC) Date: Wed, 5 Aug 2020 20:43:25 -0700 Subject: [Tutor] Issue with importing a module from the same directory Message-ID: Hello, I am having issues importing a module from the same directory as where my project is located as python says it does not exist. I'm using PyCharm and my project structure makes a direct path to a folder containing these files (embedded in another folder). Any thoughts on how I can resolve the issue? Thanks in advance. From alan.gauld at yahoo.co.uk Thu Aug 6 04:11:02 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 6 Aug 2020 09:11:02 +0100 Subject: [Tutor] Issue with importing a module from the same directory In-Reply-To: References: Message-ID: On 06/08/2020 04:43, Let's Play PC wrote: > Hello, I am having issues importing a module from the same directory as > where my project is located as python says it does not exist. Specifics are always easier to answer. Can you show us a minimal file that exhibits the problem along with a listing of your file structure(just for the example files you used) Also show us the full error message. > PyCharm and my project structure makes a direct path to a folder containing > these files (embedded in another folder). Any thoughts on how I can resolve > the issue? Thanks in advance. None of that sounds unusual, but maybe we can spot something if you send the above details. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Thu Aug 6 09:02:16 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 6 Aug 2020 14:02:16 +0100 Subject: [Tutor] Assistance request when using python 'calendar' In-Reply-To: References: Message-ID: <37cb37dc-3ed5-bc2e-3f0d-6f5376898c14@yahoo.co.uk> Please alwaysreply ALL so it goes to the list. On 06/08/2020 13:20, o1bigtenor wrote: >>> Sorry - - - - the assumption seems to be that this is an occasional >>> kind of thing. >> >> I'm not sure what you mean by that? Occasional in what sense? >> As opposed to what? > > Occasional in use and possibly even occasional in the demands placed > upon the program. >> HTML is just a presentation tool, it doesn't care too much what goes >> into it. > > That's true - - - except HTML assumes that this is something for the web. > This is much more of a tool for use in developing business planning. This > business really has zero desire to make its planning public. Most businesses today have the majority of their application developed on the web. Not necessarily the public web but on their private intranet. It makes them easier to deploy and they can run on multiple devices (Mac/Linux/Windows/Android/iOS etc). But even many desktop apps are nowadays written using HTML (and maybe a little Javascript) for presentation even if no web server is involved, again it makes the display portable to multiple devices. HTML does not imply the web, it implies at most a web browser. >>> There are LOTS of calendars like that out there. They mostly all have one >>> huge limitation - - - - they work within one (1) year - - - >> >> Which tells us that the vast majority of programmers never need to go > > Interesting - - - - when a need is expressed for something that has been > passed over for some 30 years the individual asking for change is considered > the 'problematic' one. Not the problematic one, but the one with the problem. Code gets written to solve a problem. The person with the problem writes it. That's how it happens. If you have a problem that nobody else has solved yet then you have to come up with the solution. Nobody else will do it for you unless you pay them, in which case it becomes their problem. >> I don't know where you were looking because the official Python >> tutorial includes that(Sect 9.5), as does almost every other >> tutorial - including mine(see .sig). The technique is identical >> to almost every other OOP language. > > You are presupposing intimate acquaintance with all aspects of programming. Not at all. A Python tutorial should be the first port of call for anyone starting programming in python. And classes (and subclasses are so fundamental to python programming that every tutorial includes instructions on how to do it. > I do not believe that I said anywhere that I was a long term practitioner of > said skill. As EVERY skill has its jargon there is a massive stumbling block > to the learner in even understanding what to look for. That's a very fair point. But reading any tutorial and search for subclass should have got you there pretty quickly. (Or even a google search for python subclass) >> I remember the first time I had to write an app that worked in >> local time in sites all round the planet while keeping synchronised >> > Exactly - - - - and today the that time very laboriously coded provisions > are likely a quite common little subset of the whole and only need to be > called - - - - no coding at all. Not exactly, most timezone software now provides about 37 timezones (so not all of them) and basic functions, but to do it properly there is still a lot of edge cases to be handled in code. But the point is that somebody had to create the software, somebody like me with a need for it. It wasn't written by somebody just for fun. > someone to want something to begin the process. I see no real > restriction to indicating that the calendar module needs some extending. Absolutely, and in the worlds of open source you are free to extend it. (Or hire someone to do it for you.) You can then offer those changes back to the community. Its how it works. > Whether that idea gets any traction - - - - -well that's not up to me but > I would hope that the idea would be given some careful consideration > by those tasked with developing the language. Nobody is tasked with developing the language. This is not a product that you submit requests and then pay to get a new version with the changes. It is open source. You (and everyone else using it) are the one tasked with developing the language. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From ulfat.hajiyev at gmail.com Thu Aug 6 14:13:22 2020 From: ulfat.hajiyev at gmail.com (Ulfat Hajiyev) Date: Thu, 6 Aug 2020 22:13:22 +0400 Subject: [Tutor] How to download Django Message-ID: Hi all, Pls, help me to install Django. I have read many things about VE, pip as well as djangoproject.com/download/ but wasnt able to download. I am using VS 1.47.3 as editor, python 3.7 extension is enabled Regards, Ulfat From andre.luis.m.pinto at gmail.com Thu Aug 6 19:34:04 2020 From: andre.luis.m.pinto at gmail.com (=?UTF-8?B?QW5kcsOpIFBpbnRv?=) Date: Thu, 6 Aug 2020 20:34:04 -0300 Subject: [Tutor] Get image url Message-ID: How can I get the web site url address using web scraping if I have the image tag? Best regards Andr? Luis From alan.gauld at yahoo.co.uk Thu Aug 6 19:46:26 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 7 Aug 2020 00:46:26 +0100 Subject: [Tutor] Get image url In-Reply-To: References: Message-ID: On 07/08/2020 00:34, Andr? Pinto wrote: > How can I get the web site url address using web scraping if I have the > image tag? I assume you mean the url of the image rather than the url of the host web site(since you presumably have that to scrape in the first place?) Which web scraper/parser are you using? If it is BeautifulSoup then getting the url from the img tag should be a simple lookup: https://www.crummy.com/software/BeautifulSoup/bs4/doc/#attributes -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Fri Aug 7 03:43:20 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 7 Aug 2020 08:43:20 +0100 Subject: [Tutor] Get image url In-Reply-To: References: Message-ID: Please always use ReplyAll to include the list On 07/08/2020 00:53, Andr?? Pinto wrote: > I have the image tag and I need to find out what its url is ... Are you using BeautifulSoup? Did you check the tutorial link I gave? It should be as simple as: url = my_imgtag['src'] If you are using a different parser it will be different code, you need to tell us more. Ideally, share some code. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From robertvstepp at gmail.com Sat Aug 8 21:18:46 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 8 Aug 2020 20:18:46 -0500 Subject: [Tutor] How to download Django In-Reply-To: References: Message-ID: On Thu, Aug 6, 2020 at 6:31 PM Ulfat Hajiyev wrote: > Pls, help me to install Django. I have read many things about VE, pip as > well as djangoproject.com/download/ but wasnt able to download. What exactly were the indications of failure? It would have been helpful if you had copy and pasted what you tried and likewise copy and pasted any error tracebacks you received. And what operating system are you using? > I am using VS 1.47.3 as editor, python 3.7 extension is enabled I have not had occasion (yet) to install Django. But going to the link you provided I imagine you could install it with: 1) For Windows: py -m pip install Django==3.1 2) Other OS: python3 -m pip install Django==3.1 Note that the page you link to has further installation instructions at https://docs.djangoproject.com/en/3.1/intro/install/ HTH! -- boB From grunfelderic at gmail.com Sun Aug 9 15:06:05 2020 From: grunfelderic at gmail.com (eric grunfeld) Date: Sun, 9 Aug 2020 15:06:05 -0400 Subject: [Tutor] First Time With Python - How To Calculate This Formula Message-ID: Hello Everyone: This is my first time using Python and I am unsure as to how to calculate this formula: (((1+2)?3)/4) (to the 5th power) I figured out how to do most of the formula without to the 5th power but unsure as to how to incorporate "to the 5th power" This is what I have without incorporating "to the 5th power" print(((1+2)*3)/4 Unsure where to place "to the 5th power" I look forward to your response Thank you for your help. Eric From alan.gauld at yahoo.co.uk Sun Aug 9 19:40:13 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 10 Aug 2020 00:40:13 +0100 Subject: [Tutor] First Time With Python - How To Calculate This Formula In-Reply-To: References: Message-ID: On 09/08/2020 20:06, eric grunfeld wrote: > This is what I have without incorporating "to the 5th power" > print(((1+2)*3)/4 > > Unsure where to place "to the 5th power" You have 2 options 1) use the pow() function pow(2,5) -> 32 2) use the ** operator 2 ** 5 -> 32 So in your example: print( (((1+2)*3)/4) ** 5 ) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From zebra05 at gmail.com Sun Aug 9 23:04:17 2020 From: zebra05 at gmail.com (S D) Date: Mon, 10 Aug 2020 05:04:17 +0200 Subject: [Tutor] Serializing bytestring as JSON Message-ID: Hi. If you're reading this, I hope you're healthy and safe. I built an RPC service based on the Nameko framework. The service class implements a method which takes a list of strings as an argument and returns a dictionary with each original string as a key and the string Huffman encoded as a value. The encoding works, but I cannot send the return value across the network because the encoded bytestrings cannot be serialized to JSON. If I import the service class and test the methods using PyTest, this problem is not reproduced. How can I return a Huffman encoded bytestring over a wire as JSON? TIA. Kind regards, ~ SD From cs at cskk.id.au Mon Aug 10 04:59:23 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Mon, 10 Aug 2020 18:59:23 +1000 Subject: [Tutor] Serializing bytestring as JSON In-Reply-To: References: Message-ID: <20200810085923.GA83552@cskk.homeip.net> On 10Aug2020 05:04, S D wrote: >I built an RPC service based on the Nameko framework. The service class >implements a method which takes a list of strings as an argument and >returns a dictionary with each original string as a key and the string >Huffman encoded as a value. The encoding works, but I cannot send the >return value across the network because the encoded bytestrings cannot be >serialized to JSON. > >If I import the service class and test the methods using PyTest, this >problem is not reproduced. > >How can I return a Huffman encoded bytestring over a wire as JSON? Aren't Huffman codes variable bit lengths? But anyway, presuming you've got bytes you have a few choices. The basic deal is that you need to turn the values into a type which can be JSON serialised, so a string seems simplest. But any pair of reversible functions would do, converting bytes to something JSON serialisable, and the reverse. So you want something like: # original dict with str->bytes mapping src_dict = { 'a': b'zzzz', ... } jsonable_dict = { k: bytes_as_str(v) for k, v in src_dict.items() } ... send JSON now ... ... receive some JSON ... # a received JSON dict with b'zzzz' expressed as some string serialised_dict = { 'a': 'bsbsbsbsbs', ...} # decode the strings back into original bytes dst_dict = { k: str_as_bytes(v) for k, v in serialised_dict.items() } So you just need to define your bytes_as_str() and str_as_bytes() functions. The simplest thing might be to pretend the bytes are in fact the binary transcription of some 8-bit character set. Such as 'iso8859-1'. AN 8 bit character set will neatly map 1-to-1 into a byte, since a byte is 8 bits. It doesn't matter what character set we choose provided that its encode and decode functions put a single character into a single byte and vice versa. So you might make: def bytes_as_str(bs): return bs.decode('iso8859-1') and the converse str_as_bytes() to reverse it. Cheers, Cameron Simpson From mats at wichmann.us Mon Aug 10 09:30:18 2020 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 10 Aug 2020 07:30:18 -0600 Subject: [Tutor] Serializing bytestring as JSON In-Reply-To: References: Message-ID: On 8/9/20 9:04 PM, S D wrote: > Hi. If you're reading this, I hope you're healthy and safe. > > I built an RPC service based on the Nameko framework. The service class > implements a method which takes a list of strings as an argument and > returns a dictionary with each original string as a key and the string > Huffman encoded as a value. The encoding works, but I cannot send the > return value across the network because the encoded bytestrings cannot be > serialized to JSON. > > If I import the service class and test the methods using PyTest, this > problem is not reproduced. > > How can I return a Huffman encoded bytestring over a wire as JSON? Just a question to think about: are you sure you actually want JSON to be your over-the-wire encoding? It's human-readable, yes, but adds a fair bit of bulk, and is not sufficient for directly encoding Python datastructures, although you can make _anything_ work with enough effort. From shaneperfit3121 at gmail.com Mon Aug 10 23:03:23 2020 From: shaneperfit3121 at gmail.com (Jack Funkinstain) Date: Mon, 10 Aug 2020 20:03:23 -0700 Subject: [Tutor] Is it possible to make a Raspberry do what I need it to do? Message-ID: hello Can you please help me with my raspberry project For my project I need to make a Raspberry Pi Play an HD 1080 video on start up/boot/ in full screen. The video will be roughly 15 minutes long and will play in a loop. It is very important that there is not a blank screen or any visual or audio gaps when the loop starts over (I have heard that some media player program have a noticeable delay between the end and the start of a loop). The video needs to load/start with the volume all the way down, then have a motion sensor trigger an automation of the volume parameter on the media player program to gradually go up/fade in to a set volume level (most likely full volume). The volume then needs to stay at a fixed/consistent level while the person is in front of the sensor. Then when the person leaves, the sensor triggers the automation of the volume parameter to gradually go down/fade out. If a person triggers the motion sensor before the volume reaches 0, I want the volume parameter to increase from the point it left off rather than start from 0. I will also need to install a power button. I will not be using the raspberry pi as a desktop computer. The one video MPEG4 and possibly separate audio clip I add will be the only files ever played on this Raspberry. I will be saving the video file onto a 16gb micro sd card (not on a usb drive). After the initial setup and configuration the only ports I will be using is the HDMI port and audio out jack, no wifi. I want to just plug it in, then the video/audio/programs automaically play for hours/days. Then when I am done, just push the power off button and unplug the device. Sort of as if it was being used headless. Questions I have. 1. The Raspberry pi will be in non-stop use for hours, maybe days. I read that people have used raspberry?s in video art galleries for up to 4 days without over heating problems. But I also have read that people have installed cooling systems/heat sinks for certain models (perhaps older models?)and I have seen that many official retailers offer kits with cooling systems. And I also read that it is unnecessary and pointless to install heat sinks and cooling devices on a raspberry. Do some models get hotter than others? Will the heat reduce performance causing my video/audio to glitch or cause the programs to crash? Will the application I plan on using this for cause heating problems if it is in continues use? If for some reason I cannot accomplish my goal with one media player program and I have to run 2 applications, one playing the video, the other playing the audio, possibly another for the automation, will this be a problem for certain models to handle? Will 2GB of ram be enough for my project? Does the Raspberry Pi 3 model A+ get less hot and therefore better suited for my project? Is a 16gb micro sd card enough? 2. Is what I am trying to do even possible on a raspberry pi ? I have not been able to find any tutorial about automating software parameter changes. Can you recommend any software to use for the automation? I know there are several different media player programs you can download to use as a video looper but can you recommend the one that has no noticeable gaps when restarting a loop? Will I need a breadboard, HAT? The motion sensor will be 30 inches away from the Raspberry pi and mounted onto a piece of wood. 3. I have not been able to find a tutorial video on how to code my Raspberry to do what I need it to do. Do you have any recommendations? 4. Can you please make a tutorial video to do what I am trying to do? Thank you From joel.goldstick at gmail.com Tue Aug 11 09:28:02 2020 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 11 Aug 2020 09:28:02 -0400 Subject: [Tutor] Is it possible to make a Raspberry do what I need it to do? In-Reply-To: References: Message-ID: On Tue, Aug 11, 2020 at 5:06 AM Jack Funkinstain wrote: > > hello > > Can you please help me with my raspberry project > > For my project I need to make a Raspberry Pi Play an HD 1080 video on start > up/boot/ in full screen. The video will be roughly 15 minutes long and will > play in a loop. It is very important that there is not a blank screen or > any visual or audio gaps when the loop starts over (I have heard that some > media player program have a noticeable delay between the end and the start > of a loop). The video needs to load/start with the volume all the way down, > then have a motion sensor trigger an automation of the volume parameter on > the media player program to gradually go up/fade in to a set volume level > (most likely full volume). The volume then needs to stay at a > fixed/consistent level while the person is in front of the sensor. Then > when the person leaves, the sensor triggers the automation of the volume > parameter to gradually go down/fade out. If a person triggers the motion > sensor before the volume reaches 0, I want the volume parameter to increase > from the point it left off rather than start from 0. I will also need to > install a power button. > > I will not be using the raspberry pi as a desktop computer. The one video > MPEG4 and possibly separate audio clip I add will be the only files ever > played on this Raspberry. I will be saving the video file onto a 16gb micro > sd card (not on a usb drive). After the initial setup and configuration the > only ports I will be using is the HDMI port and audio out jack, no wifi. I > want to just plug it in, then the video/audio/programs automaically play > for hours/days. Then when I am done, just push the power off button and > unplug the device. Sort of as if it was being used headless. > > Questions I have. > > 1. The Raspberry pi will be in non-stop use for hours, maybe days. I > read that people have used raspberry?s in video art galleries for up to 4 > days without over heating problems. But I also have read that people have > installed cooling systems/heat sinks for certain models (perhaps older > models?)and I have seen that many official retailers offer kits with > cooling systems. And I also read that it is unnecessary and pointless to > install heat sinks and cooling devices on a raspberry. Do some models get > hotter than others? Will the heat reduce performance causing my video/audio > to glitch or cause the programs to crash? Will the application I plan on > using this for cause heating problems if it is in continues use? If for > some reason I cannot accomplish my goal with one media player program and I > have to run 2 applications, one playing the video, the other playing the > audio, possibly another for the automation, will this be a problem for > certain models to handle? Will 2GB of ram be enough for my project? Does > the Raspberry Pi 3 model A+ get less hot and therefore better suited for my > project? Is a 16gb micro sd card enough? > 2. Is what I am trying to do even possible on a raspberry pi ? I have > not been able to find any tutorial about automating software parameter > changes. Can you recommend any software to use for the automation? I know > there are several different media player programs you can download to use > as a video looper but can you recommend the one that has no noticeable gaps > when restarting a loop? Will I need a breadboard, HAT? The motion sensor > will be 30 inches away from the Raspberry pi and mounted onto a piece of > wood. > 3. I have not been able to find a tutorial video on how to code my > Raspberry to do what I need it to do. Do you have any recommendations? > 4. Can you please make a tutorial video to do what I am trying to do? > > Thank you > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor This library looks promising. This is a python programming list. You may want to do some research at raspberrypi.org https://pypi.org/project/ffpyplayer/ -- Joel Goldstick http://joelgoldstick.com/blog http://cc-baseballstats.info/stats/birthdays From adameyring at gmail.com Tue Aug 11 10:48:44 2020 From: adameyring at gmail.com (Adam Eyring) Date: Tue, 11 Aug 2020 10:48:44 -0400 Subject: [Tutor] Is it possible to make a Raspberry do what I need it to do? In-Reply-To: References: Message-ID: This sounds doable with a cron setup to start on boot-up. Ideas can be found at raspberrypi.org as Joel mentioned or searching Youtube for how-tos. On Tue, Aug 11, 2020 at 9:28 AM Joel Goldstick wrote: > On Tue, Aug 11, 2020 at 5:06 AM Jack Funkinstain > wrote: > > > > hello > > > > Can you please help me with my raspberry project > > > > For my project I need to make a Raspberry Pi Play an HD 1080 video on > start > > up/boot/ in full screen. The video will be roughly 15 minutes long and > will > > play in a loop. It is very important that there is not a blank screen or > > any visual or audio gaps when the loop starts over (I have heard that > some > > media player program have a noticeable delay between the end and the > start > > of a loop). The video needs to load/start with the volume all the way > down, > > then have a motion sensor trigger an automation of the volume parameter > on > > the media player program to gradually go up/fade in to a set volume level > > (most likely full volume). The volume then needs to stay at a > > fixed/consistent level while the person is in front of the sensor. Then > > when the person leaves, the sensor triggers the automation of the volume > > parameter to gradually go down/fade out. If a person triggers the motion > > sensor before the volume reaches 0, I want the volume parameter to > increase > > from the point it left off rather than start from 0. I will also need to > > install a power button. > > > > I will not be using the raspberry pi as a desktop computer. The one video > > MPEG4 and possibly separate audio clip I add will be the only files ever > > played on this Raspberry. I will be saving the video file onto a 16gb > micro > > sd card (not on a usb drive). After the initial setup and configuration > the > > only ports I will be using is the HDMI port and audio out jack, no wifi. > I > > want to just plug it in, then the video/audio/programs automaically play > > for hours/days. Then when I am done, just push the power off button and > > unplug the device. Sort of as if it was being used headless. > > > > Questions I have. > > > > 1. The Raspberry pi will be in non-stop use for hours, maybe days. I > > read that people have used raspberry?s in video art galleries for up > to 4 > > days without over heating problems. But I also have read that people > have > > installed cooling systems/heat sinks for certain models (perhaps older > > models?)and I have seen that many official retailers offer kits with > > cooling systems. And I also read that it is unnecessary and pointless > to > > install heat sinks and cooling devices on a raspberry. Do some models > get > > hotter than others? Will the heat reduce performance causing my > video/audio > > to glitch or cause the programs to crash? Will the application I plan > on > > using this for cause heating problems if it is in continues use? If > for > > some reason I cannot accomplish my goal with one media player program > and I > > have to run 2 applications, one playing the video, the other playing > the > > audio, possibly another for the automation, will this be a problem for > > certain models to handle? Will 2GB of ram be enough for my project? > Does > > the Raspberry Pi 3 model A+ get less hot and therefore better suited > for my > > project? Is a 16gb micro sd card enough? > > 2. Is what I am trying to do even possible on a raspberry pi ? I have > > not been able to find any tutorial about automating software parameter > > changes. Can you recommend any software to use for the automation? I > know > > there are several different media player programs you can download to > use > > as a video looper but can you recommend the one that has no > noticeable gaps > > when restarting a loop? Will I need a breadboard, HAT? The motion > sensor > > will be 30 inches away from the Raspberry pi and mounted onto a piece > of > > wood. > > 3. I have not been able to find a tutorial video on how to code my > > Raspberry to do what I need it to do. Do you have any recommendations? > > 4. Can you please make a tutorial video to do what I am trying to do? > > > > Thank you > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > > This library looks promising. This is a python programming list. You > may want to do some research at raspberrypi.org > > https://pypi.org/project/ffpyplayer/ > -- > Joel Goldstick > http://joelgoldstick.com/blog > http://cc-baseballstats.info/stats/birthdays > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From alan.gauld at yahoo.co.uk Tue Aug 11 12:31:52 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 11 Aug 2020 17:31:52 +0100 Subject: [Tutor] Fwd: Re: Is it possible to make a Raspberry do what I need it to do? References: Message-ID: On 11/08/2020 04:03, Jack Funkinstain wrote: > Can you please help me with my raspberry project We can help with the Python bits but this is not a Raspberry forum so we can offer limited help on that side (although a few of us do dabble with Pis) > For my project I need to make a Raspberry Pi Play an HD 1080 video on start > up/boot/ in full screen. The video will be roughly 15 minutes long and will > play in a loop. It is very important that there is not a blank screen or > any visual or audio gaps when the loop starts over (I have heard that some > media player program have a noticeable delay between the end and the start > of a loop). Its possible but you will need to find the right player, its not really a Python issue. Python can launch the player and the video. But frankly you could just use the bash shell to do that, no Python needed. And if you can find a command-line player that offers a loop feature with good command line options you should be good to go without any coding as such. mplayer is the one that I'm familiar with but there are several others. > The video needs to load/start with the volume all the way down, I'm not sure about the CLI options for the sound. > then have a motion sensor trigger an automation of the volume parameter on > the media player program to gradually go up/fade in to a set volume level > (most likely full volume). The volume then needs to stay at a > fixed/consistent level while the person is in front of the sensor. Then > when the person leaves, the sensor triggers the automation of the volume > parameter to gradually go down/fade out. If a person triggers the motion > sensor before the volume reaches 0, I want the volume parameter to increase > from the point it left off rather than start from 0. I will also need to > install a power button. OK, Now this is definitely into Python territory. Reading the motion sensor is going to be Pi/sensor specific but then controlling the volume is Python. You just need to find a player that either has a programmable interface or some kind of CLI interface while the app is running. > I will not be using the raspberry pi as a desktop computer. OK, Thats not a problem. > Questions I have. > > 1. The Raspberry pi will be in non-stop use for hours, maybe days. I > read that people have used raspberry?s in video art galleries for up to 4 > days without over heating problems. This will depend on the exact Pi model you use. There are devices designed to be used 24x7 and that would be your best bet. > ...Will 2GB of ram be enough for my project? For sure > the Raspberry Pi 3 model A+ get less hot and therefore better suited for my You need a Pi forum for that I suspect > project? Is a 16gb micro sd card enough? Depends on the size of the video file but I run Linux on a 4GB card with no problems and space for all the data files i need. > 2. Is what I am trying to do even possible on a raspberry pi ? Definitely. In the worst case you might have to write your own video player but the libraries to do that are available. For your very specific needs it should be doable. > not been able to find any tutorial about automating software parameter > changes. Can you recommend any software to use for the automation? It all depends on the application. For command-line control you should read the subprocess module documents - they have lots of examples. But the best option is if the app has a programmable API, especially if it has a Python library. The Pi forums are probably the best place to ask about that. > there are several different media player programs you can download to use > as a video looper but can you recommend the one that has no noticeable gaps > when restarting a loop? You;ll need to research that yourself, ideally with the actual video file you will be using. You might have to edit the file to ensure it has no gaps too. > Will I need a breadboard, HAT? The motion sensor > will be 30 inches away from the Raspberry pi and mounted onto a piece of > wood. It depends on the motion sensor. I suspect a HAT will be the minimum. > 3. I have not been able to find a tutorial video on how to code my > Raspberry to do what I need it to do. Do you have any recommendations? Once you can read the sensor the rest should be pretty standard Python coding. We can help with that. Any Python tutorial should get you started, but there are a few Pi specific ones that would suit you best. I don't know enough about them to recommend one over another. > 4. Can you please make a tutorial video to do what I am trying to do? Nope, it's not what this forum does - we answer questions about Python. Also it's too specific to your project/sensor/player. Without knowing which models of each you are using a video would be useless. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From sheilamocallaghan at gmail.com Tue Aug 11 13:15:34 2020 From: sheilamocallaghan at gmail.com (Nanogram32) Date: Tue, 11 Aug 2020 10:15:34 -0700 Subject: [Tutor] Navigation Problem Message-ID: Adobe gave this instruction for the purpose of changing Adobe ID; "Navigate to /Users/Library/Application Support/Adobe//Digital Editions/ and drag the activation.dat to trash.? When I get to library from command line I can ls and find Application Support but when I try and open I get message ?No such file?. I can ?open other files in Library but not Application Support. Have been trying for days. Grateful for help. Best Wishes, Nanogram32 From alan.gauld at yahoo.co.uk Tue Aug 11 15:10:04 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 11 Aug 2020 20:10:04 +0100 Subject: [Tutor] Navigation Problem In-Reply-To: References: Message-ID: On 11/08/2020 18:15, Nanogram32 wrote: > Adobe gave this instruction for the purpose of changing Adobe ID; > > "Navigate to /Users/Library/Application Support/Adobe//Digital Editions/ > and drag the activation.dat to trash.? > > When I get to library from command line I can ls and find Application > Support but when I try and open I get message ?No such file?. > > I can ?open other files in Library but not Application Support. > > Have been trying for days. Grateful for help. You do understand that you are posting this on a Python programming forum right? There is nothing about python here? It sounds like you are on a Mac? And for some reason are using the Terminal instead of the Finder, is that right? When you say you try to "open" it, how are you doing that? Can you show us your exact command line(pasted not a screen grab) and error message? Are you putting quotes around the folder name: cd "Application Support" for example? But it would be easier to just use the Finder, which is obviously what the Adobe instructions assume you are using... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From david at graniteweb.com Tue Aug 11 17:06:29 2020 From: david at graniteweb.com (David Rock) Date: Tue, 11 Aug 2020 16:06:29 -0500 Subject: [Tutor] Navigation Problem In-Reply-To: References: Message-ID: <3D6F1667-AA0F-431D-9D17-0765FA987268@graniteweb.com> > On Aug 11, 2020, at 14:10, Alan Gauld via Tutor wrote: > > On 11/08/2020 18:15, Nanogram32 wrote: >> Adobe gave this instruction for the purpose of changing Adobe ID; >> >> "Navigate to /Users/Library/Application Support/Adobe//Digital Editions/ >> and drag the activation.dat to trash.? >> >> When I get to library from command line I can ls and find Application >> Support but when I try and open I get message ?No such file?. >> >> I can open other files in Library but not Application Support. >> >> Have been trying for days. Grateful for help. > > You do understand that you are posting this on a Python programming > forum right? There is nothing about python here? > > It sounds like you are on a Mac? And for some reason are using the > Terminal instead of the Finder, is that right? He?s probably using the terminal because Library is hidden by default in Finder. The path described is also likely not a copy/paste of the instructions; there is no such thing as ?/Users/Library/..? it?s either the main Library off the / (i.e., /Library) or the Library inside each individual User folder (eg, /Users//Library. The second option is more likely in this case. Try accessing it this way: 1. Open Finder 2. hit Command+Shift+G (or use the Menu: Go->Go to Folder?) and type in the path you want to open (eg. /Users//Library/Application Support) Alternatively, 1. Open Finder 2. Open the Go menu 3. While holding down the Option key, click Library (it will become visible while the Option key is held down) 4. Navigate as usual ? David Rock david at graniteweb.com From alan.gauld at yahoo.co.uk Tue Aug 11 19:23:42 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 12 Aug 2020 00:23:42 +0100 Subject: [Tutor] Fwd: Re: Navigation Problem In-Reply-To: References: Message-ID: <11b1c8f2-3b6a-443a-fefa-70ea5bee5ea2@yahoo.co.uk> Forwarding to list. Please use replyAll or replyList when responding to list emails. -------------------------- Hi Alan, ? ? ?Thank you so much for your reply. Yes, I understand this is a Python Forum. There are two issues, both involving the terminal and the path to files on the desktop, etc. The first issue with Adobe involved a problem with downloading Avid Manuals to Adobe Digital Reader. We never did get to open the activation.dat; we took another route. An Adobe engineer spent weeks with me and we finally got the downloads working. ? ? ?The second terminal problem involves opening python files in the MacBook Air terminal. The path I used is cd Desktop/ExerciseFiles/Chapo1-I get ?no such file? although when I ?ls? the file I can see the the python program I am trying to access. I finally installed the IDE Visual Studio Code and was able to get to the file through ?open folder? and successfully run the python program. ???? I am taking a Python course at Los Angeles City College this Fall. I am a film/Avid editor interested in Cyber Security. I have just one class of the 10 required and I will receive an A.S. in Cyber Security. That class is Python. Needless to say, all this is new and not my forte. I downloaded the latest version of python 3.8.5. ? ? ?I certainly understand that my dilemma is elementary; and the path will open up as I go along. I include my r?sum? with the required courses. ? ? ?Again, thanks so much for taking the time. ? Best Wishes, ? Sheila O?Callaghan Sent from my iDunno > On Aug 11, 2020, at 12:55 PM, Sheila O'Callaghan > wrote: > From grunfelderic at gmail.com Tue Aug 11 15:27:13 2020 From: grunfelderic at gmail.com (eric grunfeld) Date: Tue, 11 Aug 2020 15:27:13 -0400 Subject: [Tutor] Outstanding Python Issue Message-ID: Hello Everyone: I have been having some issues with this function in Python: Here it is: def convert_distance(miles): km = miles * 1.6 # approximately 1.6 km in 1 mile return km my_trip_miles = 55 This has been the response: Error on line 4: return km ^ SyntaxError: 'return' outside function Because I am new to Python programming, I am sure that there is an easy solution. I look forward to your thoughts/comments about this. All the best, Eric From chris_roysmith at internode.on.net Tue Aug 11 19:46:22 2020 From: chris_roysmith at internode.on.net (Chris Roy-Smith) Date: Wed, 12 Aug 2020 09:46:22 +1000 Subject: [Tutor] importing from PIL Message-ID: <9b1dcb2d-5b95-b13c-c09a-67c43a216bad@internode.on.net> Hi Ubuntu 18.04 python3.8 under these conditions I get >>> from PIL import Image Traceback (most recent call last): File "", line 1, in File "/usr/lib/python3/dist-packages/PIL/Image.py", line 60, in from . import _imaging as core ImportError: cannot import name '_imaging' from 'PIL' (/usr/lib/python3/dist-packages/PIL/__init__.py) If I do the same in python 3.6 on the same computer, this command does not raise an error. How do I proceed from here? regards, Chris Roy-Smith From david at graniteweb.com Tue Aug 11 20:06:37 2020 From: david at graniteweb.com (David Rock) Date: Tue, 11 Aug 2020 19:06:37 -0500 Subject: [Tutor] Outstanding Python Issue In-Reply-To: References: Message-ID: > On Aug 11, 2020, at 14:27, eric grunfeld wrote: > > Hello Everyone: > > I have been having some issues with this function in Python: > > Here it is: > > def convert_distance(miles): > km = miles * 1.6 # approximately 1.6 km in 1 mile > return km > > my_trip_miles = 55 > > This has been the response: > > Error on line 4: return km ^ SyntaxError: 'return' outside function > Because I am new to Python programming, I am sure that there is an easy > solution. Hi, Eric. It?s because Python uses leading whitespace indentation to tell where code blocks begin and end. Your return statement is outdented, so it?s not part of the function. You need to indent it so it?s the same depth as the km = miles * 1.6 line so it?s ?inside? the function. ? David Rock david at graniteweb.com From meherkp at gmail.com Tue Aug 11 20:21:38 2020 From: meherkp at gmail.com (Meher Kolli) Date: Tue, 11 Aug 2020 17:21:38 -0700 Subject: [Tutor] Outstanding Python Issue In-Reply-To: References: Message-ID: The return statement should be inside the def Meher On Tue, Aug 11, 2020 at 4:27 PM eric grunfeld wrote: > Hello Everyone: > > I have been having some issues with this function in Python: > > Here it is: > > def convert_distance(miles): > km = miles * 1.6 # approximately 1.6 km in 1 mile > return km > > my_trip_miles = 55 > > This has been the response: > > Error on line 4: return km ^ SyntaxError: 'return' outside function > Because I am new to Python programming, I am sure that there is an easy > solution. > > I look forward to your thoughts/comments about this. > > All the best, > Eric > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Meher Kolli From alan.gauld at yahoo.co.uk Tue Aug 11 20:44:46 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 12 Aug 2020 01:44:46 +0100 Subject: [Tutor] importing from PIL In-Reply-To: <9b1dcb2d-5b95-b13c-c09a-67c43a216bad@internode.on.net> References: <9b1dcb2d-5b95-b13c-c09a-67c43a216bad@internode.on.net> Message-ID: On 12/08/2020 00:46, Chris Roy-Smith wrote: > Hi > Ubuntu 18.04 > python3.8 > > under these conditions I get > > >>> from PIL import Image > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python3/dist-packages/PIL/Image.py", line 60, in > from . import _imaging as core > ImportError: cannot import name '_imaging' from 'PIL' > (/usr/lib/python3/dist-packages/PIL/__init__.py) > > If I do the same in python 3.6 on the same computer, this command does > not raise an error. > > How do I proceed from here? Are you sure your version of Pillow is compatible with 3.8? PIL/Pilow has a long tradition of being a release or two behind the bleeding edge. (One reason I usually leave a couple of releases before upgrading...) Is there a reason you upgraded to 3.8? Is there anything in it that you need that isn't in 3.6? Or is there an updated PIL/Pillow that works with 3.8? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From chris_roysmith at internode.on.net Tue Aug 11 22:31:12 2020 From: chris_roysmith at internode.on.net (Chris Roy-Smith) Date: Wed, 12 Aug 2020 12:31:12 +1000 Subject: [Tutor] importing from PIL In-Reply-To: References: <9b1dcb2d-5b95-b13c-c09a-67c43a216bad@internode.on.net> Message-ID: On 12/8/20 10:44 am, Alan Gauld via Tutor wrote: > On 12/08/2020 00:46, Chris Roy-Smith wrote: >> Hi >> Ubuntu 18.04 >> python3.8 >> >> under these conditions I get >> >> >>> from PIL import Image >> Traceback (most recent call last): >> File "", line 1, in >> File "/usr/lib/python3/dist-packages/PIL/Image.py", line 60, in >> from . import _imaging as core >> ImportError: cannot import name '_imaging' from 'PIL' >> (/usr/lib/python3/dist-packages/PIL/__init__.py) >> >> If I do the same in python 3.6 on the same computer, this command does >> not raise an error. >> >> How do I proceed from here? > > > Are you sure your version of Pillow is compatible with 3.8? > PIL/Pilow has a long tradition of being a release or two behind > the bleeding edge. (One reason I usually leave a couple of > releases before upgrading...) > > Is there a reason you upgraded to 3.8? Is there anything in > it that you need that isn't in 3.6? > Thanks Alan, I wasn't aware of that. I am trying to debug some code which which was to live on a windows box (I don't run windows) which has 3.8.x installed, and complains along the same lines. I use Python 3.6.x on my machine. I installed 3.8.x along side to try and debug. I prefer to work under Linux. > Or is there an updated PIL/Pillow that works with 3.8? > Synaptic (package manager) doesn't show other Pillow packages (for 3.8) as opposed to 3.6. I think it might be simpler to "downgrade" the windows box to Python 3.6.x. I know that the code works well that way. Regards, Chris Roy-Smith From alan.gauld at yahoo.co.uk Tue Aug 11 22:45:26 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 12 Aug 2020 03:45:26 +0100 Subject: [Tutor] importing from PIL In-Reply-To: References: <9b1dcb2d-5b95-b13c-c09a-67c43a216bad@internode.on.net> Message-ID: On 12/08/2020 03:31, Chris Roy-Smith wrote: > Synaptic (package manager) doesn't show other Pillow packages (for 3.8) > as opposed to 3.6. I'd check the Pillow home page, the packages are not always as well aligned with versions as they should be. > I think it might be simpler to "downgrade" the windows box to Python > 3.6.x. I know that the code works well that way. Python 3.6 code should work fine on 3.8. It's only the other way round you'd potentially have issues. Unless 3.8 breaks importing rules from 3.6.. I don't know I only upgraded to 3.7 last month, I'm a long way from even considering 3.8... I think... I tell a lie, Mint 20 appears to install 3.8 and I upgraded Mint to v20 last week to try and fix a long term Cinnamon issue. So I've been inadvertently running 3.8 for a week! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From PyTutor at DancesWithMice.info Tue Aug 11 22:59:59 2020 From: PyTutor at DancesWithMice.info (dn) Date: Wed, 12 Aug 2020 14:59:59 +1200 Subject: [Tutor] importing from PIL In-Reply-To: References: <9b1dcb2d-5b95-b13c-c09a-67c43a216bad@internode.on.net> Message-ID: On 12/08/2020 14:31, Chris Roy-Smith wrote: > On 12/8/20 10:44 am, Alan Gauld via Tutor wrote: >> On 12/08/2020 00:46, Chris Roy-Smith wrote: >>> Hi >>> Ubuntu 18.04 >>> python3.8 >>> >>> under these conditions I get >>> >>> ? >>> from PIL import Image >>> Traceback (most recent call last): >>> ??? File "", line 1, in >>> ??? File "/usr/lib/python3/dist-packages/PIL/Image.py", line 60, in >>> >>> ????? from . import _imaging as core >>> ImportError: cannot import name '_imaging' from 'PIL' >>> (/usr/lib/python3/dist-packages/PIL/__init__.py) >>> >>> If I do the same in python 3.6 on the same computer, this command does >>> not raise an error. >>> >>> How do I proceed from here? >> >> >> Are you sure your version of Pillow is compatible with 3.8? >> PIL/Pilow has a long tradition of being a release or two behind >> the bleeding edge. (One reason I usually leave a couple of >> releases before upgrading...) >> >> Is there a reason you upgraded to 3.8? Is there anything in >> it that you need that isn't in 3.6? >> > Thanks Alan, > I wasn't aware of that. I am trying to debug some code which which was > to live on a windows box (I don't run windows) which has 3.8.x > installed, and complains along the same lines. I use Python 3.6.x on my > machine. I installed 3.8.x along side to try and debug. I prefer to work > under Linux. > >> Or is there an updated PIL/Pillow that works with 3.8? >> > Synaptic (package manager) doesn't show other Pillow packages (for 3.8) > as opposed to 3.6. > I think it might be simpler to "downgrade" the windows box to Python > 3.6.x. I know that the code works well that way. Further to similar conversation on Python-List yesterday: please review Installation (https://pillow.readthedocs.io/en/stable/installation.html) to ascertain which versions of pillow are compatible with which versions of Python 3.n... Further advice: use pip3 to download separately for each OpSys/Python version-combination (cf downloading once and sharing between machines). -- Regards =dn From abishekmugunthan29 at gmail.com Tue Aug 11 19:46:13 2020 From: abishekmugunthan29 at gmail.com (abishek mugunthan) Date: Tue, 11 Aug 2020 16:46:13 -0700 Subject: [Tutor] Outstanding Python Issue In-Reply-To: References: Message-ID: Hi Eric The return should be indented to be within the function block Thanks and Regards Abishek On Tue, Aug 11, 2020, 4:27 PM eric grunfeld wrote: > Hello Everyone: > > I have been having some issues with this function in Python: > > Here it is: > > def convert_distance(miles): > km = miles * 1.6 # approximately 1.6 km in 1 mile > return km > > my_trip_miles = 55 > > This has been the response: > > Error on line 4: return km ^ SyntaxError: 'return' outside function > Because I am new to Python programming, I am sure that there is an easy > solution. > > I look forward to your thoughts/comments about this. > > All the best, > Eric > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From breamoreboy at gmail.com Tue Aug 11 19:39:51 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Wed, 12 Aug 2020 00:39:51 +0100 Subject: [Tutor] Outstanding Python Issue In-Reply-To: References: Message-ID: On 11/08/2020 20:27, eric grunfeld wrote: > Hello Everyone: > > I have been having some issues with this function in Python: > > Here it is: > > def convert_distance(miles): > km = miles * 1.6 # approximately 1.6 km in 1 mile > return km > > my_trip_miles = 55 > > This has been the response: > > Error on line 4: return km ^ SyntaxError: 'return' outside function > Because I am new to Python programming, I am sure that there is an easy > solution. > > I look forward to your thoughts/comments about this. > > All the best, > Eric > It's exactly as the SyntaxError says, your 'return' is outside the function. Remember that indentation matters in Python, so just line the 'return' up with the line above and Bob's your uncle :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From PyTutor at DancesWithMice.info Tue Aug 11 23:40:53 2020 From: PyTutor at DancesWithMice.info (dn) Date: Wed, 12 Aug 2020 15:40:53 +1200 Subject: [Tutor] Fwd: Re: Is it possible to make a Raspberry do what I need it to do? In-Reply-To: References: Message-ID: On 12/08/2020 04:31, Alan Gauld via Tutor wrote: > On 11/08/2020 04:03, Jack Funkinstain wrote: > >> Can you please help me with my raspberry project > > We can help with the Python bits but this is not a Raspberry forum > so we can offer limited help on that side (although a few of > us do dabble with Pis) Am agreeing with @Alan about Python/Pi distinctions. Remember also (apologies for having my non-Python 'hat' on) that it is relatively straightforward to use HTML5, both to monitor a camera and to play a video. Thus, the RPi will only need to run a web browser - in what is called "Kiosk mode". -- Regards =dn From chris_roysmith at internode.on.net Wed Aug 12 01:28:03 2020 From: chris_roysmith at internode.on.net (Chris Roy-Smith) Date: Wed, 12 Aug 2020 15:28:03 +1000 Subject: [Tutor] importing from PIL In-Reply-To: References: <9b1dcb2d-5b95-b13c-c09a-67c43a216bad@internode.on.net> Message-ID: <0cf4bcff-9954-dfae-ffe8-743a131a3665@internode.on.net> On 12/8/20 12:45 pm, Alan Gauld via Tutor wrote: > On 12/08/2020 03:31, Chris Roy-Smith wrote: > >> Synaptic (package manager) doesn't show other Pillow packages (for 3.8) >> as opposed to 3.6. > > I'd check the Pillow home page, the packages are not always as well > aligned with versions as they should be. > >> I think it might be simpler to "downgrade" the windows box to Python >> 3.6.x. I know that the code works well that way. > > Python 3.6 code should work fine on 3.8. > It's only the other way round you'd potentially have issues. > > Unless 3.8 breaks importing rules from 3.6.. I don't know I only > upgraded to 3.7 last month, I'm a long way from even > considering 3.8... I think... > > I tell a lie, Mint 20 appears to install 3.8 and I upgraded > Mint to v20 last week to try and fix a long term Cinnamon issue. > So I've been inadvertently running 3.8 for a week! :-) > Down grading to 3.6.3 fixed all problems in Linux and Windows ;) From alan.gauld at yahoo.co.uk Wed Aug 12 04:29:31 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 12 Aug 2020 09:29:31 +0100 Subject: [Tutor] Fwd: Re: Is it possible to make a Raspberry do what I need it to do? In-Reply-To: References: Message-ID: On 12/08/2020 04:40, dn via Tutor wrote: > play a video. Thus, the RPi will only need to run a web browser - in > what is called "Kiosk mode". Plus the software that turns the sound up/down when there is somebody actually watching it - the motion detector stuff. That's really where Python is needed. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From PyTutor at DancesWithMice.info Wed Aug 12 04:49:44 2020 From: PyTutor at DancesWithMice.info (dn) Date: Wed, 12 Aug 2020 20:49:44 +1200 Subject: [Tutor] Fwd: Re: Is it possible to make a Raspberry do what I need it to do? In-Reply-To: References: Message-ID: <1dc78e6b-3512-5aca-c457-3eda3e49c753@DancesWithMice.info> On 12/08/2020 20:29, Alan Gauld via Tutor wrote: > On 12/08/2020 04:40, dn via Tutor wrote: > >> play a video. Thus, the RPi will only need to run a web browser - in >> what is called "Kiosk mode". > > Plus the software that turns the sound up/down when there is > somebody actually watching it - the motion detector stuff. > That's really where Python is needed. I'd like to use Python within-the-browser - even if it has to be through a Python-to-JavaScript transpiler. (heard of one/them, but never tried to use) However, the motion-detector is not strictly necessary. A simple camera and slow-scan software will take care of the presence/absence question by frame-comparison. OT/$day job: advances in HTML5 often surprise! Both the video playback and camera input are covered in the Intermediate and Advanced HTML courses, and possibly progressed (according to trainee-interest) in JS training. In contemplation, the OP's spec has the makings of a good master-class or capstone project... -- Regards =dn From ireneprajay at gmail.com Tue Aug 11 23:10:21 2020 From: ireneprajay at gmail.com (Baptista Albert) Date: Tue, 11 Aug 2020 22:10:21 -0500 Subject: [Tutor] Logic help Message-ID: Hello everyone, I have been assigned a simple task of connecting to an API and show the details of a specific country when selected from a dropdown list in the UI. I am completely new to coding but have learnt to work with python. I was thinking about connecting the Api, converting into Json file and load a list from the json file and then display it in the UI with Tkinter. Is there any other way to do this? Thanks in advance Baptista Albert From alan.gauld at yahoo.co.uk Wed Aug 12 05:40:23 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 12 Aug 2020 10:40:23 +0100 Subject: [Tutor] Logic help In-Reply-To: References: Message-ID: On 12/08/2020 04:10, Baptista Albert wrote: > I was thinking about connecting the Api, converting into Json file and load > a list from the json file and then display it in the UI with Tkinter. Why do you need the JSON file? Why not take whatever the API gives you and display it directly in Tkinter? Files are normally used for storage or transmission between machines. JSON is normally used as a common format between different environments (Javascript/Java/Python/Ruby/text-editing etc) In your case I don't see a need for either a file or JSON. But we'd need to know more about your API to know for sure. What kind of data do you get back? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From manpritsinghece at gmail.com Wed Aug 12 05:38:43 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Wed, 12 Aug 2020 15:08:43 +0530 Subject: [Tutor] Assignment of an object to a target list Message-ID: Dear all, I have an iterable of three elements . i want to assign first value of the iterable to name a, second value to name b and third value to name c . Just need to know that the following examples are correct usage or not. a, b, c = ["A", "B", "C"] # List is an iterable, will assign "A" to name a , "B" to name b, "C" to name c. a, b, c = ("A", "B", "C") # Tuple is also iterable , will assign "A" to name a , "B" to name b, "C" to name c. a, b, c = {"A", "B", "C"} # Set as iterable, will assign "A" to name a , "B" to name b, "C" to name c. a, b, c = range(3) # range as an iterable, will assign 0 to name a , 1 to name b, 2 to name c. a, b, c = {"A":1, "B":2, "C":3} # Dict as iterable, will assign "A" to name a , "B" to name b, "C" to name c. a, b, c = (i for i in range(1, 7) if (i/2).is_integer()) # Generator expression(that returns an iterator) , will assign 2 to name a , 4 to name b, 6 to name c. a, b, c = "ABC" # Strings are iterables, will assign "A" to name a , "B" to name b, "C" to name c. Regards Manprit Singh From alan.gauld at yahoo.co.uk Wed Aug 12 09:08:45 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 12 Aug 2020 14:08:45 +0100 Subject: [Tutor] Assignment of an object to a target list In-Reply-To: References: Message-ID: On 12/08/2020 10:38, Manprit Singh wrote: > Just need to know that the following examples are correct usage or not. The easiest way is to try them in the interpreter - its why its there. >>> a, b, c = ["A", "B", "C"] >>> a,b,c ('A', 'B', 'C') >>> a, b, c = ("A", "B", "C") >>> a,b,c ('A', 'B', 'C') >>> a, b, c = {"A", "B", "C"} >>> a,b,c ('A', 'C', 'B') <------ Note ORDER >>> a, b, c = range(3) >>> a,b,c (0, 1, 2) >>> a, b, c = {"A":1, "B":2, "C":3} >>> a,b,c ('A', 'B', 'C') >>> a, b, c = "ABC" >>> a,b,c ('A', 'B', 'C') >>> The only oddity is the set because sets are not ordered. So you may not get the order that you expect. Also true of dicts in older versions of Python (<3.6?) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Wed Aug 12 12:09:07 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 12 Aug 2020 17:09:07 +0100 Subject: [Tutor] Fwd: Re: Logic help In-Reply-To: References: Message-ID: <296d4ba7-b751-1a9e-c801-1097384fb881@yahoo.co.uk> Forwarding to list. On 12/08/2020 15:33, Baptista Albert wrote: > The data I get back has too much information about a specific country ( > area, longitude, latitude, borders etc), I only have to display few of > the key value pairs like (name, population, currency and language). This > was the reason I tried to use the json file But if you have key/value pairs why not just load them into a Python dictionary and then use them from there? Only store the ones you care about. Converting to a JSON file means converting to text, putting it in a file then to read it back you have to scan the file to read it back. That's super slow compared to just looking up a python dictionary. The only value in a JSON file might be if the API returns its data in the form of a JSON string, but even then parsing it into a dict makes more sense than storing the file (c you only do it once). > Do you need to see my code and the data?? That's always helpful, but we should also see what documentation you have on the API. Is it short or do you have a web link you can share? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From grunfelderic at gmail.com Wed Aug 12 12:39:55 2020 From: grunfelderic at gmail.com (eric grunfeld) Date: Wed, 12 Aug 2020 12:39:55 -0400 Subject: [Tutor] Question on If/Elif Statement in Python Message-ID: Good Afternoon Everyone: I am running a basic If/Elif program/statement in Python. I wanted to get your thoughts if I am running this correctly (I always seem to have issues with indentation, since I am new to programming Python) Here it is: def number_group(number): if number > 0: return "Positive" elif number < 0: return "Negative" else: return "Zero" print(number_group(10)) #Should be Positive print(number_group(0)) #Should be Zero print(number_group(-5)) #Should be Negative I look forward to your feedback/thoughts on this. All the best, Eric From alan.gauld at yahoo.co.uk Wed Aug 12 18:38:20 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 12 Aug 2020 23:38:20 +0100 Subject: [Tutor] Question on If/Elif Statement in Python In-Reply-To: References: Message-ID: On 12/08/2020 17:39, eric grunfeld wrote: > I wanted to get your thoughts if I am running this correctly (I always seem > to have issues with indentation, since I am new to programming Python) Terminology is very important in programming. You ask if you are "running" it correctly. That means you asking us if you are executing the program correctly. But you don't tell us how you run it. I'm going to assume for now you want to know if you are writing the code correctly. ie if the layout is sensible. The answer is yes, it all looks fine. You should have gotten the correct answers when you did run it. > def number_group(number): > if number > 0: > return "Positive" > elif number < 0: > return "Negative" > else: > return "Zero" > > print(number_group(10)) #Should be Positive > print(number_group(0)) #Should be Zero > print(number_group(-5)) #Should be Negative -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From cs at cskk.id.au Wed Aug 12 19:18:42 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Thu, 13 Aug 2020 09:18:42 +1000 Subject: [Tutor] Fwd: Re: Navigation Problem In-Reply-To: References: Message-ID: <20200812231842.GA43761@cskk.homeip.net> On 12Aug2020 13:09, Dennis Lee Bieber wrote: > If the file you are trying to access has spaces in the name (you > never >tell us the full name), you probably have to wrap it in quotes (I don't >know if Mac uses " or ' for this purpose). Otherwise it will see your >command as having two or more arguments... The default Mac shell is a Bourne shell. Bash has been the default login shell until recently, when they switched the default (for new accounts, obviously) to zsh. As a zsh user, I laud this decision! Anyway, normal Bourne shell quoting is the go. So usually you'd use single quotes (because double quotes expand $ and `). Both bash and zsh had TAB completion too, so the OP should be able to cd into the directory as described and go "python foo" to expand the filename starting with foo, which will correctly quote the expansion if needed and either bash or zsh. Cheers, Cameron Simpson From manpritsinghece at gmail.com Thu Aug 13 01:15:34 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Thu, 13 Aug 2020 10:45:34 +0530 Subject: [Tutor] Use of underscore(_) in place of a variable in target list of for statement Message-ID: Dear sir , Consider a problem where i have to display first ten fibonacci numbers . if i write a code like this, a, b = 0, 1 for _ in range(10): print(a) a, b = b, a+b This gives the result , but my question is the use of underscore (_) in place of a variable in target list of the for statement . Need your comments on the use of this underscore . Use of underscore in such situations (where the variable in target list of for statement is not really needed, as it is not being used inside the block of for loop, i only have to execute the block n times , in the example above it is 10 times.), should be preferred or not . Another alternate is to use while loop like this : a, b = 0, 1 i = 0 while i < 10: print(a) a, b = b, a+b i = i+1 What should be preferred in such cases , a for loop with underscore in variable list or a while loop as given above? Which practise adheres to PEP 8 and is more cleaner and readable approach to solve such kind of problems. Regards Manprit singh From alan.gauld at yahoo.co.uk Thu Aug 13 04:54:13 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 13 Aug 2020 09:54:13 +0100 Subject: [Tutor] Use of underscore(_) in place of a variable in target list of for statement In-Reply-To: References: Message-ID: On 13/08/2020 06:15, Manprit Singh wrote: > a, b = 0, 1 > for _ in range(10): > print(a) > a, b = b, a+b > > comments on the use of this underscore . This is quite a common Python idiom, I use it occasionally but mostly I just use a single-letter variable that never gets used. Some argue that introducing an extra name adds complexity, others feel that the _ is equally complex for readers who may not be familiar with the idiom. Either works, there is no difference in the code as far as Python is concerned. > Another alternate is to use while loop like this : > a, b = 0, 1 > i = 0 > while i < 10: ... > What should be preferred in such cases I'd argue that a while loop is intended for indeterminate numbers of loops. When you know how many loops you need (or may need - break etc) you should use a for loop. At the end of the day it is all about making the code clearly express your intentions. If you are iterating over a sequence or you know how many repetitions you need, use a for loop. If you need to repeat until some condition is true (or forever), use a while 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 From mats at wichmann.us Thu Aug 13 08:52:12 2020 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 13 Aug 2020 06:52:12 -0600 Subject: [Tutor] Use of underscore(_) in place of a variable in target list of for statement In-Reply-To: References: Message-ID: <6fffb603-a251-9474-77c1-6fdd5e7a98c0@wichmann.us> On 8/13/20 2:54 AM, Alan Gauld via Tutor wrote: > On 13/08/2020 06:15, Manprit Singh wrote: > >> a, b = 0, 1 >> for _ in range(10): >> print(a) >> a, b = b, a+b >> >> comments on the use of this underscore . > > This is quite a common Python idiom, I use it occasionally but > mostly I just use a single-letter variable that never gets used. > Some argue that introducing an extra name adds complexity, > others feel that the _ is equally complex for readers who > may not be familiar with the idiom. Either works, there is > no difference in the code as far as Python is concerned. Just to add: The idiom has become rather a convention: the popular code checkers will interpret it as you signalling that you actually meant to introduce a variable that you're not going to reference, and thus refrain from issuing you a warning about an unused variable. Syntactically, you have to put *something* there in the for statement, so this is the compromise people have settled on. From nathan-tech at hotmail.com Thu Aug 13 08:29:43 2020 From: nathan-tech at hotmail.com (nathan tech) Date: Thu, 13 Aug 2020 13:29:43 +0100 Subject: [Tutor] in a pickle about pickle Message-ID: Hi there, I asked this question on stackoverflow, but realised I'd probably get better answers here and should have have asked here in the first place as the questions are a little bit newbieish. I've done a lot of work with pickle, though only recently come across cPickle which is faster (aparrently). I was wondering though if someone would be able to answer these questions for me though: 1. does pickle.dump(obj, file, protocol) thread itself in any way? 2. When I do something like: pickle.dump(obj, file, 2) the file that is put out is still, mostly, human readable. Is this normal? It talks about bytes in the docs which I took to mean it would not be human readable. Related to this I also wanted to ask is there a way to see what function is hanging a python process? Allow me to explain this further as the obvious answers may not apply: I have a program which has a graphical user interface through wx python. As part of this program it saves data to files using pickle, because they're dictionaries. I could use xml2dict and dict2xml, but cPickle is faster (I think). It executes the saving when you click a button. This occurs, the python program freezes for a second, then goes bacck to the GUI. that's fine, expected behaviour. If I then click exit it returns to the console (expected), and then sometimes will just sit there for about 10 to 15 minutes before finally finishing. I went into task manager and killed the task once, and found that the data files were only half written, which is what leads me to believe it is pickle that is either locking up or taking forever. Annoyingly, since I played around with msgpack, json and then back to cPickle it's not been doing it since, but I have observed this behaviour with another one of my programs too. Is this an issue that comes up often with pickle? I work mostly with python dictionaries when dumping to files, which is why I figured pickle would be the best option. Thanks a lot for any help Nathan From alan.gauld at yahoo.co.uk Thu Aug 13 13:01:40 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 13 Aug 2020 18:01:40 +0100 Subject: [Tutor] in a pickle about pickle In-Reply-To: References: Message-ID: On 13/08/2020 13:29, nathan tech wrote: > 1. does pickle.dump(obj, file, protocol) thread itself in any way? I doubt it. if you need threading that would be up to you. I would hope that it would be thread safe but you should check. > 2. When I do something like: pickle.dump(obj, file, 2) the file that is > put out is still, mostly, human readable. Is this normal? It talks about > bytes in the docs which I took to mean it would not be human readable. bytes are just 8 bit patterns. Most of the commonly text characters are encoded in bytes so if you can read the text you can read it as bytes too. Some binary data will be written as a group of bytes that may or may not be readable. But if you have significant amounts of text in your data then it will be visible as such in your dump. > Related to this I also wanted to ask is there a way to see what function > is hanging a python process? Probably, by using a debugger to attach to the process. But beware hanging does not mean going slow, it means stopped without terminating. very different. If the code is just taking a while to finish then probably the answer is no. > As part of this program it saves data to files using pickle, because > they're dictionaries. I could use xml2dict and dict2xml, but cPickle is > faster (I think). Surely shelves would be even better than pickle since they are effectively dictionaries in a file? In fact you could possibly do away with the dictionaries and access the shelve directly instead... > It executes the saving when you click a button. This occurs, the python > program freezes for a second, then goes bacck to the GUI. that's fine, > expected behaviour. > > If I then click exit it returns to the console (expected), and then > sometimes will just sit there for about 10 to 15 minutes before finally > finishing. That's a very long time to write a file - they are presumably many GB in size? If not something else is going on, possibly a race condition or deadlock within your code. Do you have a lot of complex relationships between your objects for example? > Is this an issue that comes up often with pickle? Nope, certainly not minutes, maybe a second or two. Are you sure you shouldn't be using a database instead? > I work mostly with python dictionaries when dumping to files, which is > why I figured pickle would be the best option. Have you looked at shelve? That potentially avoids the need to write a huge amount of data out at once. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Thu Aug 13 13:30:14 2020 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 Aug 2020 19:30:14 +0200 Subject: [Tutor] Use of underscore(_) in place of a variable in target list of for statement References: Message-ID: Manprit Singh wrote: > Consider a problem where i have to display first ten fibonacci numbers . > if i write a code like this, > > a, b = 0, 1 > for _ in range(10): > print(a) > a, b = b, a+b To go off on a tangent, I usually use a generator in cases like these: def fib(): a, b = 0, 1 while True: yield a a, b = b, a + b Then you don't need a dummy variable, you can limit the infinite sequence with itertools.islice(): from itertools import islice for n in islice(fib(), 10): print(n) From Emily.Schuster at jhuapl.edu Thu Aug 13 13:25:36 2020 From: Emily.Schuster at jhuapl.edu (Schuster, Emily A.) Date: Thu, 13 Aug 2020 17:25:36 +0000 Subject: [Tutor] ModuleNotFound Error Message-ID: Hi Everyone! I?ve been trying to install Pandas onto Anaconda. I?ve installed it using both pip and conda, and whenever I try to reinstall it says that the ?Requirement has already been satisfied?, so I know Pandas is in there somewhere; however, when I try to ?import pandas as pd? in my Python program in IDLE, I get a ModuleNotFoundError: ?pandas? does not exist. Why is python/Anaconda not able to access the Pandas library? Thank you so so much!!! Sincerely, Emily Schuster (917)596-6744 From mats at wichmann.us Thu Aug 13 14:33:16 2020 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 13 Aug 2020 12:33:16 -0600 Subject: [Tutor] ModuleNotFound Error In-Reply-To: References: Message-ID: <7281c80b-46f7-3ed6-09ac-db50e2373ed0@wichmann.us> On 8/13/20 11:25 AM, Schuster, Emily A. wrote: > Hi Everyone! > I?ve been trying to install Pandas onto Anaconda. I?ve installed it using both pip and conda, and whenever I try to reinstall it says that the ?Requirement has already been satisfied?, so I know Pandas is in there somewhere; however, when I try to ?import pandas as pd? in my Python program in IDLE, I get a ModuleNotFoundError: ?pandas? does not exist. Why is python/Anaconda not able to access the Pandas library? We can 100% answer that question: because your paths are wrong. When a module is known to exist, but Python can't import it, Python is looking in the wrong place. Fixing it isn't necessarily as easy as the snap conclusion... In *general*, if installing using the pip module, do so in a way that makes sure to use the same Python that you're going to run (pip-the-standalone-command is associated with *some* Python, but possibly not with the Python you're intending to use). So: python -m pip install pandas as long as the thing you're intending to use is "python" (i.e. adjust this if you're on Windows using the python launcher "py", or on a system where you're trying to call out a specific version like "python3.7") You've introduced two complications which makes it harder to answer from here: - you're using Anaconda, which also has its own installer. Did you use the conda installer? Or did you install using pip? - you're using IDLE, which from my limited experience with Anaconda, may not use Python the same way. Perhaps somebody else can help with that part. If you're inside IDLE's Python window, you can check the module search path like this: >>> import sys >>> sys.path [ .... whole bunch of stuff, those are the places that Python will use to look for what you try to import ] Do you know where your Pandas module went to? If you used pip you can ask this way: pip show pandas From mats at wichmann.us Thu Aug 13 14:41:23 2020 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 13 Aug 2020 12:41:23 -0600 Subject: [Tutor] ModuleNotFound Error In-Reply-To: <7281c80b-46f7-3ed6-09ac-db50e2373ed0@wichmann.us> References: <7281c80b-46f7-3ed6-09ac-db50e2373ed0@wichmann.us> Message-ID: <7288dedc-df4c-9307-2917-a69a027b16c5@wichmann.us> On 8/13/20 12:33 PM, Mats Wichmann wrote: > You've introduced two complications which makes it harder to answer from > here: > > - you're using Anaconda, which also has its own installer. Did you use > the conda installer? Or did you install using pip? > - you're using IDLE, which from my limited experience with Anaconda, may > not use Python the same way. Perhaps somebody else can help with that > part. two complete this thought... if you used conda to install, it probably installed to a Python virtual environment. then when you brought up IDLE, it's not in the context of that virtual environment, activated, and so it doesn't know to look there ("activating" basically means fiddling paths). Which would go a long way to explaining the not found problem. From grunfelderic at gmail.com Thu Aug 13 16:38:43 2020 From: grunfelderic at gmail.com (eric grunfeld) Date: Thu, 13 Aug 2020 16:38:43 -0400 Subject: [Tutor] Question on running a small Python program Message-ID: Good Afternoon Everyone: I have been working on this small program in Python. The underlying point here is that the fractional_part function divides the numerator by the denominator. And then it returns just the fractional part (some number between 0 and 1). I am seeking to complete the body of the function so that it returns the right number However, I have been getting an error message (down below) Here is the code that I have inputted: def fractional_part(numerator, denominator): if denominator != 0 return (numerator % denominator)/denominator print(fractional_part(5, 5)) # Should be 0 print(fractional_part(5, 4)) # Should be 0.25 print(fractional_part(5, 3)) # Should be 0.66... print(fractional_part(5, 2)) # Should be 0.5 print(fractional_part(5, 0)) # Should be 0 print(fractional_part(0, 5)) # Should be 0 This has been my error message: Error on line 4: if denominator != 0 ^ SyntaxError: invalid syntax I look forward to your thoughts on this. Thank you. Eric From joel.goldstick at gmail.com Thu Aug 13 19:17:28 2020 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 13 Aug 2020 19:17:28 -0400 Subject: [Tutor] Question on running a small Python program In-Reply-To: References: Message-ID: On Thu, Aug 13, 2020 at 7:15 PM eric grunfeld wrote: > > Good Afternoon Everyone: > > I have been working on this small program in Python. > > The underlying point here is that the fractional_part function divides the > numerator by the denominator. > > And then it returns just the fractional part (some number between 0 and 1). > > I am seeking to complete the body of the function so that it returns the > right number > > However, I have been getting an error message (down below) > > Here is the code that I have inputted: > > def fractional_part(numerator, denominator): > if denominator != 0 the next line needs to be indented . The previous line needs a : > return (numerator % denominator)/denominator > > print(fractional_part(5, 5)) # Should be 0 > print(fractional_part(5, 4)) # Should be 0.25 > print(fractional_part(5, 3)) # Should be 0.66... > print(fractional_part(5, 2)) # Should be 0.5 > print(fractional_part(5, 0)) # Should be 0 > print(fractional_part(0, 5)) # Should be 0 > > This has been my error message: Error on line 4: if denominator != 0 ^ > SyntaxError: invalid syntax > > I look forward to your thoughts on this. > > Thank you. > Eric > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick http://joelgoldstick.com/blog http://cc-baseballstats.info/stats/birthdays From PyTutor at DancesWithMice.info Thu Aug 13 22:41:48 2020 From: PyTutor at DancesWithMice.info (dn) Date: Fri, 14 Aug 2020 14:41:48 +1200 Subject: [Tutor] Question on running a small Python program In-Reply-To: References: Message-ID: On 14/08/2020 11:17, Joel Goldstick wrote: > On Thu, Aug 13, 2020 at 7:15 PM eric grunfeld wrote: >> I have been working on this small program in Python. ... >> This has been my error message: Error on line 4: if denominator != 0 ^ >> SyntaxError: invalid syntax >> >> I look forward to your thoughts on this. Are you attempting a training course or using a text-book? If so, which one? FYI: Are you aware of the extensive documentation available from https://docs.python.org/3/index.html (which includes a tutorial discussing if-statements as "4. More Control Flow Tools". -- Regards =dn From manpritsinghece at gmail.com Fri Aug 14 00:42:30 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Fri, 14 Aug 2020 10:12:30 +0530 Subject: [Tutor] Pure functions in python - need a glimpse of functional programming and recursive functions . Message-ID: Dear sir , Consider a problem to find nCr . where nCr = fact(n) / (fact(r) * fact(n-r)).where fact(x) is factorial of x. if i write code like this : def fact(x): # Function definition for factorial if x == 0: return 1 else : return x * fact(x-1) def comb(n, k): # Function definition for finding nCr return fact(n) / (fact(k) * fact(n-k)) calling function comb as written below comb(7,2) returns 21.0 # Which is the right answer Just need to know if function comb is a pure function in this particular case or not . I have raised this question because an external function fact has been called inside the function comb 3 times . My second question is, i had never seen any example of recursive functions in python official documentation. Is it ok to use recursive functions in python programming ? Do recursive functions take/ consume more or less resources in comparison to other alternatives in python ? Regards Manprit Singh From alan.gauld at yahoo.co.uk Fri Aug 14 04:09:44 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 14 Aug 2020 09:09:44 +0100 Subject: [Tutor] Pure functions in python - need a glimpse of functional programming and recursive functions . In-Reply-To: References: Message-ID: On 14/08/2020 05:42, Manprit Singh wrote: > def fact(x): > if x == 0: > return 1 > else : > return x * fact(x-1) > > def comb(n, k): > return fact(n) / (fact(k) * fact(n-k)) > comb(7,2) > returns 21.0 > Just need to know if function comb is a pure function in this particular > case or not . I have raised this question because an external function > fact has been called inside the function comb 3 times . According to Wikipedia: ----------------------- In computer programming, a pure function is a function that has the following properties: 1) Its return value is the same for the same arguments (no variation with local static variables, non-local variables, mutable reference arguments or input streams from I/O devices). 2) Its evaluation has no side effects (no mutation of local static variables, non-local variables, mutable reference arguments or I/O streams). ---------------------- Since you don't change state in either of your functions and there is no random variation in the conditions the functions are both pure. > My second question is, i had never seen any example of recursive > functions in python official documentation. Is it ok to use recursive > functions in python programming ? You are looking in the wrong place, a search for "recursion" brings up 81 pages (although quite a few are the same page from different versions!). But its mainly featured under error handling rather than function definition because... > Do recursive functions take/ consume > more or less resources in comparison to other alternatives in python ? While not taking more resources as such, they do have a limitation in that Python has a recursion limit (1000 by default?). This prevents "infinite" recursion consuming all memory. But it does mean that you should only use recursion when you know it will terminate "fairly quickly"). Otherwise you get a RecursionError. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From grunfelderic at gmail.com Fri Aug 14 13:45:56 2020 From: grunfelderic at gmail.com (eric grunfeld) Date: Fri, 14 Aug 2020 13:45:56 -0400 Subject: [Tutor] Python programming question related to Return/Print statement Message-ID: Good Afternoon Everyone: I have been seeking to rectify my mistake in running this program via Python. Here it is: def format_name(first_name, last_name): return "Name " + first_name + ", " + last_name return string print(format_name("Ernest", "Hemingway")) # Should return the string "Name: Hemingway, Ernest" print(format_name("", "Madonna")) # Should return the string "Name: Madonna" print(format_name("Voltaire", "")) # Should return the string "Name: Voltaire" print(format_name("", "")) # Should return an empty string However, after running the program, this has been the response: Incorrect Not quite, format_name('Ernest', 'Hemingway') returned Name Ernest, Hemingway, should be Name: Hemingway, Ernest. It appears to be how I have programmed my return statement. "return "Name " + first_name + ", " + last_name" I look forward to your thoughts or comments that you may have on this matter. All the best, Eric From marshlj20 at gmail.com Fri Aug 14 11:33:15 2020 From: marshlj20 at gmail.com (Marshall Jones) Date: Fri, 14 Aug 2020 16:33:15 +0100 Subject: [Tutor] Help with simple coding Message-ID: Hiya, Spent hours on this, but seem to be getting further from getting it right. money = int(input("how much money would you like to change into coins?")) coins = input("what coins do you want them in") pounds = (money // 1) fifty = (money // 0.5) twenties = (money // 0.2) tens = (money // 0.1) fives = (money // 0.02) twos = (money // 0.05) ones = (money // 0.001) if coins == pounds: print (pounds) and then the same for fifty, twenties etc Many thanks Marshall From Richard at Damon-Family.org Fri Aug 14 14:52:42 2020 From: Richard at Damon-Family.org (Richard Damon) Date: Fri, 14 Aug 2020 14:52:42 -0400 Subject: [Tutor] Help with simple coding In-Reply-To: References: Message-ID: <5a15cb82-7d12-d790-4940-0b455bfe757a@Damon-Family.org> On 8/14/20 11:33 AM, Marshall Jones wrote: > Hiya, > > Spent hours on this, but seem to be getting further from getting it right. > > money = int(input("how much money would you like to change into coins?")) > coins = input("what coins do you want them in") > pounds = (money // 1) > fifty = (money // 0.5) > twenties = (money // 0.2) > tens = (money // 0.1) > fives = (money // 0.02) > twos = (money // 0.05) > ones = (money // 0.001) > if coins == pounds: > print (pounds) > > and then the same for fifty, twenties etc > > Many thanks > > Marshall What sort of value do you expect to be in coins What sort of thing are you comparing it to? -- Richard Damon From mats at wichmann.us Fri Aug 14 14:53:22 2020 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 14 Aug 2020 12:53:22 -0600 Subject: [Tutor] Python programming question related to Return/Print statement In-Reply-To: References: Message-ID: On 8/14/20 11:45 AM, eric grunfeld wrote: > Good Afternoon Everyone: > > I have been seeking to rectify my mistake in running this program via > Python. > > Here it is: > > def format_name(first_name, last_name): > return "Name " + first_name + ", " + last_name > return string the second statement will never be reached, so drop it. > However, after running the program, this has been the response: > Incorrect > > Not quite, format_name('Ernest', 'Hemingway') returned Name > Ernest, Hemingway, should be Name: Hemingway, Ernest. > > It appears to be how I have programmed my return statement. it seems whatever grading tool you're entering this into is expecting a colon after the word Name, so you should include that when you construct the string.... it's possible from what you pasted that it also expected a terminating period. So it appears a question of reading the problem specification very precisely. From alan.gauld at yahoo.co.uk Fri Aug 14 16:34:42 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 14 Aug 2020 21:34:42 +0100 Subject: [Tutor] Python programming question related to Return/Print statement In-Reply-To: References: Message-ID: On 14/08/2020 18:45, eric grunfeld wrote: > def format_name(first_name, last_name): > return "Name " + first_name + ", " + last_name > return string > > print(format_name("Ernest", "Hemingway")) > # Should return the string "Name: Hemingway, Ernest" Look closely at the order of those names. > However, after running the program, this has been the response: > Incorrect > > Not quite, format_name('Ernest', 'Hemingway') returned Name > Ernest, Hemingway, should be Name: Hemingway, Ernest. Its also looking for a colon after Name. So you have two errors to fix. Computers are fussy, you'll need to get used to that if you want to be a programmer. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Fri Aug 14 16:38:09 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 14 Aug 2020 21:38:09 +0100 Subject: [Tutor] Help with simple coding In-Reply-To: References: Message-ID: On 14/08/2020 16:33, Marshall Jones wrote: > Spent hours on this, but seem to be getting further from getting it right. There are a lot of things wrong here. Let's start at the top... > money = int(input("how much money would you like to change into coins?")) > coins = input("what coins do you want them in") input() returns a string, so whatever you get back will be a string. > pounds = (money // 1) > fifty = (money // 0.5) > twenties = (money // 0.2) > tens = (money // 0.1) > fives = (money // 0.02) > twos = (money // 0.05) > ones = (money // 0.001) These values all store integers. > if coins == pounds: You are here comparing a string to an integer eg. if "pounds" == 42 -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From PyTutor at DancesWithMice.info Fri Aug 14 18:53:20 2020 From: PyTutor at DancesWithMice.info (DL Neil) Date: Sat, 15 Aug 2020 10:53:20 +1200 Subject: [Tutor] Question on running a small Python program In-Reply-To: References: Message-ID: <2f1c5edf-23d9-7517-0ab2-186c9b1b3566@DancesWithMice.info> On 15/08/2020 02:27, eric grunfeld wrote: > Thank you DN for getting back to me. > > Yes - I am taking a class that is being conducted by Google through the > Coursera platform > > And appreciate you sharing this Python docs website with me. I am sure > that it will come in handy as I continue to learn Python. One of my (professional) concerns with some of these courses, and it is a particular habit with Google, is to assume that everything will work first-time. You and I both know that is not the way the world works - well not all of the time, some of the time... May I recommend that you read the first three (or so) 'chapters' of the Python Tutorial - as linked from docs URL given earlier. You will likely gain from reading much-the-same-stuff, but written from a slightly different view-point (and it may also 'fill some gaps'!). Thereafter you will establish your own ideas for its use, keeping in-sync with your progress on the Coursera offering... Meantime, addressing the 'hole' in the course material, and to help with the particular difficulties experienced earlier, try: https://www.scalyr.com/blog/python-stack-trace-understanding-using-debug/ (skim the first few paragraphs of 'suit-talk' and concentrate on the 'meat' of how to read error messages and make sense of a "stack trace"). FYI: list-protocol is to ReplyAll/ReplyToList (so that others following the conversation may continue to benefit) and not to top-post (appearing to answer the question before it is asked). -- Regards =dn From PyTutor at DancesWithMice.info Fri Aug 14 19:42:50 2020 From: PyTutor at DancesWithMice.info (dn) Date: Sat, 15 Aug 2020 11:42:50 +1200 Subject: [Tutor] Python programming question related to Return/Print statement In-Reply-To: References: Message-ID: <882d736c-0b7e-1b9e-ead1-cb2b83bc13ba@DancesWithMice.info> On 15/08/2020 05:45, eric grunfeld wrote: > Good Afternoon Everyone: > > I have been seeking to rectify my mistake in running this program via > Python. > > Here it is: > > def format_name(first_name, last_name): > return "Name " + first_name + ", " + last_name > return string There's a cultural divide here. Even in different English-cultures: given-name, fore-name, surname, family-name, etc. (multiply-rapidly when adding other languages and their cultures!) Given your own (email) name, are you familiar with the question's terms: first-name and last-name? > print(format_name("Ernest", "Hemingway")) > # Should return the string "Name: Hemingway, Ernest" Whilst this (is the only thing we can see that) gives a clue, none of the other sample data (reproduced) will help such understanding. > I look forward to your thoughts or comments that you may have on this > matter. It might help (us, to help you) to include (the core of) the course-assignment with a question. Looking at the sample data, the specification *must* (surely) include mention of more than the label, the colon, the two names, and the comma-separator! BTW there is no crime/embarrassment in mentioning that it is a course-assignment. We're happy to help introduce you/others to Python, and the more information you give us, the better we can help your learning-progress! -- Regards =dn From PyTutor at DancesWithMice.info Fri Aug 14 20:02:25 2020 From: PyTutor at DancesWithMice.info (dn) Date: Sat, 15 Aug 2020 12:02:25 +1200 Subject: [Tutor] Help with simple coding In-Reply-To: References: Message-ID: <7dc7b77c-ee98-f094-2363-0237deec88fb@DancesWithMice.info> On 15/08/2020 03:33, Marshall Jones wrote: > Hiya, > > Spent hours on this, but seem to be getting further from getting it right. Define "right"! In another current list-conversation "Python programming question related to Return/Print statement", I've suggested: <<< It might help (us, to help you) to include (the core of) the course-assignment with a question. Looking at the sample data,... BTW there is no crime/embarrassment in mentioning that it is a course-assignment. We're happy to help introduce you/others to Python, and the more information you give us, the better we can help your learning-progress! >>> In this case, an unanswered query relates to the second input() - does this limit which denomination of coins we are 'allowed' to use, or what? (it will be totally ignored for the rest of this discussion) > money = int(input("how much money would you like to change into coins?")) > coins = input("what coins do you want them in") > pounds = (money // 1) > fifty = (money // 0.5) > twenties = (money // 0.2) > tens = (money // 0.1) > fives = (money // 0.02) > twos = (money // 0.05) > ones = (money // 0.001) > if coins == pounds: > print (pounds) > > and then the same for fifty, twenties etc The way to solve any problem is to break the 'large problem' down into 'small problems', and those into ever smaller problems, until the size of the problem is easy for us to solve. (ComSc term: "Stepwise Decomposition") So, imagine you were doing this at your desk or a bank teller's counter. You seem to have the right idea: Step one is to take the amount (to be changed) and calculate how many one-pound notes it will require. Let's use a random amount as an example: ?1.23 How many notes? 1.23 // 1 -> 1. Wow! Now, next problem: how many 50p coins? Do we use the original ?1.23-amount in this calculation? Thus, the next 'problem' is how much do we input into the second (50p) calculation? ...and assuming you've spotted the needed correction, we continue 'down' the list of coins. After a while you'll realise that the 'problem' being solved is virtually repeating itself - the only parts that are changing are the amount-left and the coin-denomination. If you've covered loops and collections, eg lists and/or tuples, then I'll say no more. If you haven't, then these might be included in the next lesson (and assignment)... -- Regards =dn From john at johnweller.co.uk Sat Aug 15 05:27:56 2020 From: john at johnweller.co.uk (John Weller) Date: Sat, 15 Aug 2020 10:27:56 +0100 Subject: [Tutor] Python Learning Resources Message-ID: <002f01d672e6$5d191de0$174b59a0$@johnweller.co.uk> I, too, am learning Python via the internet and the recent posts on learning this way prompted me to post the resources I have found particularly helpful. Top of the list must be this list ?. It provides a backstop knowing that when all else fails I can ask a question here. I have written several emails destined for this list only to discard them when I?ve found that formulating the question actually provides the answer. References I have found useful are: www.w3schools.com/python/ and www.tutorialspoint.com/python/index.htm . They are easier to read than the formal documentation but not as comprehensive. YouTube ? the Socratica series - https://www.youtube.com/watch?v=bY6m6_IIN94 &list=PLi01XoE8jYohWFPpC17Z-wWhPOSuh8Er- and tutorials by Corey Schafer are very clear and easy to follow. Hope this helps some of my fellow learners ? John John Weller 01380 723235 07976 393631 From grunfelderic at gmail.com Sun Aug 16 09:57:26 2020 From: grunfelderic at gmail.com (eric grunfeld) Date: Sun, 16 Aug 2020 09:57:26 -0400 Subject: [Tutor] Python programming question related to Return/Print statement In-Reply-To: <882d736c-0b7e-1b9e-ead1-cb2b83bc13ba@DancesWithMice.info> References: <882d736c-0b7e-1b9e-ead1-cb2b83bc13ba@DancesWithMice.info> Message-ID: Thank you DN for your help on this. And yes this is a course/assignment that I am currently working on. The course is being taught through Google on the Coursera platform. All the best, Eric On Fri, Aug 14, 2020 at 7:43 PM dn via Tutor wrote: > On 15/08/2020 05:45, eric grunfeld wrote: > > Good Afternoon Everyone: > > > > I have been seeking to rectify my mistake in running this program via > > Python. > > > > Here it is: > > > > def format_name(first_name, last_name): > > return "Name " + first_name + ", " + last_name > > return string > > There's a cultural divide here. Even in different English-cultures: > given-name, fore-name, surname, family-name, etc. (multiply-rapidly when > adding other languages and their cultures!) > > Given your own (email) name, are you familiar with the question's terms: > first-name and last-name? > > > > print(format_name("Ernest", "Hemingway")) > > # Should return the string "Name: Hemingway, Ernest" > > Whilst this (is the only thing we can see that) gives a clue, none of > the other sample data (reproduced) will help such understanding. > > > > I look forward to your thoughts or comments that you may have on this > > matter. > It might help (us, to help you) to include (the core of) the > course-assignment with a question. Looking at the sample data, the > specification *must* (surely) include mention of more than the label, > the colon, the two names, and the comma-separator! > > BTW there is no crime/embarrassment in mentioning that it is a > course-assignment. We're happy to help introduce you/others to Python, > and the more information you give us, the better we can help your > learning-progress! > -- > Regards =dn > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From manpritsinghece at gmail.com Sun Aug 16 09:55:33 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sun, 16 Aug 2020 19:25:33 +0530 Subject: [Tutor] use of assignment expression Message-ID: Dear sir , i need a comment on the use of assignment expression in the below given example : # Program to find smallest n digit number divisible by a number x n = 5 x = 83 if (no := (10**(n-1) % x)) == 0: print(10**(n-1)) else: print((mx := (10**(n-1) + x)) - (mx % x)) The answer is 10043, which is the right answer . Just need to know if the way of using the assignment expression (2 times in the above example is efficient or not.), What i feel is the usage of assignment expressions is reducing the readability of the code written above . Need your guidance. Regards Manprit From alan.gauld at yahoo.co.uk Sun Aug 16 18:31:02 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 16 Aug 2020 23:31:02 +0100 Subject: [Tutor] use of assignment expression In-Reply-To: References: Message-ID: On 16/08/2020 14:55, Manprit Singh wrote: > # Program to find smallest n digit number divisible by a number x > n = 5 > x = 83 > if (no := (10**(n-1) % x)) == 0: > print(10**(n-1)) > else: > print((mx := (10**(n-1) + x)) - (mx % x)) > > The answer is 10043, which is the right answer . Just need to know if the > way of using the assignment expression (2 times in the above example is > efficient or not.), Efficiency is not really the issue. There are a few marginal cases where inline assignment is convenient (and your else print expression is an example) but in most cases you are simply trading a small amount of space saving with a significant hit in readability and debuggability (is that a word?). Even in the else expression any improvement in efficiency is not likely to be high enough to sacrifice readability. Consider the alternative: mx = 10**(n-1) + x print( mx - (mx % x)) Is that one extra line really going to hurt so much? > What i feel is the usage of assignment expressions is reducing the > readability of the code written above . Need your guidance. I would agree. And it makes it much harder to debug since you cannot examine the value before executing the if statement. Just because a feature exists doesn't mean it's a good idea to use it. Use it where there is a significant advantage. Readability and testability should always come before efficiency and especially before saving a few characters of typing. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From mats at wichmann.us Sun Aug 16 19:44:23 2020 From: mats at wichmann.us (Mats Wichmann) Date: Sun, 16 Aug 2020 17:44:23 -0600 Subject: [Tutor] use of assignment expression In-Reply-To: References: Message-ID: <5ace7065-58bb-1b29-bb7d-b9eec44935ff@wichmann.us> On 8/16/20 4:31 PM, Alan Gauld via Tutor wrote: > On 16/08/2020 14:55, Manprit Singh wrote: > >> # Program to find smallest n digit number divisible by a number x >> n = 5 >> x = 83 >> if (no := (10**(n-1) % x)) == 0: >> print(10**(n-1)) Since no is never used, why do this (was something missing from your example)? Plus, no probably isn't getting the value you want: it will be True or False. >> else: >> print((mx := (10**(n-1) + x)) - (mx % x)) >> >> The answer is 10043, which is the right answer . Just need to know if the >> way of using the assignment expression (2 times in the above example is >> efficient or not.), > > Efficiency is not really the issue. > There are a few marginal cases where inline assignment is convenient > (and your else print expression is an example) but in most cases you > are simply trading a small amount of space saving with a significant > hit in readability and debuggability (is that a word?). > > Even in the else expression any improvement in efficiency is not > likely to be high enough to sacrifice readability. Consider the alternative: > > mx = 10**(n-1) + x > print( mx - (mx % x)) > > Is that one extra line really going to hurt so much? > >> What i feel is the usage of assignment expressions is reducing the >> readability of the code written above . Need your guidance. > > I would agree. And it makes it much harder to debug since you > cannot examine the value before executing the if statement. It makes sense if you're immediately going to redo the computation. Which you do, so it's a /candidate/. There are either two or three times you might compute 10**(n-1). As written you would save one, in the else case - at the cost of having to worry about evaluation order: did that line risk the mx on the right side of the := being undefined or some previous value, or is it going to pick up the first part of the expression? I'd opine that here the cost isn't worth it, as Alan does. The idea would be to structure the code, walrus operator or not, so you don't have to repeat a computation and in this specific case it's probably best to avoid it by splitting instead: ex = 10 ** (n - 1) if not ex % x: print(ex) else: print(ex + x - ((ex + x) % x)) (untested, I've probably mangled it) The walrus operator does have real uses. I haven't had a chance to use it much because I'm mainly working on a codebase that must promise support back to Python 3.5 (we just got off 2.7, yay!) but the other one that works for me is when you're looping over a resource that exhausts - a generator, a file, etc. - you want to test the next item, and then possibly use it in the body, but testing it already consumed it, so that doesn't work without :=, or making a more awkward loop with the first read outside, and the next read following the use inside the loop as we've been used to doing. From mats at wichmann.us Sun Aug 16 19:47:08 2020 From: mats at wichmann.us (Mats Wichmann) Date: Sun, 16 Aug 2020 17:47:08 -0600 Subject: [Tutor] use of assignment expression In-Reply-To: <5ace7065-58bb-1b29-bb7d-b9eec44935ff@wichmann.us> References: <5ace7065-58bb-1b29-bb7d-b9eec44935ff@wichmann.us> Message-ID: On 8/16/20 5:44 PM, Mats Wichmann wrote: > On 8/16/20 4:31 PM, Alan Gauld via Tutor wrote: >> On 16/08/2020 14:55, Manprit Singh wrote: >> >>> # Program to find smallest n digit number divisible by a number x >>> n = 5 >>> x = 83 >>> if (no := (10**(n-1) % x)) == 0: >>> print(10**(n-1)) > > Since no is never used, why do this (was something missing from your > example)? Plus, no probably isn't getting the value you want: it will be > True or False. sigh, I missed a set of parens here, it will work out right. But... cue Alan's comments on readability, it fooled me! From PyTutor at DancesWithMice.info Mon Aug 17 01:03:41 2020 From: PyTutor at DancesWithMice.info (dn) Date: Mon, 17 Aug 2020 17:03:41 +1200 Subject: [Tutor] use of assignment expression In-Reply-To: References: Message-ID: <28fd628c-61cd-86ee-b29b-9f919f098b09@DancesWithMice.info> On 17/08/2020 01:55, Manprit Singh wrote: > Dear sir , > i need a comment on the use of assignment expression in the below given > example : > > # Program to find smallest n digit number divisible by a number x > n = 5 > x = 83 > if (no := (10**(n-1) % x)) == 0: > print(10**(n-1)) > else: > print((mx := (10**(n-1) + x)) - (mx % x)) > > The answer is 10043, which is the right answer . Just need to know if the > way of using the assignment expression (2 times in the above example is > efficient or not.), > > What i feel is the usage of assignment expressions is reducing the > readability of the code written above . Need your guidance. Have you read the other responses? Here's an alternate point-of-view:- Firstly, this is an arcane calculation. Whilst it may well reveal the meaning of the universe*, it seems (to me) that the people who talk like this are mathematicians, not (?mere) ordinary folk. Therefore, if the bunch of likely users (or more reasonably: the coders and users likely to ever read/check the code) are happily-capable of keeping stuff like this in their heads, "readability" is in the eye of the beholder! I don't like it. I'd break the formula into components - but I am not that sort of mathematician! Secondly, "efficiency". If we execute this calculation once-in-a-blue-moon*, none of the re-statements proposed will make a noticeable difference. However, ... if this is to become a function which is executed hundreds of times within some larger calculation, eg what will the weather be like tomorrow? or, is there some new/uncharted star in this image of the galaxy? then the question of "efficiency" becomes (that many "hundreds of times") more important! Efficiency is not something to retro-fit. If the application requires efficiency, then it is 'in the spec' from-the-word-go! That said, "readability" is often in a trade-off with efficiency! We were introduced to the word "debuggability". Great choice: "able to be debugged". Let's try making our code 'testable', which puts it on the way to being "provable" (a term in math - just to show that I often talk with mathematicians - some of my best friends are ...). So, following the precepts of TDD (Test-Driven Development*) - which should be enormously popular in the world of mathematical computing (because of its similarity to developing a "proof"), let's start with:- # test_divisor.py import divisor # you'll think of a much more meaningful name! n = 5 x = 83 assert divisor.divisor( n, x ) == 10043 # later add a bunch more tests # especially for the opposite calculation # plus any/all the edge-cases/exceptions you can imagine ... Having written a test, which will fail at the import, let's 'fix' that: Funny ha-ha! Now execution/testing fails at the assert, because there is no such function:- # divisor.py # Program to find smallest n digit number divisible by a number x def divisor( n, x ): if (no := (10**(n-1) % x)) == 0: print(10**(n-1)) else: print((mx := (10**(n-1) + x)) - (mx % x)) The test fails because the assert 'complains' that returning None is incorrect. Let's pause to discuss "testability". SRP (Single Responsibility Principle) applies - code each function/method to perform one task (and to perform it well). The function as it stands (as directly copied from the OP's code - with due apologies) performs TWO tasks: the calculation, and the printing of its result. Trivial? Agreed! However, principles are principles - and this is a toy-example. If we remove the second task, the function becomes thoroughly 'testable'. It has one task to complete, and we can easily check to see if the task has completed, and has delivered the correct response:- def divisor( n, x ): if (no := (10**(n-1) % x)) == 0: return 10**(n-1) else: return (mx := (10**(n-1) + x)) - (mx % x) Does that first test now work? Yes! (only because our brilliance outshines the sun...) BTW: add an if __main... and print( divisor(...) ) to divisor.py, and you'll be able to see where that second task (printing) currently-belongs - in case you were wondering. One of the other components of TDD is to re-factor (both code-code and test-code). One component of re-factoring is - wait for it - "efficiency". Sure, most of us, happily deciding to use an interpreted-language, don't worry too much about this - but there will still be folks whose eyes start to bulge* at such a blas? assumption - and failure to accommodate (their) "diversity"! Personally, I favor the virtue of putting the base-calculation before the if-statement. However, I'm a simple boy, and thus not a mathematician. If you are, and you are comfortable with reading the expression as a single thought (as are your colleagues) then your opinions of "readability" and "complexity" will be very different from mine! (psychology: "chunking") Having stood-upon principle (SRP) earlier, let's pull out another. How about DRY (Do not Repeat Yourself)? Few coders (judging from the worst of the YouTube demos) are typists - and can I/dare I say, even fewer mathematicians. So, if the expression "10**(n-1)" has to be entered into the code-base three (or more) times, what are the chances of a typo creeping-in somewhere? Talking about "debuggability"? The best debugging is to obviate its need! Quoting some commentary from my over-the-fence conversation with a neighbor this morning: "best to keep your mouth closed and be thought a fool, than to open it and remove all doubt!"* (no he didn't have you (or I) in-mind) Re-stated for our use: 'best not to type, if you don't have to'. Thus: type it once, make it test-able, test it, and then re-use with confidence! The time has come, to talk about the walrus (with apologies to Lewis Carroll*). An <<>>* The PEP's rationale, better-explains its advantages/purposes as <<>>* There's that "re-use" again - and my DRY sense of humor. Hah! The OP twice demonstrates the named-expression's syntax but in the first case, sadly, fails to benefit from its purpose (as observed in another response). The "reuse" advantage/rationale was lost. Which part(s) of the calculations are candidates for reuse? Well, "10**(n-1)" appears three times. So let's start there. I would go for: n_digit_number = 10**(n-1) if... but, in-keeping with the OP's (apparent) preferences, the all-in-one/walrus approach is: if ( (no := 10**(n-1) ) % x) == 0: NB only a mathematician could love a variable called "no". Do I like it? No! Do I (primarily) speak a language where the word "number" includes the letters "N" and "o". No! 98% of Norwegians likely also agree. TDD-ers: run a test to assure the refactoring work! Then we can move-on to:- if... return no # saving one re-computation else: return (mx := no + x) - (mx % x)) # the use of no saving another re-computation, plus # using mx already demonstrates how it should be done! Get your TDD-on, and ensure that this is correct... There is no point in using a named-assignment if it is not subsequently re-used - any more than would be the case for other types of assignment. Conversely, if the same computation is required at multiple points in the code, then the 'walrus operator' is another arrow in your quiver*. NB I'm not running Python v3.8. Accordingly have yet to build-up an opinion based upon experience! Web.Refs apologies, not Monty Python: https://en.wikipedia.org/wiki/42_(number) https://www.dictionary.com/browse/once-in-a-blue-moon https://www.agilealliance.org/glossary/tdd/#q=~(infinite~false~filters~(postType~(~'page~'post~'aa_book~'aa_event_session~'aa_experience_report~'aa_glossary~'aa_research_paper~'aa_video)~tags~(~'tdd))~searchTerm~'~sort~false~sortDirection~'asc~page~1) Surprise! https://image.shutterstock.com/image-photo/image-450w-228517990.jpg https://www.quora.com/What-does-the-phrase-open-your-mouth-and-remove-all-doubt-mean?share=1 https://forum.wordreference.com/threads/stand-on-principle.2206751/ https://www.goodreads.com/quotes/6028-the-time-has-come-the-walrus-said-to-talk-of https://docs.python.org/3/whatsnew/3.8.html#assignment-expressions https://docs.python.org/3/reference/expressions.html?highlight=named%20expressions#assignment-expressions https://www.python.org/dev/peps/pep-0572/ https://idioms.thefreedictionary.com/an+arrow+in+the+quiver -- Regards =dn From manpritsinghece at gmail.com Mon Aug 17 02:01:46 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Mon, 17 Aug 2020 11:31:46 +0530 Subject: [Tutor] use of assignment expression In-Reply-To: <28fd628c-61cd-86ee-b29b-9f919f098b09@DancesWithMice.info> References: <28fd628c-61cd-86ee-b29b-9f919f098b09@DancesWithMice.info> Message-ID: Dear all, Thanks for the response. So If i just say the better, clear and readable solution is : n = 5 x = 83 no = 10**(n-1) if no % x == 0: print(no) else: print((no + x) - ((no + x) % x)) We can avoid using assignment expression in this example. Regards Manprit Singh On Mon, Aug 17, 2020 at 10:34 AM dn via Tutor wrote: > On 17/08/2020 01:55, Manprit Singh wrote: > > Dear sir , > > i need a comment on the use of assignment expression in the below given > > example : > > > > # Program to find smallest n digit number divisible by a number x > > n = 5 > > x = 83 > > if (no := (10**(n-1) % x)) == 0: > > print(10**(n-1)) > > else: > > print((mx := (10**(n-1) + x)) - (mx % x)) > > > > The answer is 10043, which is the right answer . Just need to know if the > > way of using the assignment expression (2 times in the above example is > > efficient or not.), > > > > What i feel is the usage of assignment expressions is reducing the > > readability of the code written above . Need your guidance. > > > Have you read the other responses? Here's an alternate point-of-view:- > > Firstly, this is an arcane calculation. Whilst it may well reveal the > meaning of the universe*, it seems (to me) that the people who talk like > this are mathematicians, not (?mere) ordinary folk. Therefore, if the > bunch of likely users (or more reasonably: the coders and users likely > to ever read/check the code) are happily-capable of keeping stuff like > this in their heads, "readability" is in the eye of the beholder! I > don't like it. I'd break the formula into components - but I am not that > sort of mathematician! > > Secondly, "efficiency". If we execute this calculation > once-in-a-blue-moon*, none of the re-statements proposed will make a > noticeable difference. However, ... if this is to become a function > which is executed hundreds of times within some larger calculation, eg > what will the weather be like tomorrow? or, is there some new/uncharted > star in this image of the galaxy? then the question of "efficiency" > becomes (that many "hundreds of times") more important! Efficiency is > not something to retro-fit. If the application requires efficiency, then > it is 'in the spec' from-the-word-go! > > That said, "readability" is often in a trade-off with efficiency! > > > We were introduced to the word "debuggability". Great choice: "able to > be debugged". Let's try making our code 'testable', which puts it on the > way to being "provable" (a term in math - just to show that I often talk > with mathematicians - some of my best friends are ...). So, following > the precepts of TDD (Test-Driven Development*) - which should be > enormously popular in the world of mathematical computing (because of > its similarity to developing a "proof"), let's start with:- > > # test_divisor.py > import divisor # you'll think of a much more meaningful name! > n = 5 > x = 83 > assert divisor.divisor( n, x ) == 10043 > # later add a bunch more tests > # especially for the opposite calculation > # plus any/all the edge-cases/exceptions you can imagine > ... > > Having written a test, which will fail at the import, let's 'fix' that: > > > Funny ha-ha! Now execution/testing fails at the assert, because there is > no such function:- > > # divisor.py > # Program to find smallest n digit number divisible by a number x > > def divisor( n, x ): > if (no := (10**(n-1) % x)) == 0: > print(10**(n-1)) > else: > print((mx := (10**(n-1) + x)) - (mx % x)) > > The test fails because the assert 'complains' that returning None is > incorrect. > > > Let's pause to discuss "testability". SRP (Single Responsibility > Principle) applies - code each function/method to perform one task (and > to perform it well). The function as it stands (as directly copied from > the OP's code - with due apologies) performs TWO tasks: the calculation, > and the printing of its result. Trivial? Agreed! However, principles are > principles - and this is a toy-example. If we remove the second task, > the function becomes thoroughly 'testable'. It has one task to complete, > and we can easily check to see if the task has completed, and has > delivered the correct response:- > > def divisor( n, x ): > if (no := (10**(n-1) % x)) == 0: > return 10**(n-1) > else: > return (mx := (10**(n-1) + x)) - (mx % x) > > Does that first test now work? Yes! > (only because our brilliance outshines the sun...) > > BTW: add an if __main... and print( divisor(...) ) to divisor.py, and > you'll be able to see where that second task (printing) > currently-belongs - in case you were wondering. > > > One of the other components of TDD is to re-factor (both code-code and > test-code). One component of re-factoring is - wait for it - > "efficiency". Sure, most of us, happily deciding to use an > interpreted-language, don't worry too much about this - but there will > still be folks whose eyes start to bulge* at such a blas? assumption - > and failure to accommodate (their) "diversity"! > > Personally, I favor the virtue of putting the base-calculation before > the if-statement. However, I'm a simple boy, and thus not a > mathematician. If you are, and you are comfortable with reading the > expression as a single thought (as are your colleagues) then your > opinions of "readability" and "complexity" will be very different from > mine! (psychology: "chunking") > > > Having stood-upon principle (SRP) earlier, let's pull out another. How > about DRY (Do not Repeat Yourself)? Few coders (judging from the worst > of the YouTube demos) are typists - and can I/dare I say, even fewer > mathematicians. So, if the expression "10**(n-1)" has to be entered into > the code-base three (or more) times, what are the chances of a typo > creeping-in somewhere? > > Talking about "debuggability"? The best debugging is to obviate its > need! Quoting some commentary from my over-the-fence conversation with a > neighbor this morning: "best to keep your mouth closed and be thought a > fool, than to open it and remove all doubt!"* (no he didn't have you (or > I) in-mind) Re-stated for our use: 'best not to type, if you don't have > to'. Thus: type it once, make it test-able, test it, and then re-use > with confidence! > > > The time has come, to talk about the walrus (with apologies to Lewis > Carroll*). An << expression? or ?walrus?) assigns an expression to an identifier, while > also returning the value of the expression.>>>* The PEP's rationale, > better-explains its advantages/purposes as << expression is an important part of programming, allowing a descriptive > name to be used in place of a longer expression, and permitting reuse.>>>* > > There's that "re-use" again - and my DRY sense of humor. Hah! > > The OP twice demonstrates the named-expression's syntax but in the first > case, sadly, fails to benefit from its purpose (as observed in another > response). The "reuse" advantage/rationale was lost. > > Which part(s) of the calculations are candidates for reuse? Well, > "10**(n-1)" appears three times. So let's start there. I would go for: > > n_digit_number = 10**(n-1) > if... > > but, in-keeping with the OP's (apparent) preferences, the > all-in-one/walrus approach is: > > if ( (no := 10**(n-1) ) % x) == 0: > > NB only a mathematician could love a variable called "no". Do I like it? > No! Do I (primarily) speak a language where the word "number" includes > the letters "N" and "o". No! 98% of Norwegians likely also agree. > > > TDD-ers: run a test to assure the refactoring work! Then we can move-on > to:- > > if... > return no # saving one re-computation > else: > return (mx := no + x) - (mx % x)) > # the use of no saving another re-computation, plus > # using mx already demonstrates how it should be done! > > Get your TDD-on, and ensure that this is correct... > > > There is no point in using a named-assignment if it is not subsequently > re-used - any more than would be the case for other types of assignment. > Conversely, if the same computation is required at multiple points in > the code, then the 'walrus operator' is another arrow in your quiver*. > > > NB I'm not running Python v3.8. Accordingly have yet to build-up an > opinion based upon experience! > > > Web.Refs > apologies, not Monty Python: https://en.wikipedia.org/wiki/42_(number) > > https://www.dictionary.com/browse/once-in-a-blue-moon > > > https://www.agilealliance.org/glossary/tdd/#q=~(infinite~false~filters~(postType~(~'page~'post~'aa_book~'aa_event_session~'aa_experience_report~'aa_glossary~'aa_research_paper~'aa_video)~tags~(~'tdd))~searchTerm~'~sort~false~sortDirection~'asc~page~1) > > Surprise! > https://image.shutterstock.com/image-photo/image-450w-228517990.jpg > > > https://www.quora.com/What-does-the-phrase-open-your-mouth-and-remove-all-doubt-mean?share=1 > > https://forum.wordreference.com/threads/stand-on-principle.2206751/ > > > https://www.goodreads.com/quotes/6028-the-time-has-come-the-walrus-said-to-talk-of > > https://docs.python.org/3/whatsnew/3.8.html#assignment-expressions > > https://docs.python.org/3/reference/expressions.html?highlight=named%20expressions#assignment-expressions > https://www.python.org/dev/peps/pep-0572/ > > https://idioms.thefreedictionary.com/an+arrow+in+the+quiver > -- > Regards =dn > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From manpritsinghece at gmail.com Mon Aug 17 03:05:18 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Mon, 17 Aug 2020 12:35:18 +0530 Subject: [Tutor] use of assignment expression In-Reply-To: References: <28fd628c-61cd-86ee-b29b-9f919f098b09@DancesWithMice.info> Message-ID: Dear Sir, My question was about to write a program to find the smallest n digit number, divisible by number x. There are now two solutions to this problem: n = 5 x = 83 no = 10**(n-1) while True: if (no / x).is_integer(): print(no) break no = no + 1 ------------------------------------------------ n = 5 x = 83 no = 10**(n-1) if no % x == 0: print(no) else: print((no + x) - ((no + x) % x)) Will give the answer 10043. What I have concluded from all the previous mails, that assignment expression can be avoided in this case .The first solution is not in more mathematical terms, but the second solution is more mathematical. Need your comments further. Regards Manprit Singh On Mon, Aug 17, 2020 at 11:31 AM Manprit Singh wrote: > Dear all, > > Thanks for the response. So If i just say the better, clear and readable > solution is : > > n = 5 > x = 83 > no = 10**(n-1) > if no % x == 0: > print(no) > else: > print((no + x) - ((no + x) % x)) > > We can avoid using assignment expression in this example. > > Regards > Manprit Singh > > > > > On Mon, Aug 17, 2020 at 10:34 AM dn via Tutor wrote: > >> On 17/08/2020 01:55, Manprit Singh wrote: >> > Dear sir , >> > i need a comment on the use of assignment expression in the below given >> > example : >> > >> > # Program to find smallest n digit number divisible by a number x >> > n = 5 >> > x = 83 >> > if (no := (10**(n-1) % x)) == 0: >> > print(10**(n-1)) >> > else: >> > print((mx := (10**(n-1) + x)) - (mx % x)) >> > >> > The answer is 10043, which is the right answer . Just need to know if >> the >> > way of using the assignment expression (2 times in the above example is >> > efficient or not.), >> > >> > What i feel is the usage of assignment expressions is reducing the >> > readability of the code written above . Need your guidance. >> >> >> Have you read the other responses? Here's an alternate point-of-view:- >> >> Firstly, this is an arcane calculation. Whilst it may well reveal the >> meaning of the universe*, it seems (to me) that the people who talk like >> this are mathematicians, not (?mere) ordinary folk. Therefore, if the >> bunch of likely users (or more reasonably: the coders and users likely >> to ever read/check the code) are happily-capable of keeping stuff like >> this in their heads, "readability" is in the eye of the beholder! I >> don't like it. I'd break the formula into components - but I am not that >> sort of mathematician! >> >> Secondly, "efficiency". If we execute this calculation >> once-in-a-blue-moon*, none of the re-statements proposed will make a >> noticeable difference. However, ... if this is to become a function >> which is executed hundreds of times within some larger calculation, eg >> what will the weather be like tomorrow? or, is there some new/uncharted >> star in this image of the galaxy? then the question of "efficiency" >> becomes (that many "hundreds of times") more important! Efficiency is >> not something to retro-fit. If the application requires efficiency, then >> it is 'in the spec' from-the-word-go! >> >> That said, "readability" is often in a trade-off with efficiency! >> >> >> We were introduced to the word "debuggability". Great choice: "able to >> be debugged". Let's try making our code 'testable', which puts it on the >> way to being "provable" (a term in math - just to show that I often talk >> with mathematicians - some of my best friends are ...). So, following >> the precepts of TDD (Test-Driven Development*) - which should be >> enormously popular in the world of mathematical computing (because of >> its similarity to developing a "proof"), let's start with:- >> >> # test_divisor.py >> import divisor # you'll think of a much more meaningful name! >> n = 5 >> x = 83 >> assert divisor.divisor( n, x ) == 10043 >> # later add a bunch more tests >> # especially for the opposite calculation >> # plus any/all the edge-cases/exceptions you can imagine >> ... >> >> Having written a test, which will fail at the import, let's 'fix' that: >> >> >> Funny ha-ha! Now execution/testing fails at the assert, because there is >> no such function:- >> >> # divisor.py >> # Program to find smallest n digit number divisible by a number x >> >> def divisor( n, x ): >> if (no := (10**(n-1) % x)) == 0: >> print(10**(n-1)) >> else: >> print((mx := (10**(n-1) + x)) - (mx % x)) >> >> The test fails because the assert 'complains' that returning None is >> incorrect. >> >> >> Let's pause to discuss "testability". SRP (Single Responsibility >> Principle) applies - code each function/method to perform one task (and >> to perform it well). The function as it stands (as directly copied from >> the OP's code - with due apologies) performs TWO tasks: the calculation, >> and the printing of its result. Trivial? Agreed! However, principles are >> principles - and this is a toy-example. If we remove the second task, >> the function becomes thoroughly 'testable'. It has one task to complete, >> and we can easily check to see if the task has completed, and has >> delivered the correct response:- >> >> def divisor( n, x ): >> if (no := (10**(n-1) % x)) == 0: >> return 10**(n-1) >> else: >> return (mx := (10**(n-1) + x)) - (mx % x) >> >> Does that first test now work? Yes! >> (only because our brilliance outshines the sun...) >> >> BTW: add an if __main... and print( divisor(...) ) to divisor.py, and >> you'll be able to see where that second task (printing) >> currently-belongs - in case you were wondering. >> >> >> One of the other components of TDD is to re-factor (both code-code and >> test-code). One component of re-factoring is - wait for it - >> "efficiency". Sure, most of us, happily deciding to use an >> interpreted-language, don't worry too much about this - but there will >> still be folks whose eyes start to bulge* at such a blas? assumption - >> and failure to accommodate (their) "diversity"! >> >> Personally, I favor the virtue of putting the base-calculation before >> the if-statement. However, I'm a simple boy, and thus not a >> mathematician. If you are, and you are comfortable with reading the >> expression as a single thought (as are your colleagues) then your >> opinions of "readability" and "complexity" will be very different from >> mine! (psychology: "chunking") >> >> >> Having stood-upon principle (SRP) earlier, let's pull out another. How >> about DRY (Do not Repeat Yourself)? Few coders (judging from the worst >> of the YouTube demos) are typists - and can I/dare I say, even fewer >> mathematicians. So, if the expression "10**(n-1)" has to be entered into >> the code-base three (or more) times, what are the chances of a typo >> creeping-in somewhere? >> >> Talking about "debuggability"? The best debugging is to obviate its >> need! Quoting some commentary from my over-the-fence conversation with a >> neighbor this morning: "best to keep your mouth closed and be thought a >> fool, than to open it and remove all doubt!"* (no he didn't have you (or >> I) in-mind) Re-stated for our use: 'best not to type, if you don't have >> to'. Thus: type it once, make it test-able, test it, and then re-use >> with confidence! >> >> >> The time has come, to talk about the walrus (with apologies to Lewis >> Carroll*). An <<> expression? or ?walrus?) assigns an expression to an identifier, while >> also returning the value of the expression.>>>* The PEP's rationale, >> better-explains its advantages/purposes as <<> expression is an important part of programming, allowing a descriptive >> name to be used in place of a longer expression, and permitting reuse.>>>* >> >> There's that "re-use" again - and my DRY sense of humor. Hah! >> >> The OP twice demonstrates the named-expression's syntax but in the first >> case, sadly, fails to benefit from its purpose (as observed in another >> response). The "reuse" advantage/rationale was lost. >> >> Which part(s) of the calculations are candidates for reuse? Well, >> "10**(n-1)" appears three times. So let's start there. I would go for: >> >> n_digit_number = 10**(n-1) >> if... >> >> but, in-keeping with the OP's (apparent) preferences, the >> all-in-one/walrus approach is: >> >> if ( (no := 10**(n-1) ) % x) == 0: >> >> NB only a mathematician could love a variable called "no". Do I like it? >> No! Do I (primarily) speak a language where the word "number" includes >> the letters "N" and "o". No! 98% of Norwegians likely also agree. >> >> >> TDD-ers: run a test to assure the refactoring work! Then we can move-on >> to:- >> >> if... >> return no # saving one re-computation >> else: >> return (mx := no + x) - (mx % x)) >> # the use of no saving another re-computation, plus >> # using mx already demonstrates how it should be done! >> >> Get your TDD-on, and ensure that this is correct... >> >> >> There is no point in using a named-assignment if it is not subsequently >> re-used - any more than would be the case for other types of assignment. >> Conversely, if the same computation is required at multiple points in >> the code, then the 'walrus operator' is another arrow in your quiver*. >> >> >> NB I'm not running Python v3.8. Accordingly have yet to build-up an >> opinion based upon experience! >> >> >> Web.Refs >> apologies, not Monty Python: https://en.wikipedia.org/wiki/42_(number) >> >> https://www.dictionary.com/browse/once-in-a-blue-moon >> >> >> https://www.agilealliance.org/glossary/tdd/#q=~(infinite~false~filters~(postType~(~'page~'post~'aa_book~'aa_event_session~'aa_experience_report~'aa_glossary~'aa_research_paper~'aa_video)~tags~(~'tdd))~searchTerm~'~sort~false~sortDirection~'asc~page~1) >> >> Surprise! >> https://image.shutterstock.com/image-photo/image-450w-228517990.jpg >> >> >> https://www.quora.com/What-does-the-phrase-open-your-mouth-and-remove-all-doubt-mean?share=1 >> >> https://forum.wordreference.com/threads/stand-on-principle.2206751/ >> >> >> https://www.goodreads.com/quotes/6028-the-time-has-come-the-walrus-said-to-talk-of >> >> https://docs.python.org/3/whatsnew/3.8.html#assignment-expressions >> >> https://docs.python.org/3/reference/expressions.html?highlight=named%20expressions#assignment-expressions >> https://www.python.org/dev/peps/pep-0572/ >> >> https://idioms.thefreedictionary.com/an+arrow+in+the+quiver >> -- >> Regards =dn >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > From ptan1 at capellauniversity.edu Mon Aug 17 00:36:56 2020 From: ptan1 at capellauniversity.edu (Phaik Huen Tan) Date: Sun, 16 Aug 2020 23:36:56 -0500 Subject: [Tutor] Save output to log file Message-ID: I am supposed to create a network monitoring tool using python and send the output to log file. I have been searching online and don't have any luck finding how to send the result to log file. Can you please give me example on how to send the log from the output? Thanks! From alan.gauld at yahoo.co.uk Mon Aug 17 03:58:56 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 17 Aug 2020 08:58:56 +0100 Subject: [Tutor] Save output to log file In-Reply-To: References: Message-ID: On 17/08/2020 05:36, Phaik Huen Tan wrote: > I am supposed to create a network monitoring tool using python and send the > output to log file. I have been searching online and don't have any luck > finding how to send the result to log file. Can you please give me example > on how to send the log from the output? A log file is just a file. So if you can write to any file you can write to a log file. The simplest way to to that is just to use print statements then, when you run the code use output redirection to your log file $ python myprog.py > mylogfile.txt But assuming you need something more sophisticated than that you can use the logging module that comes with Python. Check the documentation for many examples. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Mon Aug 17 04:15:06 2020 From: __peter__ at web.de (Peter Otten) Date: Mon, 17 Aug 2020 10:15:06 +0200 Subject: [Tutor] use of assignment expression References: <28fd628c-61cd-86ee-b29b-9f919f098b09@DancesWithMice.info> Message-ID: Manprit Singh wrote: > Dear Sir, > My question was about to write a program to find the smallest n digit > number, divisible by number x. > There are now two solutions to this problem: > > n = 5 > x = 83 > no = 10**(n-1) > while True: > if (no / x).is_integer(): This check may raise an OverflowError or, worse, give the wrong result: >>> (10**300/3).is_integer() True > print(no) > break > no = no + 1 > ------------------------------------------------ > n = 5 > x = 83 > no = 10**(n-1) > if no % x == 0: > print(no) > else: > print((no + x) - ((no + x) % x)) > > > > Will give the answer 10043. What I have concluded from all the previous > mails, that assignment expression can be avoided in this case .The first > solution is not in more mathematical terms, but the second solution is > more mathematical. Need your comments further. If you understand the second solution, go with it. While the first solution works if you avoid the use of float it may be slow for big x. From cs at cskk.id.au Mon Aug 17 04:53:24 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Mon, 17 Aug 2020 18:53:24 +1000 Subject: [Tutor] Save output to log file In-Reply-To: References: Message-ID: <20200817085324.GA16956@cskk.homeip.net> On 17Aug2020 08:58, Alan Gauld wrote: >On 17/08/2020 05:36, Phaik Huen Tan wrote: >> I am supposed to create a network monitoring tool using python and send the >> output to log file. I have been searching online and don't have any luck >> finding how to send the result to log file. Can you please give me example >> on how to send the log from the output? > >A log file is just a file. So if you can write to any file >you can write to a log file. The simplest way to to that is just >to use print statements then, when you run the code use >output redirection to your log file > >$ python myprog.py > mylogfile.txt I'd add two important things here: First, log files generally grow. So the above line should always look like this: $ python myprog.py >> mylogfile.txt to append to the file if it already exists. If you're opening the log file from within your python programme this would look like: logfile = open(logfile_pathname, 'a') # open for append Second, generally it is useful to include a timestamp on everything you write to a log file - that way you know when things happened when you review the log. Finally, the logging module, which Alan mentions: >But assuming you need something more sophisticated than that >you can use the logging module that comes with Python. >Check the documentation for many examples. The logging module docs are here: https://docs.python.org/3/library/logging.html#module-logging The basic deal is that you configure the logging when your programme commences, and then broadly just use debug(), info(), warning() and error() logging calls elsewhere. The configuration is where you set up things like log filenames and the format for the log messages. Then the various log calls just contain the message itself, all the things like putting it in the right file, with a timestamp etc are already done. Cheers, Cameron Simpson From john at johnweller.co.uk Mon Aug 17 04:57:33 2020 From: john at johnweller.co.uk (John Weller) Date: Mon, 17 Aug 2020 09:57:33 +0100 Subject: [Tutor] Save output to log file In-Reply-To: References: Message-ID: <000601d67474$74feeae0$5efcc0a0$@johnweller.co.uk> > I am supposed to create a network monitoring tool using python and send the output > to log file. I have been searching online and don't have any luck finding how to send > the result to log file. Can you please give me example on how to send the log from > the output? > > Thanks! You might find the following YouTube videos helpful: https://www.youtube.com/watch?v=g8nQ90Hk328 https://www.youtube.com/watch?v=Uh2ebFW8OYM&t=21s https://www.youtube.com/watch?v=-ARI4Cz-awo John Weller From brendap at marketamerica.com Mon Aug 17 08:53:54 2020 From: brendap at marketamerica.com (Brenda Ives) Date: Mon, 17 Aug 2020 12:53:54 +0000 Subject: [Tutor] Python programming question related to Return/Print statement In-Reply-To: References: Message-ID: Good morning, While I am still learning python, I've been programming for a very long time. Some of what the issues with this is logical knowing how computers work. While we know that "" means you don't print anything computers are literal and they will print a space and a comma when you don't want that to occur. You need to check for empty values and skip them. This was actually a good learning lesson for me so I had to try it. Here is what my attempt arrived at. def format_name(first_name, last_name): # return "Name: " + first_name + ", " + last_name if last_name is '': return "Name: " + first_name elif first_name is '': return "Name: " + last_name else: return "Name: " + last_name + ", " + first_name print(format_name("Ernest", "Hemingway")) # Should return the string "Name: Hemingway, Ernest" print(format_name("", "Madonna")) # Should return the string "Name: Madonna" print(format_name("Voltaire", "")) # Should return the string "Name: Voltaire" print(format_name("", "")) # Should return an empty string When I ran it, here is the result. Name: Hemingway, Ernest Name: Madonna Name: Voltaire Name: -----Original Message----- From: Tutor On Behalf Of Mats Wichmann Sent: Friday, August 14, 2020 2:53 PM To: tutor at python.org Subject: Re: [Tutor] Python programming question related to Return/Print statement On 8/14/20 11:45 AM, eric grunfeld wrote: > Good Afternoon Everyone: > > I have been seeking to rectify my mistake in running this program via > Python. > > Here it is: > > def format_name(first_name, last_name): > return "Name " + first_name + ", " + last_name > return string the second statement will never be reached, so drop it. > However, after running the program, this has been the response: > Incorrect > > Not quite, format_name('Ernest', 'Hemingway') returned Name Ernest, > Hemingway, should be Name: Hemingway, Ernest. > > It appears to be how I have programmed my return statement. it seems whatever grading tool you're entering this into is expecting a colon after the word Name, so you should include that when you construct the string.... it's possible from what you pasted that it also expected a terminating period. So it appears a question of reading the problem specification very precisely. _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From Richard at Damon-Family.org Mon Aug 17 10:32:53 2020 From: Richard at Damon-Family.org (Richard Damon) Date: Mon, 17 Aug 2020 10:32:53 -0400 Subject: [Tutor] Python programming question related to Return/Print statement In-Reply-To: References: Message-ID: On 8/17/20 8:53 AM, Brenda Ives wrote: > Good morning, > > > > While I am still learning python, I've been programming for a very long time. Some of what the issues with this is logical knowing how computers work. While we know that "" means you don't print anything computers are literal and they will print a space and a comma when you don't want that to occur. You need to check for empty values and skip them. This was actually a good learning lesson for me so I had to try it. Here is what my attempt arrived at. > > > > def format_name(first_name, last_name): > > # return "Name: " + first_name + ", " + last_name > > if last_name is '': > > return "Name: " + first_name > > elif first_name is '': > > return "Name: " + last_name > > else: > > return "Name: " + last_name + ", " + first_name > > > > > > print(format_name("Ernest", "Hemingway")) # Should return the string "Name: Hemingway, Ernest" > > > > print(format_name("", "Madonna")) > > # Should return the string "Name: Madonna" > > > > print(format_name("Voltaire", "")) > > # Should return the string "Name: Voltaire" > > > > print(format_name("", "")) > > # Should return an empty string > > > > When I ran it, here is the result. > > > > Name: Hemingway, Ernest > > Name: Madonna > > Name: Voltaire > > Name: > > Note, the test last_name is '' doesn't check that the last_name is some empty string but is THAT particular empty string. 'is' is not just an equality check, but an identity check. Python just happens to cache certain values, so one empty string may end up being used for many of them, but this is not guaranteed, and particularly, if the empty string comes out of a If you want to check for equality of value, use == to make that test. -- Richard Damon From grunfelderic at gmail.com Tue Aug 18 11:17:00 2020 From: grunfelderic at gmail.com (eric grunfeld) Date: Tue, 18 Aug 2020 11:17:00 -0400 Subject: [Tutor] For Loops Program Issue Message-ID: Good Morning Everyone: I am currently taking a beginners Python course that is being taught by Google, on the Coursera platform. I have been working on a problem but I seem to be obtaining an error message after running the program. Here is the problem: def factorial(n): result = 1 for i in range(result,n): result = result * n+1 return result print(factorial(4)) # should return 24 print(factorial(5)) # should return 120: Here is the the error message that I have been receiving: Here is your output: 85 781 Not quite. Pay attention at the operations that the code is doing and make sure that the factorial function returns the product of the numbers between 1 and n. Based upon my understanding, it appears that my issue is with the set-up of my range. I look forward to any thoughts or comments that you may have. All the best, Eric From Richard at Damon-Family.org Tue Aug 18 12:13:59 2020 From: Richard at Damon-Family.org (Richard Damon) Date: Tue, 18 Aug 2020 12:13:59 -0400 Subject: [Tutor] For Loops Program Issue In-Reply-To: References: Message-ID: <20723d26-3ecf-9ab7-2247-1ae4170ef14b@Damon-Family.org> On 8/18/20 11:17 AM, eric grunfeld wrote: > Good Morning Everyone: > > I am currently taking a beginners Python course that is being taught by > Google, on the Coursera platform. > > I have been working on a problem but I seem to be obtaining an error > message after running the program. > > Here is the problem: > > def factorial(n): > result = 1 > for i in range(result,n): > result = result * n+1 > return result > > print(factorial(4)) # should return 24 > print(factorial(5)) # should return 120: > > Here is the the error message that I have been receiving: > > Here is your output: > 85 > 781 > > Not quite. Pay attention at the operations that the code is > doing and make sure that the factorial function returns the > product of the numbers between 1 and n. > > Based upon my understanding, it appears that my issue is with the set-up of > my range. > > I look forward to any thoughts or comments that you may have. > > All the best, > Eric Why is your range using 'result' as its base? What values do you WANT out of the range? What values is range defined to give you? look at the statement: result = result * n+1 Spaces matter for program nesting of control flow, it does not affect the order of operations in a statement. What are you expecting here? -- Richard Damon From alan.gauld at yahoo.co.uk Tue Aug 18 12:49:12 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 18 Aug 2020 17:49:12 +0100 Subject: [Tutor] For Loops Program Issue In-Reply-To: References: Message-ID: On 18/08/2020 16:17, eric grunfeld wrote: > Here is the problem: > > def factorial(n): > result = 1 > for i in range(result,n): > result = result * n+1 > return result > > print(factorial(4)) # should return 24 A common debugging technique is to work through the program manually to see what the variables are doing. Lets try that: For i = 1 n = 4, result = 1 result => 1 * 4 + 1 => 5 (*) For i = 2 n = 4, result = 5 result => 5 * 4 + 1 => 21 For i = 3 n = 4, result = 21 result => 21 * 4 + 1 => 85 ... Can you see what is going wrong? What values should you be multiplying by? Recall that multiplication comes before addition in priority so result * n+1 is (result*n) + 1 Also you want n to increase but it doesn't. What does increase is i. > Here is your output: > 85 > Based upon my understanding, it appears that my issue is with the set-up of > my range. Not entirely, its mainly to do with which values you are mutiplying by. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From john at johnweller.co.uk Tue Aug 18 12:32:56 2020 From: john at johnweller.co.uk (John Weller) Date: Tue, 18 Aug 2020 17:32:56 +0100 Subject: [Tutor] For Loops Program Issue In-Reply-To: References: Message-ID: <00b801d6757d$3bfdd120$b3f97360$@johnweller.co.uk> > -----Original Message----- > From: Tutor On Behalf Of eric > grunfeld > Sent: 18 August 2020 16:17 > To: tutor at python.org > Subject: [Tutor] For Loops Program Issue > > Good Morning Everyone: > > I am currently taking a beginners Python course that is being taught by Google, on > the Coursera platform. > > I have been working on a problem but I seem to be obtaining an error message > after running the program. > > Here is the problem: > > def factorial(n): > result = 1 > for i in range(result,n): > result = result * n+1 > return result Should be result = result * i Range should be n+1 > print(factorial(4)) # should return 24 > print(factorial(5)) # should return 120: > > Here is the the error message that I have been receiving: > > Here is your output: > 85 > 781 > Forgot to Reply to All John Weller 01380 723235 07976 393631 From D.P.Noone at lumc.nl Wed Aug 19 01:54:38 2020 From: D.P.Noone at lumc.nl (D.P.Noone at lumc.nl) Date: Wed, 19 Aug 2020 05:54:38 +0000 Subject: [Tutor] Executing a .sh script in a for loop Message-ID: <721de3a7fda641d9bd1af8306247bd08@lumc.nl> Hey all, I am trying to use a for loop to execute a .sh script on every file in a directory that ends with a particular ending and extension. My loop successfully loops over the files with the correct endings, opens the script but does not execute it correctly on the file. Here is the for loop: import os import sys import subprocess for root, dirs, files in os.walk("."): for filename in files: if filename.endswith("fileending.txt"): subprocess.Popen('./script.sh',) print("Done") The result is I get this repeated for every file I want in the directory: Usage: script.sh output_from_fileending.txt Done This is the same as if I just type script.sh in the command line in linux, but do not target it to any file specifically. i.e. > script.sh Usage: script.sh output_from_fileending.txt The script usually works if you do: >script.sh targetfile_with_fileending.txt Generated plots of 1D profiles and fits: targetfile_plot.pdf Any ideas? Thanks in advance, Dylan From alan.gauld at yahoo.co.uk Wed Aug 19 05:00:37 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 19 Aug 2020 10:00:37 +0100 Subject: [Tutor] Executing a .sh script in a for loop In-Reply-To: <721de3a7fda641d9bd1af8306247bd08@lumc.nl> References: <721de3a7fda641d9bd1af8306247bd08@lumc.nl> Message-ID: On 19/08/2020 06:54, D.P.Noone at lumc.nl wrote: > for root, dirs, files in os.walk("."): > for filename in files: > if filename.endswith("fileending.txt"): > subprocess.Popen('./script.sh',) > print("Done") > This is the same as if I just type script.sh in the command line in linux, > but do not target it to any file specifically. i.e. Correct. You have just answered your own question. How do you suppose script.sh is supposed to know what your python code is doing? There is no magic communication channel. You need to tell it the file name when you call it just as you do at the command line. Popen() can take arguments as well as the script name. sub.Popen( ['./script.sh', filename] ) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From la_spirou at hotmail.com Wed Aug 19 05:00:22 2020 From: la_spirou at hotmail.com (P L) Date: Wed, 19 Aug 2020 09:00:22 +0000 Subject: [Tutor] For Loops Program Issue In-Reply-To: References: Message-ID: Your range will be whatever input that is given. There's no need to include the result variable in the input range. Second issue, you can simplify the formula even more: result *= ? followed by a second line of instructions for n. Best of luck, Pat ________________________________ From: Tutor on behalf of eric grunfeld Sent: August 18, 2020 11:17 AM To: tutor at python.org Subject: [Tutor] For Loops Program Issue Good Morning Everyone: I am currently taking a beginners Python course that is being taught by Google, on the Coursera platform. I have been working on a problem but I seem to be obtaining an error message after running the program. Here is the problem: def factorial(n): result = 1 for i in range(result,n): result = result * n+1 return result print(factorial(4)) # should return 24 print(factorial(5)) # should return 120: Here is the the error message that I have been receiving: Here is your output: 85 781 Not quite. Pay attention at the operations that the code is doing and make sure that the factorial function returns the product of the numbers between 1 and n. Based upon my understanding, it appears that my issue is with the set-up of my range. I look forward to any thoughts or comments that you may have. All the best, Eric _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://nam11.safelinks.protection.outlook.com/?url=https%3A%2F%2Fmail.python.org%2Fmailman%2Flistinfo%2Ftutor&data=02%7C01%7C%7C9a64081af0b4445256f908d8438f7510%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C637333630700211531&sdata=2FG3qR%2Fdv21fjRG1j0BoWVrzDl5YY9fdt4qSurIJ%2Fjw%3D&reserved=0 From Steve.Flynn at capita.com Wed Aug 19 04:47:07 2020 From: Steve.Flynn at capita.com (Flynn, Stephen (Life & Pensions)) Date: Wed, 19 Aug 2020 08:47:07 +0000 Subject: [Tutor] Executing a .sh script in a for loop In-Reply-To: <721de3a7fda641d9bd1af8306247bd08@lumc.nl> References: <721de3a7fda641d9bd1af8306247bd08@lumc.nl> Message-ID: At no point do you ever actually try to run the script.sh code with a filename as its first argument. You effectively call "script.sh" however many times you find a file which matches your filename requirements but never tell it which filename to operate on. Call "script.sh" and also supply the filename variable as it's first argument. S. -----Original Message----- From: Tutor On Behalf Of D.P.Noone at lumc.nl Sent: 19 August 2020 06:55 To: tutor at python.org Subject: [Tutor] Executing a .sh script in a for loop **EXTERNAL** Hey all, I am trying to use a for loop to execute a .sh script on every file in a directory that ends with a particular ending and extension. My loop successfully loops over the files with the correct endings, opens the script but does not execute it correctly on the file. Here is the for loop: import os import sys import subprocess for root, dirs, files in os.walk("."): for filename in files: if filename.endswith("fileending.txt"): subprocess.Popen('./script.sh',) print("Done") The result is I get this repeated for every file I want in the directory: Usage: script.sh output_from_fileending.txt Done This is the same as if I just type script.sh in the command line in linux, but do not target it to any file specifically. i.e. > script.sh Usage: script.sh output_from_fileending.txt The script usually works if you do: >script.sh targetfile_with_fileending.txt Generated plots of 1D profiles and fits: targetfile_plot.pdf Any ideas? Thanks in advance, Dylan _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor This message has been scanned by Capita systems, but if you believe it to be spam, please send it to spam at forcepoint.com. Messages sent to spam at forcepoint.com are queued for email analysis by Forcepoint Threat Lab. This email originates from outside of Capita. Keep this in mind before responding, opening attachments or clicking any links. Unless you recognise the sender and know the content is safe. If in any doubt, the grammar and spelling are poor, or the name doesn't match the email address then please contact the sender via an alternate known method. This email is security checked and subject to the disclaimer on web-page: https://www.capita.com/email-disclaimer.aspx From mats at wichmann.us Wed Aug 19 10:12:03 2020 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 19 Aug 2020 08:12:03 -0600 Subject: [Tutor] Executing a .sh script in a for loop In-Reply-To: References: <721de3a7fda641d9bd1af8306247bd08@lumc.nl> Message-ID: <083feffe-4a98-f8dc-ef39-fad4cac415c5@wichmann.us> On 8/19/20 3:00 AM, Alan Gauld via Tutor wrote: > On 19/08/2020 06:54, D.P.Noone at lumc.nl wrote: > >> for root, dirs, files in os.walk("."): >> for filename in files: >> if filename.endswith("fileending.txt"): >> subprocess.Popen('./script.sh',) >> print("Done") > >> This is the same as if I just type script.sh in the command line in linux, >> but do not target it to any file specifically. i.e. > > Correct. You have just answered your own question. > How do you suppose script.sh is supposed to know what your > python code is doing? There is no magic communication channel. > You need to tell it the file name when you call it just as > you do at the command line. > > Popen() can take arguments as well as the script name. > > sub.Popen( ['./script.sh', filename] ) > In addition, if using the Popen constructor directly, you need to manage this connection a little better - making sure the script has completed, collecting any results, etc. It's easier to use one of the convenience methods: I prefer subprocess.run(), which handles the whole deal, and gives you back an instance of the nice CompletedProcess class. This is now highlighted at the very top of the subprocess documentation: https://docs.python.org/3/library/subprocess.html From brendap at marketamerica.com Wed Aug 19 08:12:41 2020 From: brendap at marketamerica.com (Brenda Ives) Date: Wed, 19 Aug 2020 12:12:41 +0000 Subject: [Tutor] Python programming question related to Return/Print statement In-Reply-To: References: Message-ID: Thank you, very good information to know and in my programming language it would be "if not(last_name) then". I will try that and see what error I get and if it would have led me to try that simple solution. Brenda -----Original Message----- From: Tutor On Behalf Of Dennis Lee Bieber Sent: Monday, August 17, 2020 11:44 AM To: tutor at python.org Subject: Re: [Tutor] Python programming question related to Return/Print statement On Mon, 17 Aug 2020 12:53:54 +0000, Brenda Ives > declaimed the following: > >def format_name(first_name, last_name): > > # return "Name: " + first_name + ", " + last_name > > if last_name is '': "is" tests that the two are exactly the same object, it does not test if they are equal value. The Python interpreter /might/ cache short strings for re-use, but this behavior can not be relied upon if strings become longer than some amount. Also, Python considers "empty" strings as False, so this can be written as just if not last_name: (that also applies to empty lists and dictionaries) -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From okpanachivictor0 at gmail.com Wed Aug 19 12:13:32 2020 From: okpanachivictor0 at gmail.com (Victor Okpanachi) Date: Wed, 19 Aug 2020 18:13:32 +0200 Subject: [Tutor] Request Message-ID: Please, is there any similar emailing list for java? I will be grateful if there is and anyone can share with me. From robertvstepp at gmail.com Wed Aug 19 20:41:49 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Wed, 19 Aug 2020 19:41:49 -0500 Subject: [Tutor] Request In-Reply-To: References: Message-ID: On Wed, Aug 19, 2020 at 4:04 PM Victor Okpanachi wrote: > > Please, is there any similar emailing list for java? You might enjoy https://javaranch.com/ -- boB From anilduggirala at fastmail.fm Fri Aug 21 13:35:14 2020 From: anilduggirala at fastmail.fm (Anil Felipe Duggirala) Date: Fri, 21 Aug 2020 12:35:14 -0500 Subject: [Tutor] cannot install module with pip in venv Message-ID: hello, I am trying to install modules in a requirements.txt list, and am getting the following error: https://pastebin.com/tSxwTwgg Modules setuptools and wheel appear to be installed already. I am trying to install these modules in a venv. thank you. From mats at wichmann.us Fri Aug 21 19:37:07 2020 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 21 Aug 2020 17:37:07 -0600 Subject: [Tutor] cannot install module with pip in venv In-Reply-To: References: Message-ID: On 8/21/20 11:35 AM, Anil Felipe Duggirala wrote: > hello, > > I am trying to install modules in a requirements.txt list, and am > getting the following error: > > https://pastebin.com/tSxwTwgg > > Modules setuptools and wheel appear to be installed already. I am trying > to install these modules in a venv. A little prospecting turns up some bad news (posted here as it might be educational how to look this kind of thing up). It looks like one of the packages isn't supported, in a couple of ways... ERROR: Failed building wheel for electrumsv-secp256k1 A quick look on pypi.org shows this intends to be a prepackaged build of said software, which means it isn't expected to be trying to build a wheel in the first place. "A vetted customised build of libsecp256k1 published as a Python package " But it's old.. if you click to go to the files link on pypi: https://pypi.org/project/electrumsv-secp256k1/#files There are some wheels... Mac 3.6 and 3.7, 32-bit Linux 3.6 and 3.6, and 64-bit Linux 3.6 and 3.7, and some Windows . Since there isn't one for Linux and 3.8 (no surprise, since there was no 3.8 back in March 2019), that's why it falls back to trying to compile it from source. DEPRECATION: Could not build wheels for electrumsv-secp256k1 which do not use PEP 517. pip will fall back to legacy 'setup.py install' for these. pip 21.0 will remove support for this functionality. A possible replacement is to fix the wheel build issue reported above. You can find discussion regarding this at https://github.com/pypa/pip/issues/8368. Looks like the package is packaged against versions of the tools that aren't current, and is using stuff which is about to go entirely obsolete. ERROR: Command errored out with exit status 1: command: /home/anilfd/pyvenvs/crypto/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-r7tuyssz/electrumsv-secp256k1/setup.py'"'"'; __file__='"'"'/tmp/pip-install-r7tuyssz/electrumsv-secp256k1/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-u40re0sf cwd: /tmp/pip-install-r7tuyssz/electrumsv-secp256k1/ : Warning: 'keywords' should be a list, got type 'tuple' That's frankly horrid looking... I've never seen that kind of construction. In any case, the best advice for something like that is to contact the project. There's a link on the pep page, but it doesn't look active. Since you're using a virtualenv anyway, perhaps you could try one based on Python 3.7? From mats at wichmann.us Fri Aug 21 19:42:36 2020 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 21 Aug 2020 17:42:36 -0600 Subject: [Tutor] cannot install module with pip in venv In-Reply-To: References: Message-ID: <2e777d57-7512-2d09-cf3d-b03f3d5b8d40@wichmann.us> On 8/21/20 5:37 PM, Mats Wichmann wrote: > In any case, the best advice for something like that is to contact the > project. There's a link on the pep page, but it doesn't look active. pypi page... I can't even blame autocorrect for that one :) From manpritsinghece at gmail.com Sat Aug 22 12:51:25 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sat, 22 Aug 2020 22:21:25 +0530 Subject: [Tutor] Function definition with default argument Message-ID: Dear sir , Consider a pandas series as given below : import pandas as pd ser = pd.Series(["M", "F", "M", "F", "F", "M"]) upon printing the series we will get : 0 M 1 F 2 M 3 F 4 F 5 M dtype: object Now if i have to count number of "M' and 'F' in the series, using a function, and if i write a function and call it as given below , passing the series as a default argument in the function : def offcnt(x=ser): return x.value_counts() g = offcnt() print(g) Which gives the right answer: F 3 M 3 dtype: int64 The second way of writing and calling a function to solve this problem is : Here i have passed the series as an actual parameter in the function call. def offcnt(x): return x.value_counts() g = offcnt(ser) print(g) This also gives the right answer as written below: F 3 M 3 dtype: int64 My question is, what way of defining and calling functions should I prefer in this case, first one or second one ? Need your guidance. Regards Manprit Singh From alan.gauld at yahoo.co.uk Sat Aug 22 15:17:54 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 22 Aug 2020 20:17:54 +0100 Subject: [Tutor] Function definition with default argument In-Reply-To: References: Message-ID: On 22/08/2020 17:51, Manprit Singh wrote: > import pandas as pd > ser = pd.Series(["M", "F", "M", "F", "F", "M"]) > function, and if i write a function and call it as given below , > passing the series as a default argument in the function : > > def offcnt(x=ser): > return x.value_counts() You almost certainly do not want to do that. The reason is that the default argument is the value of ser when you define the function. If you change ser to something else and then call your function without arguments it will still use the old value of ser. Which I suspect is not what you would expect? If it is what you want you should do it more explicitly: def offcnt(x = = pd.Series(["M", "F", "M", "F", "F", "M"])) ... > The second way of writing and calling a function to solve this problem is : > Here i have passed the series as an actual parameter in the function call. > > def offcnt(x): > return x.value_counts() This is usually what you want. Then you can ass whatever value ser has and get the answer you want. The point of a default value is when you want the same value(not variable) to be used as the argument. Its often used where the value never changes or where the function is normally called to habdle one specific set of data (the set of primes say) but you want the ability to change that when needed (to the fibonacci series say) > My question is, what way of defining and calling functions should I > prefer in this case, first one or second one ? In most cases make the argument explicit if you expect it to change regularly. Also as a generality don't make the default a variable since it won't do what you 9or other users) might expect when you change the variables value. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From Richard at Damon-Family.org Sat Aug 22 15:34:41 2020 From: Richard at Damon-Family.org (Richard Damon) Date: Sat, 22 Aug 2020 15:34:41 -0400 Subject: [Tutor] Function definition with default argument In-Reply-To: References: Message-ID: <5fb4ca63-8040-342c-e3b8-9d551cec5905@Damon-Family.org> On 8/22/20 3:17 PM, Alan Gauld via Tutor wrote: > On 22/08/2020 17:51, Manprit Singh wrote: > >> import pandas as pd >> ser = pd.Series(["M", "F", "M", "F", "F", "M"]) >> function, and if i write a function and call it as given below , >> passing the series as a default argument in the function : >> >> def offcnt(x=ser): >> return x.value_counts() > You almost certainly do not want to do that. > The reason is that the default argument is the value > of ser when you define the function. If you change ser > to something else and then call your function without > arguments it will still use the old value of ser. It actually doesn't bind to the original values, but the original object. If ser is rebound by assignment, you won't see the change, but if it is mutated to some other state you will. -- Richard Damon From icarrrdo at gmail.com Mon Aug 24 01:08:12 2020 From: icarrrdo at gmail.com (Ricardo) Date: Mon, 24 Aug 2020 01:08:12 -0400 Subject: [Tutor] Python Tutorial Confusion Message-ID: This is probably a very elementary question/problem to most of you, but I?m having trouble understanding lines 5 through 10. Can someone explain it to me? ? 1? command = "" 2? started = False 3? while True: 4? ????command = input("> ").lower() 5? ????if command == "start": 6? ????????if started: 7? ????????????print("Car is already started!") 8? ????????else: 9? ????????????started = True 10? ????????????print("Car started...") 11? ????elif command == "stop": 12? ????????print("Car stopped.") 13? ????elif command == "help": 14? ????????print(""" 15 start - to start the car 16 stop - to stop the car 17 quit - to end the game 18??????? """) 19? ????elif command == "quit": 20? ????????break 21? ????else: 22???? ???print("Sorry, I don't understand that") ? The person conducting the tutorial says line 2 means the car is NOT started ? Line 5 says if command is ?start?, it prints ?Car Started?? (line10) ? Then, line 6 says ?if started? meaning if NOT started (because started = False in line2) then print ?Car is already started!?) (line7) which I don?t understand. Why would it print ?Car is already started!? (line7) if started = false (line2) meaning it is NOT started. ? Then line 9 sets started = True and it just confuses me. Sorry for such a beginner question. ? ? From alan.gauld at yahoo.co.uk Mon Aug 24 04:23:33 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 24 Aug 2020 09:23:33 +0100 Subject: [Tutor] Python Tutorial Confusion In-Reply-To: References: Message-ID: On 24/08/2020 06:08, Ricardo wrote: > 1? command = "" > 2? started = False > 3? while True: Note that we are entering a loop so this following code will be executed many times not just once. > 4? ????command = input("> ").lower() > 5? ????if command == "start": First time through the car will be NOT started so this command must start the car. On subsequent cycles of the code the car may already be started so we need to check for that. We cannot tell in advance and users often enter non-sensical commands.(like starting a car that is already started!) > 6? ????????if started: > 7? ????????????print("Car is already started!") So just in case we check here. On the first time through the loop this will never be executed. On subsequent iterations it might be. > 8? ????????else: > 9? ????????????started = True > 10? ????????????print("Car started...") If the car was NOT started then we must now start it because that's what the user asked us to do. > 11? ????elif command == "stop": > 12? ????????print("Car stopped.") But this is probably a fault since as well as printing "stopped" we should also set started to false to actually stop the car! > 13? ????elif command == "help": > 14? ????????print(""" > 15 start - to start the car > 16 stop - to stop the car > 17 quit - to end the game > 18??????? """) > 19? ????elif command == "quit": > 20? ????????break This exits the while loop and therefore the program. > 21? ????else: > 22???? ???print("Sorry, I don't understand that") > The person conducting the tutorial says line 2 means the car is NOT > started Wich is correct when we first enter the loop, and only then. After entering the loop started may get changed to true at which point the car is started. > Line 5 says if command is ?start?, it prints ?Car Started?? (line10) It also starts the car by setting started to true. The print line is not the important one, its the start assignment. Thinking in terms of a real car the assignment is like turning on the ignition, the print is like the dashboard light coming on. The light is only an indication to the user, its turning the key that actually starts the engine. But line 5 is only executed if the car is not already started. As is the case the firt time through the loop. > Then, line 6 says ?if started? meaning if NOT started (because started = No it does not mean if not started, it means if started. This test only makes sense on the second, third, fourth, etc times through the loop. On the first time it will always fail. > False in line2) then print ?Car is already started!?) (line7) which I > don?t understand. Why would it print ?Car is already started!? (line7) if > started = false (line2) meaning it is NOT started. Because line 2 is outside the loop (in what is called the initialization code) and only executed once. But inside the loop started can be changed in line 9 (and probably in the missing line 11a) > Then line 9 sets started = True and it just confuses me. This line is only executed the first time the user enters "start" as a command. In future loops the car is already started so it never gets back here again (unless we add the missing line 11a) The main points to understand is that line 2 is executed only once, then everything under the while statement gets executed many times - until the user types "quit". And the state of started can change on each loop around the code, it does not stay the same. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From icarrrdo at gmail.com Mon Aug 24 01:08:12 2020 From: icarrrdo at gmail.com (Ricardo) Date: Mon, 24 Aug 2020 01:08:12 -0400 Subject: [Tutor] Python Tutorial Confusion Message-ID: This is probably a very elementary question/problem to most of you, but I?m having trouble understanding lines 5 through 10. Can someone explain it to me? ? 1? command = "" 2? started = False 3? while True: 4? ????command = input("> ").lower() 5? ????if command == "start": 6? ????????if started: 7? ????????????print("Car is already started!") 8? ????????else: 9? ????????????started = True 10? ????????????print("Car started...") 11? ????elif command == "stop": 12? ????????print("Car stopped.") 13? ????elif command == "help": 14? ????????print(""" 15 start - to start the car 16 stop - to stop the car 17 quit - to end the game 18??????? """) 19? ????elif command == "quit": 20? ????????break 21? ????else: 22???? ???print("Sorry, I don't understand that") ? The person conducting the tutorial says line 2 means the car is NOT started ? Line 5 says if command is ?start?, it prints ?Car Started?? (line10) ? Then, line 6 says ?if started? meaning if NOT started (because started = False in line2) then print ?Car is already started!?) (line7) which I don?t understand. Why would it print ?Car is already started!? (line7) if started = false (line2) meaning it is NOT started. ? Then line 9 sets started = True and it just confuses me. Sorry for such a beginner question. ? ? From PythonList at DancesWithMice.info Mon Aug 24 21:17:39 2020 From: PythonList at DancesWithMice.info (dn) Date: Tue, 25 Aug 2020 13:17:39 +1200 Subject: [Tutor] Training Review: Computational Thinking for Problem Solving Message-ID: Many of us learn Python by memorising code-constructs and their use. Even over-coming this learning-curve is but a small portion of becoming a competent coder or programmer. The challenges of learning how to construct an algorithm, and/or how to analyse a real-world problem to produce a solution, are not to be found in the Python Tutorial. However, such higher-order problems often surface on the Python-Tutor and Python Discussion Lists. For newcomers (and anyone in the field who would like to fill-in topics 'missing' in his/her basic understanding), Coursera offer a "Computational Thinking for Problem Solving" course (free* or $certified) from "Penn" (University of Pennsylvania, USA). I have occupied various 'spare' moments during the last week or so, to review the course, and am recommend it to you/yours. Aside from coders, you might also mention it to any friends who want to learn 'problem-solving' (an increasingly important skill in these modern-times where the only constant is 'change') because this is not a 'computer course'. Starting at higher-level thinking, gradually more detail is added, before arriving at the level of implementing computer-based solutions in Python. It offers a (rather brief) introduction to Python. Thus could be used as a 'taster', before moving to Python-for-the-sake-of-Python course. Throughout the course reference is made to case-studies drawn from the university's wider operations. There is also an interesting topic in linguistic analysis (ie the stuff of grammar-checkers, search engines, etc) which trainees can gradually develop, stage-by-stage. Here is their introduction:- <<< Computational thinking is the process of approaching a problem in a systematic manner and creating and expressing a solution such that it can be carried out by a computer. But you don't need to be a computer scientist to think like a computer scientist! In fact, we encourage students from any field of study to take this course. Many quantitative and data-centric problems can be solved using computational thinking and an understanding of computational thinking will give you a foundation for solving problems that have real-world, social impact. In this course, you will learn about the pillars of computational thinking, how computer scientists develop and analyze algorithms, and how solutions can be realized on a computer using the Python programming language. By the end of the course, you will be able to develop an algorithm and express it to the computer by writing a simple Python program. This course will introduce you to people from diverse professions who use computational thinking to solve problems. You will engage with a unique community of analytical thinkers and be encouraged to consider how you can make a positive social impact through computational thinking. >>> 100% online Flexible deadlines Beginner Level Approx. 17 hours to complete Four 'weeks' or sessions: Pillars of Computational Thinking Expressing and Analyzing Algorithms Fundamental Operations of a Modern Computer Applied Computational Thinking Using Python https://www.coursera.org/learn/computational-thinking-problem-solving#syllabus They did conclude by uttering heresy: that graduates might like to move to "more advanced languages like Java ... JavaScript", but let's not hold that lapse of judgement against them (they are after-all, a school of Engineering)! * the $free option allows access to quizzes, tests, and assignments but not to any grading process. That said, any 'problems', phrased with at a Python background, could likely be discussed/corrected in posts to the Python-Tutor List (don't forget to declare the course and notify which session/component). Disclaimer: I use the ('competing') edX training/education platform - but for non-Python courses. -- Regards, =dn From nzbzxx at gmail.com Wed Aug 26 08:01:24 2020 From: nzbzxx at gmail.com (nzbz xx) Date: Wed, 26 Aug 2020 20:01:24 +0800 Subject: [Tutor] Converting a txt file to dictionary Message-ID: I have a plantrecords.txt file with the following format: Plantname date & time of record description description description (blank line) Plantname date & time of record description description description (blank line) . . . How do I convert this text file into a dictionary such that it gives me dict = {'plantname': [datetimerecord, description, description, description], 'plantname': [datetime.....]} so on and so forth From ulfat.hajiyev at gmail.com Wed Aug 26 06:26:36 2020 From: ulfat.hajiyev at gmail.com (Ulfat Hajiyev) Date: Wed, 26 Aug 2020 03:26:36 -0700 Subject: [Tutor] Can not install pomegranate Message-ID: Dears, 1st and foremost would like to say that I experience every time a lot of problems when downloading packages with pip. It consumes a lot of time and energy. To the point - can not install pomegranate to use it for probability. I use Windows 10, python 3.8.5, pip 20.2.2. Error is shown below email. Please advise: 1. How should I continue downloading pomegranate through pip properly, *or* maybe 2. What are alternatives(to pip) to downloading pomegranate, *and* also 3. What are other libraries for python where I can use full potential of probability. *ERROR shown below* *----------------------------------------------------* *.................* *.................* *.................* *.................* c1: fatal error C1083: Cannot open source file: 'pomegranate/distributions/NeuralNetworkWrapper.c': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\cl.exe' failed with exit status 2 ---------------------------------------- ERROR: Failed building wheel for pomegranate Running setup.py clean for pomegranate Failed to build pomegranate DEPRECATION: Could not build wheels for pomegranate which do not use PEP 517. pip will fall back to legacy 'setup.py install' for these. pip 21.0 will remove support for this functionality. A possible replacement is to fix the wheel build issue reported above. You can find discussion regarding this at https://github.com/pypa/pip/issues/8368. Installing collected packages: pomegranate Running setup.py install for pomegranate ... error ERROR: Command errored out with exit status 1: *.................* *.................* *.................* *.................* NeuralNetworkWrapper.c c1: fatal error C1083: Cannot open source file: 'pomegranate/distributions/NeuralNetworkWrapper.c': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\cl.exe' failed with exit status 2 ---------------------------------------- ERROR: Command errored out with exit status 1: 'C:\Users\GYBYM\AppData\Local\Programs\Python\Python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\GYBYM\\AppData\\Local\\Temp\\pip-install-ugry4g1v\\pomegranate\\setup.py'"'"'; __file__='"'"'C:\\Users\\GYBYM\\AppData\\Local\\Temp\\pip-install-ugry4g1v\\pomegranate\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\GYBYM\AppData\Local\Temp\pip-record-infr9vti\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\GYBYM\AppData\Local\Programs\Python\Python38-32\Include\pomegranate' Check the logs for full command output. ____________________ *end of error* Thanks. Virus-free. www.avast.com <#DAB4FAD8-2DD7-40BB-A1B8-4E2AA1F9FDF2> From __peter__ at web.de Wed Aug 26 13:29:23 2020 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 Aug 2020 19:29:23 +0200 Subject: [Tutor] Converting a txt file to dictionary References: Message-ID: nzbz xx wrote: Interesting name ;) > I have a plantrecords.txt file with the following format: > > Plantname > date & time of record > description > description > description > (blank line) > Plantname > date & time of record > description > description > description > (blank line) > . > . > . > > > How do I convert this text file into a dictionary such that it gives me > dict = {'plantname': [datetimerecord, description, description, > description], 'plantname': [datetime.....]} so on and so forth import itertools import pprint filename = "plants.txt" plants = {} with open(filename) as instream: for key, group in itertools.groupby(map(str.strip, instream), key=bool): if key: name, *rest = group plants[name] = rest pprint.pprint(plants) From mats at wichmann.us Wed Aug 26 13:31:13 2020 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 26 Aug 2020 11:31:13 -0600 Subject: [Tutor] Can not install pomegranate In-Reply-To: References: Message-ID: <31c7e71a-c63f-dc37-3e57-f3e298d246ea@wichmann.us> On 8/26/20 4:26 AM, Ulfat Hajiyev wrote: > Dears, > > 1st and foremost would like to say that I experience every time a lot of > problems when downloading packages with pip. It consumes a lot of time and > energy. > > To the point - can not install pomegranate to use it for probability. > > I use Windows 10, python 3.8.5, pip 20.2.2. Error is shown below email. > > Please advise: > 1. How should I continue downloading pomegranate through pip properly, *or* > maybe > 2. What are alternatives(to pip) to downloading pomegranate, *and* also > 3. What are other libraries for python where I can use full potential of > probability. A couple of notes: 0. Usually, the best place to get support for issues with a package is from the person or organization that produces the package. 1. you don't show how you ran the command; normally you should use your Python to install via pip, not the /command/ named pip. That is, if you successfully launch Python by using the Python Launcher, use it to launch pip: py -m pip install somepackage 2. If you look up the package you're trying to install on pypi, you can usually learn something. If nothing else, where it comes from (see #0), but also what's available to download. This link suggests that you should probably be able to install this successfully as there's a Windows version for Python 3.8 https://pypi.org/project/pomegranate/#files 3. If pip fails to find and install a matching wheel (.whl), it will fall back to picking the source package and try to build it. If there are bits of that which require a compiler, that's normally a bad look on Windows, which doesn't come with a setup compilation environment (even if you have a compiler, they're almost never set up the way the package expects). That seems to be where you are: > *ERROR shown below* > *----------------------------------------------------* > > *.................* > *.................* > *.................* > *.................* > c1: fatal error C1083: Cannot open source file: > 'pomegranate/distributions/NeuralNetworkWrapper.c': No such file or > directory > error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio > 14.0\\VC\\BIN\\cl.exe' failed with exit status 2 > ---------------------------------------- > ERROR: Failed building wheel for pomegranate So you need to figure out why it's not picking the wheel for Win/3.8 and is instead attempting to compile from source. The only thing I can spot from here is that through 3.7 there were two Windows wheels, one for 32-bit, one for 64-bit. For 3.8 the provider seems to have only uploaded a 64-bit (amd64) one. Are you by chance running 32-bit WIndows and/or Python? From truzen at gmail.com Wed Aug 26 13:31:02 2020 From: truzen at gmail.com (truzen at gmail.com) Date: Wed, 26 Aug 2020 13:31:02 -0400 Subject: [Tutor] Can not install pomegranate In-Reply-To: References: Message-ID: <014201d67bce$ac89cdc0$059d6940$@gmail.com> This may not answer your question directly, but normally when I've encounter wheel error, it's due to an incompatibility between the version of python your using and the package. It looks like someone's request an update for 3.8 in GitHub (https://github.com/jmschrei/pomegranate/issues/555) but that's was tacked onto an unrelated thread. The author also mentions forgetting to "upload the wheels for this version", and it looks like the issue is still open (https://github.com/jmschrei/pomegranate/issues/782). I'm still newbie at this, so someone else might be able to chime in, but my recommendation would be to try an older version of Python and/or Pomegranate. -Thomas -----Original Message----- From: Tutor On Behalf Of Ulfat Hajiyev Sent: Wednesday, August 26, 2020 6:27 AM To: tutor at python.org Subject: [Tutor] Can not install pomegranate Dears, 1st and foremost would like to say that I experience every time a lot of problems when downloading packages with pip. It consumes a lot of time and energy. To the point - can not install pomegranate to use it for probability. I use Windows 10, python 3.8.5, pip 20.2.2. Error is shown below email. Please advise: 1. How should I continue downloading pomegranate through pip properly, *or* maybe 2. What are alternatives(to pip) to downloading pomegranate, *and* also 3. What are other libraries for python where I can use full potential of probability. *ERROR shown below* *----------------------------------------------------* *.................* *.................* *.................* *.................* c1: fatal error C1083: Cannot open source file: 'pomegranate/distributions/NeuralNetworkWrapper.c': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\cl.exe' failed with exit status 2 ---------------------------------------- ERROR: Failed building wheel for pomegranate Running setup.py clean for pomegranate Failed to build pomegranate DEPRECATION: Could not build wheels for pomegranate which do not use PEP 517. pip will fall back to legacy 'setup.py install' for these. pip 21.0 will remove support for this functionality. A possible replacement is to fix the wheel build issue reported above. You can find discussion regarding this at https://github.com/pypa/pip/issues/8368. Installing collected packages: pomegranate Running setup.py install for pomegranate ... error ERROR: Command errored out with exit status 1: *.................* *.................* *.................* *.................* NeuralNetworkWrapper.c c1: fatal error C1083: Cannot open source file: 'pomegranate/distributions/NeuralNetworkWrapper.c': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\cl.exe' failed with exit status 2 ---------------------------------------- ERROR: Command errored out with exit status 1: 'C:\Users\GYBYM\AppData\Local\Programs\Python\Python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\GYBYM\\AppData\\Local\\Temp\\pip-install-ugry4g1v\\pomegrana te\\setup.py'"'"'; __file__='"'"'C:\\Users\\GYBYM\\AppData\\Local\\Temp\\pip-install-ugry4g1v\\ pomegranate\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\GYBYM\AppData\Local\Temp\pip-record-infr9vti\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\GYBYM\AppData\Local\Programs\Python\Python38-32\Include\pomegranat e' Check the logs for full command output. ____________________ *end of error* Thanks. Virus-free. www.avast.com <#DAB4FAD8-2DD7-40BB-A1B8-4E2AA1F9FDF2> _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From robertvstepp at gmail.com Thu Aug 27 21:34:45 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Thu, 27 Aug 2020 20:34:45 -0500 Subject: [Tutor] Why does "window = tk.Tk()" open a tkinter window when typed in the Python interpreter? Message-ID: I learned something new today about tkinter from a book [1], but I do not understand why it happens. If I do this in the Python interpreter: Python 3.8.3 (default, Jul 11 2020, 16:27:50) [GCC 9.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. 3.8.3: import tkinter as tk 3.8.3: window = tk.Tk() A tkinter window opens despite there being no explicit call to window.mainloop(). Why is this so? And even more interesting (and useful) I can see the execution of a tkinter window being built widget by widget like so with the Label widget: 3.8.3: label = tk.Label(window, text="First label.") 3.8.3: label.pack() 3.8.3: label.config(text='Second label.') I am greatly looking forward to someone's explanation of why all of this works without an explicit call to window.mainloop(). [1] "Practical Programming -- An Introduction to Computer Science Using Python 3.6, Third Edition" by Paul Gries, et al, c. 2017. Chapter 16. Creating Graphical User Interfaces, p. 324. -- boB From alan.gauld at yahoo.co.uk Fri Aug 28 03:48:22 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 28 Aug 2020 08:48:22 +0100 Subject: [Tutor] Why does "window = tk.Tk()" open a tkinter window when typed in the Python interpreter? In-Reply-To: References: Message-ID: On 28/08/2020 02:34, boB Stepp wrote: > 3.8.3: import tkinter as tk > 3.8.3: window = tk.Tk() > > A tkinter window opens despite there being no explicit call to > window.mainloop(). Why is this so? Because it's what Tcl/Tk does... > And even more interesting (and useful) I can see the execution of a > tkinter window being built widget by widget I've always assumed that's why the window appears when it does: so that you can see the widgets as you add them when working interactively. But I confess I have never investigated deeply, its just a handy feature! > I am greatly looking forward to someone's explanation of why all of > this works without an explicit call to window.mainloop(). mainloop() turns on the event handling, until then the window is just a graphic image on screen. But you don't need the mainloop running to draw on the screen, its only when you want to interact with it that you have to start mainloop(). Note that this behaviour depends on the environment. If you use a shell within an IDE it might not happen, but if you use a shell from the OS it will (IDLE works like this too). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From manpritsinghece at gmail.com Fri Aug 28 07:18:10 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Fri, 28 Aug 2020 16:48:10 +0530 Subject: [Tutor] Confusion about name in the target list of for loop Message-ID: Dear sir , Consider a problem of finding the average of numbers(1,2, 3, 4, 5). if this is solved using the for loop in this way, is it correct ? s = 0 for i in range(1, 6): s = s + i print(s / i) 3.0 As we know, the for loop in the above example will produce the sum of numbers, 1, 2, 3, 4, 5. Now as the last value of variable i (which is a variable in the target list of for loop) is equal to the number of loops executed, it can be used to find the average ?. s divided by i will give the average . My question is, the way i have used variable in the target list, just after the completion of for loop, is its appropriate use or not. Regards Manprit Singh From alan.gauld at yahoo.co.uk Fri Aug 28 08:33:30 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 28 Aug 2020 13:33:30 +0100 Subject: [Tutor] Confusion about name in the target list of for loop In-Reply-To: References: Message-ID: On 28/08/2020 12:18, Manprit Singh wrote: > Dear sir , > Consider a problem of finding the average of numbers(1,2, 3, 4, 5). if this > is solved using the for loop in this way, is it correct ? > > s = 0 > for i in range(1, 6): > s = s + i > print(s / i) > 3.0 In that it will work yes it is correct. However, it is far from the best approach. > My question is, the way i have used variable in the target list, just after > the completion of for loop, is its appropriate use or not. Remember that 'i' will have the value of the last member of the collection not the index. So... It's only appropriate if dealing with a straight range of numbers. If the numbers were in an unordered, non-sequential list it would break. You could use the enumerate() function to get the index of the item - that will work for any collection. Better however is to use the sum() and len() functions: ave = sum(collection)/len(collection) No loops, no risk of boundary errors. Much more reliable. There is also the Python "statistics" module in the standard library which can deliver several variations on average: mean, median, etc. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From Richard at Damon-Family.org Fri Aug 28 08:35:11 2020 From: Richard at Damon-Family.org (Richard Damon) Date: Fri, 28 Aug 2020 08:35:11 -0400 Subject: [Tutor] Confusion about name in the target list of for loop In-Reply-To: References: Message-ID: <1e1a22d7-469d-6aab-ed42-2cef486cb964@Damon-Family.org> On 8/28/20 7:18 AM, Manprit Singh wrote: > Dear sir , > Consider a problem of finding the average of numbers(1,2, 3, 4, 5). if this > is solved using the for loop in this way, is it correct ? > > s = 0 > for i in range(1, 6): > s = s + i > print(s / i) > 3.0 > > As we know, the for loop in the above example will produce the sum of > numbers, > 1, 2, 3, 4, 5. Now as the last value of variable i (which is a variable in > the target list of for loop) is equal to the number of loops executed, it > can be used to find the average ?. s divided by i will give the average . > > My question is, the way i have used variable in the target list, just after > the completion of for loop, is its appropriate use or not. > > Regards > Manprit Singh For a general average operation, it wouldn't be good as you are assuming that the last number equals the number of points, which isn't generally true (ranges beginning with 1 and stepping by 1 are one major special case where it works) -- Richard Damon From robertvstepp at gmail.com Fri Aug 28 16:38:15 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Fri, 28 Aug 2020 15:38:15 -0500 Subject: [Tutor] Why does "window = tk.Tk()" open a tkinter window when typed in the Python interpreter? In-Reply-To: References: Message-ID: On Fri, Aug 28, 2020 at 2:48 AM Alan Gauld via Tutor wrote: > > On 28/08/2020 02:34, boB Stepp wrote: > > > 3.8.3: import tkinter as tk > > 3.8.3: window = tk.Tk() > > > > A tkinter window opens despite there being no explicit call to > > window.mainloop(). Why is this so? > > Because it's what Tcl/Tk does... Perhaps I should phrase the question differently: Why does this happen in the interpreter but does *not* happen if I run a program without calling window.mainloop()? -- boB From Richard at Damon-Family.org Fri Aug 28 17:22:37 2020 From: Richard at Damon-Family.org (Richard Damon) Date: Fri, 28 Aug 2020 17:22:37 -0400 Subject: [Tutor] Why does "window = tk.Tk()" open a tkinter window when typed in the Python interpreter? In-Reply-To: References: Message-ID: On 8/28/20 4:38 PM, boB Stepp wrote: > On Fri, Aug 28, 2020 at 2:48 AM Alan Gauld via Tutor wrote: >> On 28/08/2020 02:34, boB Stepp wrote: >> >>> 3.8.3: import tkinter as tk >>> 3.8.3: window = tk.Tk() >>> >>> A tkinter window opens despite there being no explicit call to >>> window.mainloop(). Why is this so? >> Because it's what Tcl/Tk does... > Perhaps I should phrase the question differently: Why does this > happen in the interpreter but does *not* happen if I run a program > without calling window.mainloop()? > Because Python when in interactive mode uses tkinter, and has a main loop of it own that will pump your messages if you don't. -- Richard Damon From carrieudo at gmail.com Fri Aug 28 16:32:02 2020 From: carrieudo at gmail.com (Carrie Udowychenko) Date: Fri, 28 Aug 2020 16:32:02 -0400 Subject: [Tutor] Turtle help Message-ID: I am new to Python and have tried every command I can find but still do not seem to be able to access a turtle library and do any drawing. I have tried: import turtle and from turtle import * But after both of these any commands like forward or right still show errors and forward is not recognized. Please help Thanks! Carrie From alan.gauld at yahoo.co.uk Fri Aug 28 18:52:48 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 28 Aug 2020 23:52:48 +0100 Subject: [Tutor] Why does "window = tk.Tk()" open a tkinter window when typed in the Python interpreter? In-Reply-To: References: Message-ID: On 28/08/2020 21:38, boB Stepp wrote: >> Because it's what Tcl/Tk does... > > Perhaps I should phrase the question differently: Why does this > happen in the interpreter but does *not* happen if I run a program > without calling window.mainloop()? I repeat, because its what Tcl/Tk does.... Now why (or more to the point how) Tcl/Tk does that, I have no idea! Sorry... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From marc.tompkins at gmail.com Fri Aug 28 18:53:47 2020 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Fri, 28 Aug 2020 15:53:47 -0700 Subject: [Tutor] Turtle help In-Reply-To: References: Message-ID: On Fri, Aug 28, 2020 at 3:47 PM Carrie Udowychenko wrote: > I am new to Python and have tried every command I can find but still do not > seem to be able to access a turtle library and do any drawing. > > I have tried: import turtle > and from turtle import * > > But after both of these any commands like forward or right still show > errors and forward is not recognized. Please help > Try this? https://opentechschool.github.io/python-beginners/en/simple_drawing.html From alan.gauld at yahoo.co.uk Fri Aug 28 18:54:16 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 28 Aug 2020 23:54:16 +0100 Subject: [Tutor] Why does "window = tk.Tk()" open a tkinter window when typed in the Python interpreter? In-Reply-To: References: Message-ID: On 28/08/2020 22:22, Richard Damon wrote: >> Perhaps I should phrase the question differently: Why does this >> happen in the interpreter but does *not* happen if I run a program >> without calling window.mainloop()? >> > Because Python when in interactive mode uses tkinter, and has a main > loop of it own that will pump your messages if you don't Nope, the regular Python interpreter does not use tkinter, nor even need tkinter to be installed. This may require some examination of the source. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Fri Aug 28 18:55:34 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 28 Aug 2020 23:55:34 +0100 Subject: [Tutor] Turtle help In-Reply-To: References: Message-ID: On 28/08/2020 21:32, Carrie Udowychenko wrote: > I am new to Python and have tried every command I can find but still do not > seem to be able to access a turtle library and do any drawing. > > I have tried: import turtle > and from turtle import * > > But after both of these any commands like forward or right still show > errors and forward is not recognized. Please help The missing magic may be turtle.pendown() Once you do that the turtle and its actions become visible. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From robertvstepp at gmail.com Fri Aug 28 22:13:53 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Fri, 28 Aug 2020 21:13:53 -0500 Subject: [Tutor] Why does "window = tk.Tk()" open a tkinter window when typed in the Python interpreter? In-Reply-To: References: Message-ID: On Fri, Aug 28, 2020 at 5:55 PM Alan Gauld via Tutor wrote: > > On 28/08/2020 22:22, Richard Damon wrote: > > >> Perhaps I should phrase the question differently: Why does this > >> happen in the interpreter but does *not* happen if I run a program > >> without calling window.mainloop()? > >> > > Because Python when in interactive mode uses tkinter, and has a main > > loop of it own that will pump your messages if you don't > Nope, the regular Python interpreter does not use tkinter, > nor even need tkinter to be installed. > > This may require some examination of the source. Are you inclined to think the source code of Tcl/Tk is where to look, or do you think it is how Python's wrapper, tkinter, implements Tcl/Tk is where I should look? I've been trying to research this online and have been unsuccessful so far -- not quite sure how to phrase an effective set of search terms. I did come across that the scripting language, Tcl, seems to have its own interpreter mode, so your initial comments may be spot on if this was the behavior being sought up front by Tcl itself. -- boB From breamoreboy at gmail.com Fri Aug 28 18:53:37 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Fri, 28 Aug 2020 23:53:37 +0100 Subject: [Tutor] Turtle help In-Reply-To: References: Message-ID: On 28/08/2020 21:32, Carrie Udowychenko wrote: > I am new to Python and have tried every command I can find but still do not > seem to be able to access a turtle library and do any drawing. > > I have tried: import turtle > and from turtle import * > > But after both of these any commands like forward or right still show > errors and forward is not recognized. Please help > > Thanks! > Please help us to help you by giving the entire traceback, Python version and your OS, thanks. The traceback will look something like this:- import cobblers Traceback (most recent call last): File "", line 1, in ModuleNotFoundError: No module named 'cobblers' -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From nzbzxx at gmail.com Sat Aug 29 02:30:47 2020 From: nzbzxx at gmail.com (nzbz xx) Date: Sat, 29 Aug 2020 14:30:47 +0800 Subject: [Tutor] Converting a txt file to dictionary In-Reply-To: References: Message-ID: I'm trying to create a def function code to validate user input. I would want the user to only input either 1 or 2. Any other inputs would reprompt the user again. This is what i have so far: def data_validation(User_Decision): try: if User_Decision != 1 or User_Decision != 2: print("Please enter option number: 1 or 2.") except ValueError: print("Input is invalid. Please try again.") User_Decision = int(input(">")) while data_validation(User_Decision): User_Decision = input(">") On Thu, Aug 27, 2020 at 1:30 AM Peter Otten <__peter__ at web.de> wrote: > nzbz xx wrote: > > Interesting name ;) > > > I have a plantrecords.txt file with the following format: > > > > Plantname > > date & time of record > > description > > description > > description > > (blank line) > > Plantname > > date & time of record > > description > > description > > description > > (blank line) > > . > > . > > . > > > > > > How do I convert this text file into a dictionary such that it gives me > > dict = {'plantname': [datetimerecord, description, description, > > description], 'plantname': [datetime.....]} so on and so forth > > > import itertools > import pprint > > filename = "plants.txt" > plants = {} > with open(filename) as instream: > for key, group in itertools.groupby(map(str.strip, instream), > key=bool): > if key: > name, *rest = group > plants[name] = rest > > pprint.pprint(plants) > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From __peter__ at web.de Sat Aug 29 03:47:51 2020 From: __peter__ at web.de (Peter Otten) Date: Sat, 29 Aug 2020 09:47:51 +0200 Subject: [Tutor] Turtle help References: Message-ID: Carrie Udowychenko wrote: > I am new to Python and have tried every command I can find but still do > not seem to be able to access a turtle library and do any drawing. > > I have tried: import turtle > and from turtle import * The difference between these two forms of import is that with the first you need qualified names... import turtle for i in range(4): turtle.forward(50) turtle.left(90) turtle.exitonclick() whereas the second allows you to use the names from the module directly: from turtle import * for i in range(4): forward(50) left(90) exitonclick() This may be more convenient for your first experiments, but will get confusing once you import more than a single module. > But after both of these any commands like forward or right still show > errors and forward is not recognized. Please help Does the error look like this? Traceback (most recent call last): File "turtle.py", line 1, in from turtle import * File "/home/carrie/turtle.py", line 4, in forward(50) NameError: name 'forward' is not defined This is called "traceback", and if you copy and paste it in your post asking for help you provide us with a very useful means to debug your problem. Without that we can only guess: Did you call your own script turtle.py ? Then it hides the "real" turtle module provided by Python. Rename your script to myturtle.py, say, and it should work. From alan.gauld at yahoo.co.uk Sat Aug 29 04:04:01 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 29 Aug 2020 09:04:01 +0100 Subject: [Tutor] User validation was: Re: Converting a txt file to dictionary In-Reply-To: References: Message-ID: Please don;t start a new discussion in another thread. start a new discussion with a fresh message with a new subject line. That way searches in the archives make more sense. On 29/08/2020 07:30, nzbz xx wrote: > I'm trying to create a def function code to validate user input. I would > want the user to only input either 1 or 2. Any other inputs would reprompt > the user again. This is what i have so far: > > def data_validation(User_Decision): > try: > if User_Decision != 1 or User_Decision != 2: > print("Please enter option number: 1 or 2.") > except ValueError: > print("Input is invalid. Please try again.") This will work although I doubt the try/except will catch any value errors since you don;t do anything that would cause one. Also your test would be easier using an 'in test: if User_Decision not in [1,2]: print(....) That is much easier to extend if new values need to be included in the future. > User_Decision = int(input(">")) > > while data_validation(User_Decision): > User_Decision = input(">") But here you are testing the return value of your function. But you do not return anything from your function you only print stuff. Python will supply a default value of None in that case which the while loop sees as False and so never executes. I would suggest converting your function to simply test the value and return True or false, Then in the while loop add the error message. Also its often clearer to name predicate functions(those with a boolean result) as a statement of intent: def data_valid(user_decision): return user_decision in [1,2] choice = int(input('> ')) while not data_valid(choice): print("You must enter 1 or 2") choice = int(input('> ')) Or more Pythonically: while True: choice = int(input('> ')) if data_valid(choice): break print(" You must enter 1 or 2") Which avoids entering the input line twice. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Sat Aug 29 04:09:58 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 29 Aug 2020 09:09:58 +0100 Subject: [Tutor] Why does "window = tk.Tk()" open a tkinter window when typed in the Python interpreter? In-Reply-To: References: Message-ID: On 29/08/2020 03:13, boB Stepp wrote: >> This may require some examination of the source. > > Are you inclined to think the source code of Tcl/Tk is where to look, I suspect so since the behaviour is the same as for Python. Tkinter is just a wrapper around Tk so whatever Tk does Tkinter will do. > or do you think it is how Python's wrapper, tkinter, implements > Tcl/Tk is where I should look? It might need both. Id suggest asking on the tkinter mailing list. Those guys will likely know, or at least know where to look! On gmane its found at: gmane.comp.python.tkinter > phrase an effective set of search terms. I did come across that the > scripting language, Tcl, seems to have its own interpreter mode, so > your initial comments may be spot on if this was the behavior being > sought up front by Tcl itself. Yes, there is a dedicated interpreter for both Tcl (tclsh) and for Tk (wish). When you run wish it starts up the same blank window you get with a call to Tk() so I'm guessing that somehow tkinter fires up wish when in interactive mode. But that is just a guess... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Sat Aug 29 04:13:51 2020 From: __peter__ at web.de (Peter Otten) Date: Sat, 29 Aug 2020 10:13:51 +0200 Subject: [Tutor] Why does "window = tk.Tk()" open a tkinter window when typed in the Python interpreter? References: Message-ID: boB Stepp wrote: > On Fri, Aug 28, 2020 at 5:55 PM Alan Gauld via Tutor > wrote: >> >> On 28/08/2020 22:22, Richard Damon wrote: >> >> >> Perhaps I should phrase the question differently: Why does this >> >> happen in the interpreter but does *not* happen if I run a program >> >> without calling window.mainloop()? >> >> >> > Because Python when in interactive mode uses tkinter, and has a main >> > loop of it own that will pump your messages if you don't >> Nope, the regular Python interpreter does not use tkinter, >> nor even need tkinter to be installed. >> >> This may require some examination of the source. > > Are you inclined to think the source code of Tcl/Tk is where to look, > or do you think it is how Python's wrapper, tkinter, implements > Tcl/Tk is where I should look? I've been trying to research this > online and have been unsuccessful so far -- not quite sure how to > phrase an effective set of search terms. I did come across that the > scripting language, Tcl, seems to have its own interpreter mode, so > your initial comments may be spot on if this was the behavior being > sought up front by Tcl itself. The following comment in Modules/_tkinter.c /* If Tcl can wait for a Unix file descriptor, define the EventHook() routine which uses this to handle Tcl events while the user is typing commands. */ indicates that the behaviour you observe is implemented in CPython. When you run a script like import tkinter as tk root = tk.Tk() button = tk.Button(root, text="Press", command=lambda: print("pressed")) button.pack() input() you'll see that it's not just the look (pressing the button will work like expected) and that it's not limited to the interpreter. From __peter__ at web.de Sat Aug 29 04:30:36 2020 From: __peter__ at web.de (Peter Otten) Date: Sat, 29 Aug 2020 10:30:36 +0200 Subject: [Tutor] User validation was: Re: Converting a txt file to dictionary References: Message-ID: Alan Gauld via Tutor wrote: > Please don;t start a new discussion in another thread. start a new > discussion with a fresh message with a new subject line. That way > searches in the archives make more sense. > > > On 29/08/2020 07:30, nzbz xx wrote: >> I'm trying to create a def function code to validate user input. I would >> want the user to only input either 1 or 2. Any other inputs would >> reprompt the user again. This is what i have so far: >> >> def data_validation(User_Decision): >> try: >> if User_Decision != 1 or User_Decision != 2: >> print("Please enter option number: 1 or 2.") >> except ValueError: >> print("Input is invalid. Please try again.") > > This will work although I doubt the try/except will catch any value > errors since you don;t do anything that would cause one. > > Also your test would be easier using an 'in test: > > if User_Decision not in [1,2]: > print(....) > > That is much easier to extend if new values need to be > included in the future. > >> User_Decision = int(input(">")) >> >> while data_validation(User_Decision): >> User_Decision = input(">") > > But here you are testing the return value of your function. > But you do not return anything from your function you only > print stuff. Python will supply a default value of None in > that case which the while loop sees as False and so > never executes. > > I would suggest converting your function to simply test the > value and return True or false, Then in the while loop add > the error message. Also its often clearer to name predicate > functions(those with a boolean result) as a statement of > intent: > > > def data_valid(user_decision): > return user_decision in [1,2] > > choice = int(input('> ')) > while not data_valid(choice): > print("You must enter 1 or 2") > choice = int(input('> ')) > > Or more Pythonically: > > while True: > choice = int(input('> ')) > if data_valid(choice): > break > print(" You must enter 1 or 2") > > Which avoids entering the input line twice. In this case it might be ok to use the "walrus" operator: while not data_valid(choice:=int(input('> '))): print("You must enter 1 or 2") print(choice) However, for all but the tiniest scripts I would not want that they raise a ValueError on wrong user input. To cover both cases, an illegal number and not a number at all, you need something a little more complex: def one_or_two(): while True: try: result = int(input("> ")) except ValueError: pass else: if result in {1, 2}: return result print("You must enter 1 or 2") print(one_or_two()) From alan.gauld at yahoo.co.uk Sat Aug 29 06:27:54 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 29 Aug 2020 11:27:54 +0100 Subject: [Tutor] Why does "window = tk.Tk()" open a tkinter window when typed in the Python interpreter? In-Reply-To: References: Message-ID: On 29/08/2020 09:13, Peter Otten wrote: > indicates that the behaviour you observe is implemented in CPython. > When you run a script like > > import tkinter as tk > root = tk.Tk() > button = tk.Button(root, text="Press", command=lambda: print("pressed")) > button.pack() > input() > > you'll see that it's not just the look (pressing the button will work like > expected) and that it's not limited to the interpreter. How interesting. Which makes me wonder what exactly the mainloop() function does extra? I tried it in the interpreter and sure enough it seems to work as expected but when you call mainloop() it stops reading input at the Python prompt. But the Tkinter GUI works with or without mainloop() which I didn't expect. Definitely worth some more digging. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From robertvstepp at gmail.com Sat Aug 29 12:04:08 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 29 Aug 2020 11:04:08 -0500 Subject: [Tutor] Validating specific integer input [Was: Re: Converting a txt file to dictionary] In-Reply-To: References: Message-ID: It might have been better if you had created a new thread as your question (statement) below is wholly unrelated to this subject line. On Sat, Aug 29, 2020 at 2:38 AM nzbz xx wrote: > > I'm trying to create a def function code to validate user input. I would > want the user to only input either 1 or 2. Any other inputs would reprompt > the user again. This is what i have so far: > > def data_validation(User_Decision): > try: > if User_Decision != 1 or User_Decision != 2: > print("Please enter option number: 1 or 2.") > except ValueError: > print("Input is invalid. Please try again.") Think about this for a moment. Inside your function above, what statement would ever produce a ValueError exception? If unsure experiment with a statement in the interpreter. Also, what if it *is* valid user input? How would this function *return* the validated user input back to the code that called it? > User_Decision = int(input(">")) You use this in your while loop below, but without the enclosing "int()". Is it really needed in both places? BTW, would the above statement ever generate a ValueError exception? > while data_validation(User_Decision): > User_Decision = input(">") We have reached the end of the code you provided. Have you run this code? What happened? Is it what you expected? Notice that you have never called your validation function, so it is doing nothing for you. Where would the logical place to call it and validate user input? Another question: Will your while loop ever end? Will the user ever be able to successfully enter input and have your program continue to process the user input? How should you exit your loop upon successful user input validation? Should your loop be the place to call your user validation function? And where should "int()" be used? In the loop? Or in your function? Isn't calling "int()" on user input the way a ValueError may arise? A thought: If I were the user, with the code you have showed us, I would have no clue as to what you wanted me to enter for input. Do you have an introduction displayed (that you haven't shown us) that explains this to the user? Another question for your input validation: Do you need to worry about the user entering floats? I suspect not as int() conveniently truncates decimal places from entered floats, but you should at least briefly think about it. I apologize in advance that I have not provided any answers, only questions, but I believe that if you consider the questions you will see what you need to do to achieve your desired result. If you get stuck submit your new code and any exception tracebacks (fully cut-and-paste into your email please) and I am sure we will get you where you would like to be going. HTH! -- boB From robertvstepp at gmail.com Sat Aug 29 12:21:53 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 29 Aug 2020 11:21:53 -0500 Subject: [Tutor] Validating specific integer input [Was: Re: Converting a txt file to dictionary] In-Reply-To: References: Message-ID: On Sat, Aug 29, 2020 at 11:04 AM boB Stepp wrote: > On Sat, Aug 29, 2020 at 2:38 AM nzbz xx wrote: > > while data_validation(User_Decision): > > User_Decision = input(">") > > We have reached the end of the code you provided. Have you run this > code? What happened? Is it what you expected? > > Notice that you have never called your validation function, so it is > doing nothing for you. Where would the logical place to call it and > validate user input? Ugh. I fell asleep at the switch here! You *do* call your validation function, but as you never explicitly return anything from that function it is not doing what you expect. Note that if you do not return anything from a function explicitly it returns "None". -- boB From robertvstepp at gmail.com Sat Aug 29 12:58:00 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 29 Aug 2020 11:58:00 -0500 Subject: [Tutor] Why does "window = tk.Tk()" open a tkinter window when typed in the Python interpreter? In-Reply-To: References: Message-ID: On Sat, Aug 29, 2020 at 3:14 AM Peter Otten <__peter__ at web.de> wrote: > > boB Stepp wrote: > > > On Fri, Aug 28, 2020 at 5:55 PM Alan Gauld via Tutor > > wrote: > >> This may require some examination of the source. > > > > Are you inclined to think the source code of Tcl/Tk is where to look, > > or do you think it is how Python's wrapper, tkinter, implements > > Tcl/Tk is where I should look? I've been trying to research this > > online and have been unsuccessful so far -- not quite sure how to > > phrase an effective set of search terms. I did come across that the > > scripting language, Tcl, seems to have its own interpreter mode, so > > your initial comments may be spot on if this was the behavior being > > sought up front by Tcl itself. > > The following comment in Modules/_tkinter.c > > /* If Tcl can wait for a Unix file descriptor, define the EventHook() > routine > which uses this to handle Tcl events while the user is typing commands. > */ > > indicates that the behaviour you observe is implemented in CPython. Ah! Thanks, Peter! > When you run a script like > > import tkinter as tk > root = tk.Tk() > button = tk.Button(root, text="Press", command=lambda: print("pressed")) > button.pack() > input() > > you'll see that it's not just the look (pressing the button will work like > expected) and that it's not limited to the interpreter. This gets even more interesting -- and potentially useful. Again, thanks again, Peter. -- boB From nzbzxx at gmail.com Sat Aug 29 13:17:03 2020 From: nzbzxx at gmail.com (nzbz xx) Date: Sun, 30 Aug 2020 01:17:03 +0800 Subject: [Tutor] Writing a dictionary to txt file Message-ID: I have a txt file of records that I have converted into a dictionary. How can I write this dictionary back to the txt file after appending/replacing the values of the dictionary keys? From alan.gauld at yahoo.co.uk Sat Aug 29 17:33:34 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 29 Aug 2020 22:33:34 +0100 Subject: [Tutor] Writing a dictionary to txt file In-Reply-To: References: Message-ID: On 29/08/2020 18:17, nzbz xx wrote: > I have a txt file of records that I have converted into a dictionary. How > can I write this dictionary back to the txt file after appending/replacing > the values of the dictionary keys? There are sio many ways to do this that its hard to give advice without more details. Do you have a data specification for the output? What kind of data is stored in the dictionary? It potentially could be arbitrarily complex and so needs a complex text specification. But it could just be strings in which case it is nearly trivial. You need to give us a lot more information before we can give solid advice. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From cs at cskk.id.au Sat Aug 29 18:01:56 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 30 Aug 2020 08:01:56 +1000 Subject: [Tutor] Writing a dictionary to txt file In-Reply-To: References: Message-ID: <20200829220156.GA42790@cskk.homeip.net> On 29Aug2020 22:33, Alan Gauld wrote: >On 29/08/2020 18:17, nzbz xx wrote: >> I have a txt file of records that I have converted into a dictionary. How >> can I write this dictionary back to the txt file after appending/replacing >> the values of the dictionary keys? > >There are sio many ways to do this that its hard to give advice without >more details. > >Do you have a data specification for the output? Yes, because the OP got the data from that same text file to start with. So the OP just needs to reverse the parsing process used to read the data. Without seeing the code it is hard to be more specific. Cheers, Cameron Simpson From nzbzxx at gmail.com Sat Aug 29 23:28:51 2020 From: nzbzxx at gmail.com (nzbz xx) Date: Sun, 30 Aug 2020 11:28:51 +0800 Subject: [Tutor] Writing a dictionary to txt file In-Reply-To: <20200829220156.GA42790@cskk.homeip.net> References: <20200829220156.GA42790@cskk.homeip.net> Message-ID: The original txt file is written in this format: Plant 1 date & time description description description (Blank line) Plant 2 ... .... ... I have converted this file into dict = {'Plant 1': ['datetime','description','description','description'], 'Plant2' : ['datetime',....]}. So how can i write this dict back to the txt file in the same format? On Sun, Aug 30, 2020 at 7:31 AM Cameron Simpson wrote: > On 29Aug2020 22:33, Alan Gauld wrote: > >On 29/08/2020 18:17, nzbz xx wrote: > >> I have a txt file of records that I have converted into a dictionary. > How > >> can I write this dictionary back to the txt file after > appending/replacing > >> the values of the dictionary keys? > > > >There are sio many ways to do this that its hard to give advice without > >more details. > > > >Do you have a data specification for the output? > > Yes, because the OP got the data from that same text file to start with. > > So the OP just needs to reverse the parsing process used to read the > data. > > Without seeing the code it is hard to be more specific. > > Cheers, > Cameron Simpson > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From joel.goldstick at gmail.com Sun Aug 30 03:32:35 2020 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 30 Aug 2020 03:32:35 -0400 Subject: [Tutor] Writing a dictionary to txt file In-Reply-To: References: <20200829220156.GA42790@cskk.homeip.net> Message-ID: On Sun, Aug 30, 2020 at 3:22 AM nzbz xx wrote: > > The original txt file is written in this format: > > Plant 1 > date & time > description > description > description > (Blank line) > Plant 2 > ... > .... > ... > > I have converted this file into dict = {'Plant 1': > ['datetime','description','description','description'], 'Plant2' : > ['datetime',....]}. So how can i write this dict back to the txt file in > the same format? > > You may want to look at the pickle library. https://docs.python.org/3/library/pickle.html Writing a file that has been pickled, doesn't produce 'text', but it allows you to save your dictionary, and later you can read the file and unpickle it back to the dictionary you created earlier. I'm not sure if this is what you are going for, but its how I read your message. From alan.gauld at yahoo.co.uk Sun Aug 30 03:57:37 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 30 Aug 2020 08:57:37 +0100 Subject: [Tutor] Writing a dictionary to txt file In-Reply-To: References: <20200829220156.GA42790@cskk.homeip.net> Message-ID: On 30/08/2020 04:28, nzbz xx wrote: > The original txt file is written in this format: > > Plant 1 > date & time > description > description > description > (Blank line) > Plant 2 > ... > .... > ... > > I have converted this file into dict = {'Plant 1': > ['datetime','description','description','description'], 'Plant2' : > ['datetime',....]}. So how can i write this dict back to the txt file in > the same format? It looks like you need two loops: an outer one to read the dictionary keys and an inner one to process the list of value items for key in thedict: write key to file for item in thedict[key]: write item write blank line If it needs to go back in "the same" file then the normal approach would be to read the data from the file rename the file file.old or similar write the data to a new file with the original name if successful delete the .old version else delete the new file and rename .old back to the original. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Sun Aug 30 03:59:48 2020 From: __peter__ at web.de (Peter Otten) Date: Sun, 30 Aug 2020 09:59:48 +0200 Subject: [Tutor] Writing a dictionary to txt file References: <20200829220156.GA42790@cskk.homeip.net> Message-ID: nzbz xx wrote: > The original txt file is written in this format: > > Plant 1 > date & time > description > description > description > (Blank line) > Plant 2 > ... > .... > ... > > I have converted this file into dict = {'Plant 1': > ['datetime','description','description','description'], 'Plant2' : > ['datetime',....]}. So how can i write this dict back to the txt file in > the same format? How about trying something yourself? Make an effort and write a few lines of code. Here's a sketch: Open a file for writing (use the with statement). Iterate over the dict items (key-value pairs). Inside the loop: Print the key. You may need to investigate how the print() function works with files. Iterate over the value list and print the items. Print a blank line. If your code doesn't work come back and post it here. From ddfw.dw at gmail.com Sun Aug 30 17:22:05 2020 From: ddfw.dw at gmail.com (Dianna Wotherspoon) Date: Sun, 30 Aug 2020 17:22:05 -0400 Subject: [Tutor] beginner question Message-ID: Is there someone that would help explain an edx tutorial? I am having trouble with the last part of the self guided certificate course. thanks From ddfw.dw at gmail.com Sun Aug 30 17:26:47 2020 From: ddfw.dw at gmail.com (Dianna Wotherspoon) Date: Sun, 30 Aug 2020 17:26:47 -0400 Subject: [Tutor] problem Message-ID: can you help me with this problem please? Write a program that repeatedly prompts a user for integer numbers until the user enters done. Once Donna entered print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try accept and put out an appropriate message and ignore the number. Enter 7, too, Bob, 10, and 4 and match the output below. Thanks From robertvstepp at gmail.com Sun Aug 30 18:55:49 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 30 Aug 2020 17:55:49 -0500 Subject: [Tutor] problem In-Reply-To: References: Message-ID: <20200830225549.GA122810@Dream-Machine1> On Sun, Aug 30, 2020 at 05:26:47PM -0400, Dianna Wotherspoon wrote: >can you help me with this problem please? Hello! What is the problem with your problem? What have you tried? We will help you figure this out, but we won't do it for you. Can you break up your problem below into conceptual steps (or pseudocode)? >Write a program that repeatedly prompts a user for integer numbers until >the user enters done. "repeatedly" suggest the use of a loop. Perhaps a "while True:"? "the user enters done" suggests using a conditional statement to check for whatever you have the user to enter to indicate done, perhaps a "q" for quit. So perhaps something like "if user_input == 'q':" then "break" out of your loop? What Python statement can you use to collect "input" from the user? What will be the data type of the user input? Will you need to convert it? What Python statements will do the conversion? > ...Once Donna entered print out the largest and smallest >of the numbers. If the user enters anything other than a valid number catch >it with a try accept and put out an appropriate message and ignore the >number. Enter 7, too, Bob, 10, and 4 and match the output below. How will you determine if the number is valid? Hints: Try in the interpreter "int('a')". What happens? Do you get an exception? If yes, how can you use that in a try/except structure? What data structure will you store all of the correctly entered numbers into? Does that data structure have a convenient method for determining the minimum/maximum values contained in that structure? Hopefully there are enough hints to get you to the point of writing some code. Suggestion: Write out the steps the program must perform in the correct order in natural language and see if you can translate that process of ordered steps into Python. Good luck! If you run into problems copy-and-paste your code into a plain text email along with the copy-and-paste of any tracebacks and someone will try to help you out. -- Wishing you only the best, boB Stepp From alan.gauld at yahoo.co.uk Sun Aug 30 19:06:32 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 31 Aug 2020 00:06:32 +0100 Subject: [Tutor] beginner question In-Reply-To: References: Message-ID: On 30/08/2020 22:22, Dianna Wotherspoon wrote: > Is there someone that would help explain an edx tutorial? > I am having trouble with the last part of the self guided certificate > course. It might help if you were more specific. Which edx course? - there are at least 18 courses listed as being Python based. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From robertvstepp at gmail.com Sun Aug 30 21:06:14 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 30 Aug 2020 20:06:14 -0500 Subject: [Tutor] Interesting article: "Never Run 'python' In Your Downloads Folder" Message-ID: <20200831010614.GH122810@Dream-Machine1> This article -- "Never Run 'python' In Your Downloads Folder" -- brought up quite a few things that I had not actively considered that are potential security risks. I thought it might be of interest and perhaps might help someone not make a bad error in judgement. https://glyph.twistedmatrix.com/2020/08/never-run-python-in-your-downloads-folder.html Perhaps it might generate some fruitful discussion! -- Wishing you only the best, boB Stepp From john at johnweller.co.uk Mon Aug 31 11:39:35 2020 From: john at johnweller.co.uk (John Weller) Date: Mon, 31 Aug 2020 16:39:35 +0100 Subject: [Tutor] Datetime object as a class property Message-ID: <00e301d67fac$ef18f120$cd4ad360$@johnweller.co.uk> I have an instance of a class called, say, data. I know I can create a property, name, in the class as a string with self.name = '' which I can then populate in an instance of my class with data.name = 'John'. How do I create datetime object, eg sunrise, so that in the code I can put data.sunrise = datetime.strptime("05:45:00", "%H:%M:%S"). Self.sunrise = ? Thanks John John Weller 01380 723235 07976 393631 From david at graniteweb.com Mon Aug 31 13:42:50 2020 From: david at graniteweb.com (David Rock) Date: Mon, 31 Aug 2020 12:42:50 -0500 Subject: [Tutor] Datetime object as a class property In-Reply-To: <00e301d67fac$ef18f120$cd4ad360$@johnweller.co.uk> References: <00e301d67fac$ef18f120$cd4ad360$@johnweller.co.uk> Message-ID: > On Aug 31, 2020, at 10:39, John Weller wrote: > > I have an instance of a class called, say, data. I know I can create a > property, name, in the class as a string with self.name = '' which I can > then populate in an instance of my class with data.name = 'John'. How do I > create datetime object, eg sunrise, so that in the code I can put > data.sunrise = datetime.strptime("05:45:00", "%H:%M:%S"). Self.sunrise = ? If I understand correctly, you want data.sunrise to contain a datetime object. There is no need to specify a specific data type in the class; python variable names just point to whatever data type is associated to them. If you assign a datetime object to data.sunrise, it will be a datetime object. The simplest way to have a ?placeholder? would be to assign None to self.sunrise: self.sunrise = None then once you create the data instance, data.sunrise can be associated to datetime.strptime("05:45:00", "%H:%M:%S?) ? David Rock david at graniteweb.com From marc.tompkins at gmail.com Mon Aug 31 13:54:33 2020 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 31 Aug 2020 10:54:33 -0700 Subject: [Tutor] Datetime object as a class property In-Reply-To: <00e301d67fac$ef18f120$cd4ad360$@johnweller.co.uk> References: <00e301d67fac$ef18f120$cd4ad360$@johnweller.co.uk> Message-ID: On Mon, Aug 31, 2020 at 10:32 AM John Weller wrote: > I have an instance of a class called, say, data. I know I can create a > property, name, in the class as a string with self.name = '' which I can > then populate in an instance of my class with data.name = 'John'. How do > I > create datetime object, eg sunrise, so that in the code I can put > data.sunrise = datetime.strptime("05:45:00", "%H:%M:%S"). Self.sunrise = ? > Here's an example with default values for name and sunrise: from datetime import datetime class Data(object): def __init__(self, name="Nemo", sunrise="06:00:00"): self.name = name self.sunrise = datetime.strptime(sunrise, "%H:%M:%S") data = Data() print(data.name) print(data.sunrise) data = Data("John", "05:45:00") print(data.name) print(data.sunrise) From stephen.m.smith at comcast.net Mon Aug 31 14:08:17 2020 From: stephen.m.smith at comcast.net (Stephen M Smith) Date: Mon, 31 Aug 2020 14:08:17 -0400 Subject: [Tutor] Webbrowser's capabilities to do more than just open up a webpage Message-ID: <030101d67fc1$c4273d90$4c75b8b0$@comcast.net> I am having trouble with various websites detecting the usage of python, selenium and chrome and rejecting my request to make reservations automatically. I am not scraping or in any way violating information that anyone could or would consider private or proprietary. I have read through all of the questions i can find ( How to make Selenium script undetectable using GeckoDriver and Firefox through Python? - to cite one) and have tried most if not all of the recommendations. I continue to experiment with combinations of what is suggested, but have not found the answer yet. However, it occurs to me that using the python webbrowser module directly would allow me to eliminate the middleman (selenium) and keep my usage clean. (Using wireshark i can see that the header sent with webbrowser appears to be exactly the same as the header sent when i invoke chrome manually, with selenium it is different.) However, webbrowser does not seem to have the ability to fill in forms, 'press' buttons and locate and interact with various elements. In other words, I need to be able to manually create the click, switch_to_frame, xpath_search, find_element_by_class_name, etc. functions provided by selenium. I first hoped that these capabilities would be available in webbrowser, but that seems to be wrong. Then i thought that perhaps i could look through the selenium code and learn how those capabilities were provided and borrow/copy, but that has proven to be difficult. Finally i thought perhaps i could use webbrowser to get started, and then introduce selenium to query the site opened natively (with webbrowser), but i can't figure out if that is possible and am not sure that will work. I am hoping someone out there more knowledgeable than me can point me in the right direction. I know i may be biting off a lot, but i am basically a python hobbyist and am enjoying the learning process. Thanks as always for any and all help provided. From jf_byrnes at comcast.net Mon Aug 31 16:11:28 2020 From: jf_byrnes at comcast.net (Jim) Date: Mon, 31 Aug 2020 15:11:28 -0500 Subject: [Tutor] Webbrowser's capabilities to do more than just open up a webpage In-Reply-To: <030101d67fc1$c4273d90$4c75b8b0$@comcast.net> References: <030101d67fc1$c4273d90$4c75b8b0$@comcast.net> Message-ID: On 8/31/20 1:08 PM, Stephen M Smith wrote: > I am having trouble with various websites detecting the usage of python, > selenium and chrome and rejecting my request to make reservations > automatically. I am not scraping or in any way violating information that > anyone could or would consider private or proprietary. I have read through > all of the questions i can find ( > detectable-using-geckodriver-and-firefox-through-p> How to make Selenium > script undetectable using GeckoDriver and Firefox through Python? - to cite > one) and have tried most if not all of the recommendations. I continue to > experiment with combinations of what is suggested, but have not found the > answer yet. > > However, it occurs to me that using the python webbrowser module directly > would allow me to eliminate the middleman (selenium) and keep my usage > clean. (Using wireshark i can see that the header sent with webbrowser > appears to be exactly the same as the header sent when i invoke chrome > manually, with selenium it is different.) However, webbrowser does not seem > to have the ability to fill in forms, 'press' buttons and locate and > interact with various elements. In other words, I need to be able to > manually create the click, switch_to_frame, xpath_search, > find_element_by_class_name, etc. functions provided by selenium. I first > hoped that these capabilities would be available in webbrowser, but that > seems to be wrong. Then i thought that perhaps i could look through the > selenium code and learn how those capabilities were provided and > borrow/copy, but that has proven to be difficult. Finally i thought perhaps > i could use webbrowser to get started, and then introduce selenium to query > the site opened natively (with webbrowser), but i can't figure out if that > is possible and am not sure that will work. > > I am hoping someone out there more knowledgeable than me can point me in the > right direction. I know i may be biting off a lot, but i am basically a > python hobbyist and am enjoying the learning process. > > Thanks as always for any and all help provided. > > > You might want to look at pyppeteer - https://pypi.org/project/pyppeteer/. I have never needed to use it, but if I had problems with selenium I would give it a try. pyautogui may be an option. You can give it screen coordinates and it will click buttons and type in text. This is a little fragile if the elements on the screen don't always appear where you think they will Sometimes you can move around a web page using the keyboard. pyautogui can issue keyboard commands like etc. Regards, Jim From alan.gauld at yahoo.co.uk Mon Aug 31 19:57:42 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 1 Sep 2020 00:57:42 +0100 Subject: [Tutor] Webbrowser's capabilities to do more than just open up a webpage In-Reply-To: <030101d67fc1$c4273d90$4c75b8b0$@comcast.net> References: <030101d67fc1$c4273d90$4c75b8b0$@comcast.net> Message-ID: On 31/08/2020 19:08, Stephen M Smith wrote: > I am having trouble with various websites detecting the usage of python, > selenium and chrome and rejecting my request to make reservations > automatically. I am not scraping or in any way violating information that > anyone could or would consider private or proprietary. It sounds as if you are scraping. That means any kind of robotic activity where you extract data by examining user interface details rather than through a published API. > experiment with combinations of what is suggested, but have not found the > answer yet. That's because it is deliberately made as difficult as possible to dissuade programmers from automating access. Its a bit like hacking, you try to bypass the security arrangements of a server or in your case bypass the security arrangements of a web site designer. So yes, it will be difficult. > I am hoping someone out there more knowledgeable than me can point me in the > right direction. I know i may be biting off a lot, but i am basically a > python hobbyist and am enjoying the learning process. The right direction is to find a published API and use that. If there isn't one it means the web site designer doesn't want you accessing it programmatically - perhaps because their web infrastructure is not capable of processing high transaction rates or because it is funded by advertising which you don't see if using an automated access. If you aren't seeing the adverts the advertisers stop placing the ads and the site loses revenue. So, are you sure that the web site owner is happy for you to access the site programatically? If so, contact them and they may assist you find a way in. If not, desist or persist in the sure knowledge that you are doing battle with the content provider, who will doubtless be monitoring for attempted access and adding new security features if/when they detect such access.. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From john at johnweller.co.uk Mon Aug 31 13:50:34 2020 From: john at johnweller.co.uk (John Weller) Date: Mon, 31 Aug 2020 18:50:34 +0100 Subject: [Tutor] Datetime object as a class property In-Reply-To: References: <00e301d67fac$ef18f120$cd4ad360$@johnweller.co.uk> Message-ID: <012201d67fbf$3d5b8f20$b812ad60$@johnweller.co.uk> Excellent!! Many thanks. John John Weller 01380 723235 07976 393631 > -----Original Message----- > From: Tutor On Behalf Of > David Rock > Sent: 31 August 2020 18:43 > To: tutor > Subject: Re: [Tutor] Datetime object as a class property > > > > On Aug 31, 2020, at 10:39, John Weller wrote: > > > > I have an instance of a class called, say, data. I know I can create > > a property, name, in the class as a string with self.name = '' which I > > can then populate in an instance of my class with data.name = 'John'. > > How do I create datetime object, eg sunrise, so that in the code I can > > put data.sunrise = datetime.strptime("05:45:00", "%H:%M:%S"). Self.sunrise = > ? > > If I understand correctly, you want data.sunrise to contain a datetime object. There > is no need to specify a specific data type in the class; python variable names just > point to whatever data type is associated to them. If you assign a datetime object > to data.sunrise, it will be a datetime object. The simplest way to have a > ?placeholder? would be to assign None to self.sunrise: > > self.sunrise = None > > then once you create the data instance, data.sunrise can be associated to > datetime.strptime("05:45:00", "%H:%M:%S?) > > > ? > David Rock > david at graniteweb.com > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From john at johnweller.co.uk Mon Aug 31 14:01:52 2020 From: john at johnweller.co.uk (John Weller) Date: Mon, 31 Aug 2020 19:01:52 +0100 Subject: [Tutor] Datetime object as a class property In-Reply-To: References: <00e301d67fac$ef18f120$cd4ad360$@johnweller.co.uk> Message-ID: <013501d67fc0$cf8fbb40$6eaf31c0$@johnweller.co.uk> Many thanks. John John Weller 01380 723235 07976 393631 From: Marc Tompkins Sent: 31 August 2020 18:55 To: john at johnweller.co.uk Cc: tutor at python.org Subject: Re: [Tutor] Datetime object as a class property On Mon, Aug 31, 2020 at 10:32 AM John Weller > wrote: I have an instance of a class called, say, data. I know I can create a property, name, in the class as a string with self.name = '' which I can then populate in an instance of my class with data.name = 'John'. How do I create datetime object, eg sunrise, so that in the code I can put data.sunrise = datetime.strptime("05:45:00", "%H:%M:%S"). Self.sunrise = ? Here's an example with default values for name and sunrise: from datetime import datetime class Data(object): def __init__(self, name="Nemo", sunrise="06:00:00"): self.name = name self.sunrise = datetime.strptime(sunrise, "%H:%M:%S") data = Data() print(data.name ) print(data.sunrise) data = Data("John", "05:45:00") print(data.name ) print(data.sunrise)