[Tutor] How to make object disappear?
Dear Tutor, My students and I are creating a maze game in tkinter. We are trying to make the ball disappear when it hits the wall (black lines). We are not having much luck. The following code has run the best, but still, the ball does not disappear. Any advice would be appreciated! from tkinter import * import random import time tk = Tk() tk.title("Game") tk.resizable(0, 0) tk.wm_attributes("-topmost", 1) canvas = Canvas(tk, width=1400, height=835, bd=0, highlightthickness=0) canvas.pack() tk.update() class dot: def __init__(self, canvas, color): self.canvas = canvas self.id = canvas.create_oval(15, 15, 30, 30, fill='Blue', tags='dot1') this = dot(canvas, 'blue') def ball(n, x, y): canvas.move(n, x, y) def mt(event): if event.keysym == 'Left': ball(1, -30, 0) restart() elif event.keysym == 'Up': ball(1, 0, -30) restart() elif event.keysym == 'Down': ball(1, 0, 30) restart() elif event.keysym == 'Right': ball(1, 30, 0) restart() else: ball(1, 30, 0) restart() canvas.bind_all('', mt) canvas.bind_all('', mt) canvas.bind_all('', mt) canvas.bind_all('', mt) dot_bbox = canvas.coords('dot1') x = dot_bbox[0] y = dot_bbox[1] x2 = dot_bbox[2] y2 = dot_bbox[3] canvas.create_line(0, 0, 0, 300, width=20) canvas.create_line(0, 300, 300, 300, width=10) canvas.create_line(80, 240, 80, 0, width=10) canvas.create_line(160, 300, 160, 60, width=10) canvas.create_line(240, 240, 240, 0, width=10) canvas.create_line(300, 300, 300, 150, width=10) canvas.create_line(300, 150, 600, 150, width=10) canvas.create_line(80, 0, 2000, 0, width=30) canvas.create_line(300, 75, 600, 75, width=10) canvas.create_line(760, 0, 760, 300, width=10) canvas.create_line(600, 75, 680, 75, width=10) def restart(): if (canvas.find_overlapping(x, y, x2, y2) == (1, 2)) or (canvas.find_overlapping(x, y, x2, y2) == (1, 3)) or (canvas.find_overlapping(x, y, x2, y2) == (1, 4)) or (canvas.find_overlapping(x, y, x2, y2) == (1, 5)) or (canvas.find_overlapping(x, y, x2, y2) == (1, 6)) == True: canvas.delete('dot1') Shell: Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "copyright", "credits" or "license()" for more information. >>> WARNING: The version of Tcl/Tk (8.5.9) in use may be unstable. Visit http://www.python.org/download/mac/tcltk/ for current information. >>> RESTART: /Users/BScherer/Desktop/MazeTest.py >>> === RESTART: Shell === >>> RESTART: /Users/BScherer/Desktop/MazeTest.py >>> === RESTART: Shell === >>> from tkinter import * >>> import random >>> import time >>> tk = Tk() >>> >>> tk.title("Game") '' >>> tk.resizable(0, 0) '' >>> tk.wm_attributes("-topmost", 1) '' >>> canvas = Canvas(tk, width=1400, height=835, bd=0, highlightthickness=0) >>> canvas.pack() >>> tk.update() >>> class dot: def __init__(self, canvas, color): self.canvas = canvas self.id = canvas.create_oval(10, 10, 25, 25, fill='Blue', tags='dot1') >>> this = dot(canvas, 'blue') >>> def ball(n, x, y): canvas.move(n, x, y) >>> def mt(event): if event.keysym == 'Left': ball(1, -30, 0) restart() elif event.keysym == 'Up': ball(1, 0, -30) restart() elif event.keysym == 'Down': ball(1, 0, 30) restart() elif event.keysym == 'Right': ball(1, 30, 0) restart() else: ball(1, 30, 0) restart() >>> canvas.bind_all('', mt) '4300440008mt' >>> canvas.bind_all('', mt) '4329736584mt' >>> canvas.bind_all('', mt) '4380738824mt' >>> canvas.bind_all('', mt) '4383283336mt' >>> dot_bbox = canvas.coords('dot1') >>> x = dot_bbox[0] >>> y = dot_bbox[1] >>> x2 = dot_bbox[2] >>> y2 = dot_bbox[3] >>> print(canvas.find_overlapping(x, y, x2, y2)) (1,) >>> print(canvas.find_overlapping(x, y, x2, y2)) (1,) >>> canvas.create_line(0, 0, 0, 300, width=20) 2 >>> print(canvas.find_overlapping(x, y, x2, y2)) (1, 2) >>> canvas.create_line(600, 75, 680, 75, width=10) 3 >>> print(canvas.find_overlapping(x, y, x2, y2)) (1, 2) >>> RESTART: /Users/BScherer/Desktop/MazeTest.py >>> === RESTART: Shell === >>> RESTART: /Users/BScherer/Desktop/MazeTest.py >>> === RESTART: Shell === >>> RESTART: /Users/BScherer/Desktop/MazeTest.py >>> ===
Re: [Tutor] How to make object disappear?
On May 9, 2016 8:01 AM, "Lisa Hasler Waters" wrote: > > Dear Tutor, > > My students and I are creating a maze game in tkinter. We are trying to > make the ball disappear when it hits the wall (black lines). We are not > having much luck. The following code has run the best, but still, the ball > does not disappear. Any advice would be appreciated! > > from tkinter import * > import random > import time > > > tk = Tk() > tk.title("Game") > tk.resizable(0, 0) > tk.wm_attributes("-topmost", 1) > canvas = Canvas(tk, width=1400, height=835, bd=0, highlightthickness=0) > canvas.pack() > tk.update() > > > class dot: It is a Python convention to capitalize class names. In the future write class Dot. > def __init__(self, canvas, color): > self.canvas = canvas > self.id = canvas.create_oval(15, 15, 30, 30, fill='Blue', > tags='dot1') > > this = dot(canvas, 'blue') > > def ball(n, x, y): > canvas.move(n, x, y) > > def mt(event): > if event.keysym == 'Left': > ball(1, -30, 0) > restart() > elif event.keysym == 'Up': > ball(1, 0, -30) > restart() > elif event.keysym == 'Down': > ball(1, 0, 30) > restart() > elif event.keysym == 'Right': > ball(1, 30, 0) > restart() > else: > ball(1, 30, 0) > restart() This is my own opinion. It is important to separate data from logic. In this case you are trying to map a key symbol to some numeric values: key_to_val = {'Left' : (0, 30, 0), 'Right' etc} (I realize you are probably introducing students to programming. So you might first show the then else logic, then introduce the dictionary alternative.) val = key_to_val.get(event.keysym, (30, 0)) ball(val) restart() 15 lines of code replaced by 4. Easier to write, easier to understand, easier to maintain. Worth learning about dictionaries. > > canvas.bind_all('', mt) > canvas.bind_all('', mt) > canvas.bind_all('', mt) > canvas.bind_all('', mt) > > dot_bbox = canvas.coords('dot1') > > > > > x = dot_bbox[0] > y = dot_bbox[1] > x2 = dot_bbox[2] > y2 = dot_bbox[3] > > canvas.create_line(0, 0, 0, 300, width=20) > canvas.create_line(0, 300, 300, 300, width=10) > canvas.create_line(80, 240, 80, 0, width=10) > canvas.create_line(160, 300, 160, 60, width=10) > canvas.create_line(240, 240, 240, 0, width=10) > canvas.create_line(300, 300, 300, 150, width=10) > canvas.create_line(300, 150, 600, 150, width=10) > canvas.create_line(80, 0, 2000, 0, width=30) > canvas.create_line(300, 75, 600, 75, width=10) > canvas.create_line(760, 0, 760, 300, width=10) > canvas.create_line(600, 75, 680, 75, width=10) > > def restart(): > if (canvas.find_overlapping(x, y, x2, y2) == (1, 2)) or > (canvas.find_overlapping(x, y, x2, y2) == (1, 3)) or > (canvas.find_overlapping(x, y, x2, y2) == (1, 4)) or > (canvas.find_overlapping(x, y, x2, y2) == (1, 5)) or > (canvas.find_overlapping(x, y, x2, y2) == (1, 6)) == True: > canvas.delete('dot1') I got a syntax error from that if statement. It seems to me (obviously?) that canvas.delete is never called. This is a great opportunity for reaching debugging. I'd add a print function call to show the value of the canvas.find_overlapping call. Also a good opportunity to read the manual. canvas.find_overlapping returns a tuple of all matching items. It would make code reading and maintenance easier if you assign canvas.find_overlapping(x, y, x2, y2) to a name, then refer to that name in the logic. Revisiting the separation of data from logic: if canvas.find_overlapping(x, y, x2, y2) in ((1,1),(1,2) etc.) Also avoid things like if x ==True: It is sufficient to write if x: In English we say "if it is raining..." rather than " if it is raining is True ". Take what you want -l eave the rest. > > > > > > > Shell: > > Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44) > [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin > Type "copyright", "credits" or "license()" for more information. > >>> WARNING: The version of Tcl/Tk (8.5.9) in use may be unstable. > Visit http://www.python.org/download/mac/tcltk/ for current information. > > >>> > RESTART: /Users/BScherer/Desktop/MazeTest.py > > >>> > === RESTART: Shell > === > >>> > RESTART: /Users/BScherer/Desktop/MazeTest.py > > >>> > === RESTART: Shell > === > >>> from tkinter import * > >>> import random > >>> import time > >>> tk = Tk() > >>> > >>> tk.title("Game") > '' > >>> tk.resizable(0, 0) > '' > >>> tk.wm_attributes("-topmost", 1) > '' > >>> canvas = Canvas(tk, width=1400, height=835, bd=0, highlightthickness=0) > >>> canvas.pack() > >>> tk.update() > >>> class dot: > def __init__(self, canvas, color): > self.canvas = c
Re: [Tutor] How to make object disappear?
Hello! I am not one of the experts; instead, I am one of the learners. But if you are seeking assistance on Tutor, it is necessary to post the actual code that you successfully or unsuccessfully ran. If you were unsuccessful, you need to copy and paste the full text of the error messages you received. On Mon, May 9, 2016 at 6:59 AM, Lisa Hasler Waters wrote: The code you give below does not run when I copy and paste it into my environment. The indentation (Which is CRITICAL in Python.) is inconsistent and in places wrong. It is typical to use 4 spaces for each level of indentation. If your email client is mangling your indentations, then you need to determine how to correct this prior to posting! To see what your code looks like from my perspective, go to https://mail.python.org/pipermail/tutor/2016-May/108832.html > from tkinter import * > import random > import time > > > tk = Tk() > tk.title("Game") > tk.resizable(0, 0) > tk.wm_attributes("-topmost", 1) > canvas = Canvas(tk, width=1400, height=835, bd=0, highlightthickness=0) > canvas.pack() > tk.update() > > > class dot: > def __init__(self, canvas, color): > self.canvas = canvas > self.id = canvas.create_oval(15, 15, 30, 30, fill='Blue', > tags='dot1') > > this = dot(canvas, 'blue') > > def ball(n, x, y): > canvas.move(n, x, y) > > def mt(event): > if event.keysym == 'Left': > ball(1, -30, 0) > restart() > elif event.keysym == 'Up': > ball(1, 0, -30) > restart() > elif event.keysym == 'Down': > ball(1, 0, 30) > restart() > elif event.keysym == 'Right': > ball(1, 30, 0) > restart() > else: > ball(1, 30, 0) > restart() > > canvas.bind_all('', mt) > canvas.bind_all('', mt) > canvas.bind_all('', mt) > canvas.bind_all('', mt) > > dot_bbox = canvas.coords('dot1') > > x = dot_bbox[0] > y = dot_bbox[1] > x2 = dot_bbox[2] > y2 = dot_bbox[3] > > canvas.create_line(0, 0, 0, 300, width=20) > canvas.create_line(0, 300, 300, 300, width=10) > canvas.create_line(80, 240, 80, 0, width=10) > canvas.create_line(160, 300, 160, 60, width=10) > canvas.create_line(240, 240, 240, 0, width=10) > canvas.create_line(300, 300, 300, 150, width=10) > canvas.create_line(300, 150, 600, 150, width=10) > canvas.create_line(80, 0, 2000, 0, width=30) > canvas.create_line(300, 75, 600, 75, width=10) > canvas.create_line(760, 0, 760, 300, width=10) > canvas.create_line(600, 75, 680, 75, width=10) > > def restart(): > if (canvas.find_overlapping(x, y, x2, y2) == (1, 2)) or > (canvas.find_overlapping(x, y, x2, y2) == (1, 3)) or > (canvas.find_overlapping(x, y, x2, y2) == (1, 4)) or > (canvas.find_overlapping(x, y, x2, y2) == (1, 5)) or > (canvas.find_overlapping(x, y, x2, y2) == (1, 6)) == True: > canvas.delete('dot1') After I corrected the indentation errors, the above code still did not run as you omitted the statement to get everything going, that is: tk.mainloop() Now I can see your maze game! It looks potentially very fun and cool. As to your actual problem, I have not gone through your "if" conditions, but obviously you need to accurately detect when the "edge" of the ball collides with the nearest side of one of the walls. If such an event happens the canvas would have to be redrawn with the walls in place, but without the ball. If the ball is not disappearing, then my initial thoughts would be: 1) Your if/elif statements are not correctly detecting the collisions. 2) You are not actually "capturing" the collision event as the ball moves; that is, you may not be successfully detecting the ball's *current* coordinates. 3) You are not correctly redrawing the window at the point where the ball must "disappear". There are various stylistic issues. You and your students might want to glance through the portions of PEP 8 similar to the Python that you are currently coding: https://www.python.org/dev/peps/pep-0008/ PEP 8 is the Python style-guide, which many if not most Python coders strive to emulate. Good luck! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] is there a better way to do this?
Hi Python 3.4 Linux (ubuntu) This code does what I want. curs is the result of a mysql query data = [[" " for x in range(9)] for y in range(count)] for (ddate, mood, walk, lag, sleep) in curs: data[row][0]=ddate data[row][1]=mood data[row][2]=walk data[row][3]=lag data[row][4]=sleep row +=1 While I don't know a better way to do this, it seems a bit awkward, is there a better way? Thank you Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to make object disappear?
Lisa Hasler Waters wrote: > My students and I are creating a maze game in tkinter. We are trying to > make the ball disappear when it hits the wall (black lines). We are not > having much luck. The following code has run the best, but still, the ball > does not disappear. Any advice would be appreciated! You need to consider not just the ball, but the whole trajectory. When you can only move up/down/left/right that is roughly the rectangle spread by the starting and the end position of the ball. I calculate that rectangle as (x0,y0)-(x1,y1) in the checked_move() method below. I recommend that you use pen and paper, draw two rectangular "balls" on a horizontal or vertical line and the rectangle between them to try it yourself before you take a look. I then use that rectangle to find overlapping canvas items. Of course the ball will always overlap with itself, so I have to make sure to rule that out. While dabbling with the code I have also cleaned it up a bit -- but you should still recognize it ;) from tkinter import * import random import time class Ball: def __init__(self, canvas, color): self.canvas = canvas self.id = canvas.create_oval( 15, 15, 30, 30, fill='Blue') def checked_move(self, dx, dy): """Move unless we would hit a wall""" x0, y0, x1, y1 = self.canvas.coords(self.id) if dx > 0: x1 += dx else: x0 += dx if dy > 0: y1 += dy else: y0 += dy for id in self.canvas.find_overlapping(x0, y0, x1, y1): if id != self.id: # we will hit something other than ourselves # jump back to the start instead of # deleting ourselves self.canvas.coords(self.id, 15, 15, 30, 30) # uncomment line below if you insist on deletion # self.canvas.delete(self.id) return self.canvas.move(self.id, dx, dy) def mt(event): STEP = 15 if event.keysym == 'Left': ball.checked_move(-STEP, 0) elif event.keysym == 'Up': ball.checked_move(0, -STEP) elif event.keysym == 'Down': ball.checked_move(0, STEP) elif event.keysym == 'Right': ball.checked_move(STEP, 0) WALLS = [ (0, 0, 0, 300, 20), (0, 300, 300, 300, 10), (80, 240, 80, 0, 10), (160, 300, 160, 60, 10), (240, 240, 240, 0, 10), (300, 300, 300, 150, 10), (300, 150, 600, 150, 10), (80, 0, 2000, 0, 30), (300, 75, 600, 75, 10), (760, 0, 760, 300, 10), (600, 75, 680, 75, 10), ] def main(): global ball # needed for mt() tk = Tk() tk.title("Game") tk.resizable(0, 0) tk.wm_attributes("-topmost", 1) canvas = Canvas(tk, width=1400, height=835, bd=0, highlightthickness=0) canvas.pack() ball = Ball(canvas, 'blue') canvas.bind_all('', mt) canvas.bind_all('', mt) canvas.bind_all('', mt) canvas.bind_all('', mt) for wall in WALLS: coords = wall[:4] width = wall[4] canvas.create_line(*coords, width=width, tags="wall") tk.mainloop() if __name__ == "__main__": main() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to make object disappear?
On 09/05/16 16:55, boB Stepp wrote: >> class dot: >> def __init__(self, canvas, color): >> self.canvas = canvas >> self.id = canvas.create_oval(15, 15, 30, 30, fill='Blue', >> tags='dot1') >> >> this = dot(canvas, 'blue') You create an instance of your class called this. But you never refer to it again. >> def ball(n, x, y): >> canvas.move(n, x, y) >> >> def restart(): >> if (canvas.find_overlapping(x, y, x2, y2) == (1, 2)) or >>(canvas.find_overlapping(x, y, x2, y2) == (1, 3)) or >>(canvas.find_overlapping(x, y, x2, y2) == (1, 4)) or >>(canvas.find_overlapping(x, y, x2, y2) == (1, 5)) or >>(canvas.find_overlapping(x, y, x2, y2) == (1, 6)) == True: >> canvas.delete('dot1') Here you delete the shape that your object, this, drew on the canvas but you do not delete the object. 'this' is still there. The normal way to do this kind of thing in a GUI program is to have the class have a paint/draw method that makes it visible and a hide/erase method that makes it invisible (by drawing itself with the background colour). You probably need a move() method too. You can then manipulate the "dot" (although Ball is probably a more suitable name?) by calling move() draw() and erase() on the object itself. You might want an isOverlapping() method too, that simply returns a boolean. That will hide all that horrible if/else nastiness (or even the dictionary lookup if you adopt Bob's (excellent) option. You then wind up with something like ball.move(x,y) if ball.isOverlapping(X,Y,X1,Y1): ball.erase() else: ball.draw() Which is a lot more readable IMHO. A more indirect solution to your problem would be to use pyGame to build the game where sprites etc come as standard. But pyGame itself does not of course come as standard... :-( -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] is there a better way to do this?
On Mon, May 9, 2016 at 4:13 AM, Chris Roy-Smith wrote: > Hi > Python 3.4 Linux (ubuntu) > > This code does what I want. > curs is the result of a mysql query > > does this work (untested)? data = [] for stuff in curs: data.append(stuff) > > While I don't know a better way to do this, it seems a bit awkward, is there > a better way? > > > Thank you > Chris Roy-Smith > ___ > Tutor maillist - Tutor@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 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] is there a better way to do this?
Chris Roy-Smith wrote: > Hi > Python 3.4 Linux (ubuntu) > > This code does what I want. > curs is the result of a mysql query > > > data = [[" " for x in range(9)] for y in range(count)] > for (ddate, mood, walk, lag, sleep) in curs: > data[row][0]=ddate > data[row][1]=mood > data[row][2]=walk > data[row][3]=lag > data[row][4]=sleep > row +=1 > > > While I don't know a better way to do this, it seems a bit awkward, is > there a better way? Does `curs` give `count` records? If so: data = [ list(row) + [" "] * 4 for row in curs ] ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to make object disappear?
On Mon, May 9, 2016 at 11:34 AM, Alan Gauld via Tutor wrote: > On 09/05/16 16:55, boB Stepp wrote: Did not! Lisa Hasler Waters (and her students?) wrote the code!! [Snipped her code and Alan's comments.] boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to make object disappear?
Thank you all so much for your guidance! We will try these out during our next class and will hopefully find success. We can't thank you enough for your support! Best, Lisa and students On Mon, May 9, 2016 at 12:34 PM, Alan Gauld via Tutor wrote: > On 09/05/16 16:55, boB Stepp wrote: > > >> class dot: > >> def __init__(self, canvas, color): > >> self.canvas = canvas > >> self.id = canvas.create_oval(15, 15, 30, 30, fill='Blue', > >> tags='dot1') > >> > >> this = dot(canvas, 'blue') > > You create an instance of your class called this. > But you never refer to it again. > > >> def ball(n, x, y): > >> canvas.move(n, x, y) > >> > >> def restart(): > >> if (canvas.find_overlapping(x, y, x2, y2) == (1, 2)) or > >>(canvas.find_overlapping(x, y, x2, y2) == (1, 3)) or > >>(canvas.find_overlapping(x, y, x2, y2) == (1, 4)) or > >>(canvas.find_overlapping(x, y, x2, y2) == (1, 5)) or > >>(canvas.find_overlapping(x, y, x2, y2) == (1, 6)) == True: > >> canvas.delete('dot1') > > Here you delete the shape that your object, this, drew on > the canvas but you do not delete the object. 'this' is > still there. > > The normal way to do this kind of thing in a GUI program > is to have the class have a paint/draw method that makes > it visible and a hide/erase method that makes it invisible > (by drawing itself with the background colour). You probably > need a move() method too. You can then manipulate the "dot" > (although Ball is probably a more suitable name?) by > calling move() draw() and erase() on the object itself. > You might want an isOverlapping() method too, that simply > returns a boolean. That will hide all that horrible if/else > nastiness (or even the dictionary lookup if you adopt > Bob's (excellent) option. > > You then wind up with something like > > ball.move(x,y) > if ball.isOverlapping(X,Y,X1,Y1): > ball.erase() > else: > ball.draw() > > Which is a lot more readable IMHO. > > A more indirect solution to your problem would be to use > pyGame to build the game where sprites etc come as standard. > But pyGame itself does not of course come as standard... :-( > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Lisa Waters, PhD Technology Integration Flint Hill School ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] postgreSQL + psycopg2
Hi All, I am trying to pass a variable to the following statement : for line1 in smallLIST1: design1 = line1[3] print design1 nextRow=cursor1.execute("SELECT designation_name FROM designation WHERE designation_id = %s;", (design1)) print nextRow print "" for row in line1: print ""+str(row)+"" print "" 1st "print" shows values 1 , correctly. 2nd "print" shows "None". I am not able to pass this value, 1, as variable to the SELECT statement. the following is 'line1' (1, 'Vinayak', 'Salunke', '1', datetime.date(1982, 6, 6), 9871234567L, 'Tower-1,Millinium tower', 0, 1, datetime.date(2016, 5, 6), datetime.datetime(2016, 5, 6, 22, 55, 5, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=330, name=None))) On postgreSQL command this works SELECT designation_name FROM designation WHERE designation_id = 1; Python 2.7.6, Postgresql 9.3.7, psycopg2, apache & cgi. A little help. Thanks Nitin ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] is there a better way to do this?
Dne 9.5.2016 v 10:13 Chris Roy-Smith napsal(a): Hi Python 3.4 Linux (ubuntu) This code does what I want. curs is the result of a mysql query data = [[" " for x in range(9)] for y in range(count)] for (ddate, mood, walk, lag, sleep) in curs: data[row][0]=ddate data[row][1]=mood data[row][2]=walk data[row][3]=lag data[row][4]=sleep row +=1 if you want 'lists in list' (like your solution): data = [] for ddate, mood, walk, lag, sleep in curs: data += [ [ddate, mood, walk, lag, sleep] ] or 'tuples in list': data = [] for ddate, mood, walk, lag, sleep in curs: data += [ (ddate, mood, walk, lag, sleep) ] but for 'tuples in list'... simple: data = [] for record in curs: data += [record] -- S pozdravem -- -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Ondrej Rusek GYmnazium BOzeny Nemcove, Hradec Kralove, Czech ru...@gybon.cz, http://www.gybon.cz/~rusek ICQ: 150366991 =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -- Tato zprava byla prohledana na vyskyt viru a nebezpecneho obsahu antivirovym systemem MailScanner a zda se byt cista. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] postgreSQL + psycopg2
nitin chandra wrote: > Hi All, > > I am trying to pass a variable to the following statement : > > for line1 in smallLIST1: > design1 = line1[3] > print design1 > nextRow=cursor1.execute("SELECT designation_name FROM designation > WHERE designation_id = %s;", (design1)) Note that in the expression (design1) the parens have no effect: >>> design1 = 42 >>> (design1) 42 To get a 1-tuple add a comma: >>> (design1,) (42,) > print nextRow > print "" > for row in line1: > print ""+str(row)+"" > print "" > > 1st "print" shows values 1 , correctly. > 2nd "print" shows "None". > > I am not able to pass this value, 1, as variable to the SELECT statement. > > the following is 'line1' > > (1, 'Vinayak', 'Salunke', '1', datetime.date(1982, 6, 6), 9871234567L, > 'Tower-1,Millinium tower', 0, 1, datetime.date(2016, 5, 6), > datetime.datetime(2016, 5, 6, 22, 55, 5, > tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=330, name=None))) > > > On postgreSQL command this works > > SELECT designation_name FROM designation WHERE designation_id = 1; > > Python 2.7.6, Postgresql 9.3.7, psycopg2, apache & cgi. > > A little help. > > Thanks > > Nitin > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] is there a better way to do this?
On 09/05/16 22:03, Ondřej Rusek wrote: > but for 'tuples in list'... simple: > > data = [] > for record in curs: >data += [record] Couldn't that be abbreviated to: date = list(curs) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] is there a better way to do this?
On Mon, May 9, 2016 at 6:49 PM, Alan Gauld via Tutor wrote: > On 09/05/16 22:03, Ondřej Rusek wrote: > >> but for 'tuples in list'... simple: >> >> data = [] >> for record in curs: >>data += [record] > > Couldn't that be abbreviated to: > > date = list(curs) > I thought I nailed it earlier (and others) but this is great. An expressive language, python > ___ > Tutor maillist - Tutor@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 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] postgreSQL + psycopg2
On 09/05/16 22:14, nitin chandra wrote: > for line1 in smallLIST1: > design1 = line1[3] > print design1 > nextRow=cursor1.execute("SELECT designation_name FROM designation > WHERE designation_id = %s;", (design1)) > print nextRow > print "" > for row in line1: > print ""+str(row)+"" > print "" > > 1st "print" shows values 1 , correctly. I assume you mean design1? > 2nd "print" shows "None". I don't know postgres API so i'll assume the %s is the correct marker. In SQLite we'd use ?... Also to get the results row by row I'd expect to have to call fetchone() on the cursor: query = """ SELECT designation_name FROM designation WHERE designation_id = %s;""" nextrow = cursor1.execute(query, (design1,)).fetchone() But Postgres DBAPI may be different... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] is there a better way to do this?
On Mon, May 09, 2016 at 06:13:32PM +1000, Chris Roy-Smith wrote: > data = [[" " for x in range(9)] for y in range(count)] > for (ddate, mood, walk, lag, sleep) in curs: > data[row][0]=ddate > data[row][1]=mood > data[row][2]=walk > data[row][3]=lag > data[row][4]=sleep > row +=1 > > While I don't know a better way to do this, it seems a bit awkward, is > there a better way? Hmmm, it's hard to be sure because we don't really know what count is. Do you want a bunch of empty rows at the end? My guess is No. In your code above, you initialise each row with ten spaces, and only replace five of them. So assuming you need the extra five spaces: data = [record + [" "]*5 for record in curs] provided curs returns lists, rather than tuples. (If not, it's easy to just convert using `list(record)`. If you don't need the extra five columns, the code is even simpler: data = list(curs) What if you do want extra blank rows? Easiest to just add them at the end: # initialise data as above, then add blanks for i in range(how_many_extra_rows): data.append([" "]*10) which can be simplified to: data.extend([[" "]*10 for i in range(how_many_extra_rows)]) -- Steve ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] postgreSQL + psycopg2
Thanks Alan, Peter but didn't work nextrow=(cursor1.execute(query, (design1,))).fetchone() AttributeError: 'NoneType' object has no attribute 'fetchone' 1. Yes Alan, the variable 'design1' has a value '1'. This is how I tested it from python command : >>> import psycopg2 >>> import datetime >>> line = (1, 'Vinayak', 'Salunke', '1', datetime.date(1982, 6, 6), >>> 9871234567L, 'Tower-1,Millinium tower,Gurgaon,India', 0, 1, >>> datetime.date(2016, 5, 6), datetime.datetime(2016, 5, 6, 22, 55, 5, >>> tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=330, name=None))) >>> design1 = line[3] >>> print design1 1 >>> conn = psycopg2.connect(database="passtms", user="nitin", host="localhost", >>> password="") >>> cursor1 = conn.cursor() >>> query=("""SELECT designation_name FROM designation WHERE designation_id = >>> %s;""") >>> nextrow = (query, (design1)) >>> nextrow ('SELECT designation_name FROM designation WHERE designation_id = %s;', '1') >>> nextrow = cursor1.execute(query, (design1,)) >>> nextrow >>> When we run "cursor1.execute", that is when it gives us None. How strange !!?? On 10 May 2016 at 04:36, Alan Gauld via Tutor wrote: > On 09/05/16 22:14, nitin chandra wrote: > >> for line1 in smallLIST1: >> design1 = line1[3] >> print design1 >> nextRow=cursor1.execute("SELECT designation_name FROM designation >> WHERE designation_id = %s;", (design1)) >> print nextRow >> print "" >> for row in line1: >> print ""+str(row)+"" >> print "" >> >> 1st "print" shows values 1 , correctly. > > I assume you mean design1? > >> 2nd "print" shows "None". > > I don't know postgres API so i'll assume the %s is the correct > marker. In SQLite we'd use ?... > > Also to get the results row by row I'd expect to have > to call fetchone() on the cursor: > > query = """ > SELECT designation_name > FROM designation > WHERE designation_id = %s;""" > > nextrow = cursor1.execute(query, (design1,)).fetchone() > > But Postgres DBAPI may be different... > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor