•
•
•
•
What is DaniWeb IT Discussion Community?
You're currently browsing the Python section within the Software Development category of DaniWeb, a massive community of 426,812 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 1,937 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Python advertiser: Programming Forums
Views: 54862 | Replies: 150
![]() |
The module xlrd can read Excel spreadsheets without the use of COM:
python Syntax (Toggle Plain Text)
# module xlrd is used to extract data from Excel spreadsheets. # Handles older and newer formats. Can be used on any platform. # Has support for Excel dates and is unicode-aware. # download installer xlrd-0.6.1.win32.exe from: # http://pypi.python.org/pypi/xlrd # or: # http://www.lexicon.net/sjmachin/xlrd.htm import xlrd # pick an Excel file you have book = xlrd.open_workbook("myfile.xls") sheet = book.sheet_by_index(0) for row in range(sheet.nrows): print sheet.row(row)
Last edited by sneekula : Jul 16th, 2008 at 4:39 pm.
No one died when Clinton lied.
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,470
Reputation:
Rep Power: 10
Solved Threads: 176
Sorting lists in Python is simple, but when the list elements are numeric strings like they are in Tkinter or wxPython ListBoxes you need to sort them as floats not strings to make it work properly. Here is an example ...
python Syntax (Toggle Plain Text)
def cmp_float(s1, s2): """ s1 and s2 are numeric strings in a list compare to sort as floats low to high """ if float(s1) > float(s2): return 1 elif float(s2) > float(s1): return -1 else: return 0 q = ['4.5', '11.3', '1.6', '9.4', '10.2', '-7.3'] print q print sorted(q) # you need to supply a custom compare function print sorted(q, cmp=cmp_float) """ my output --> ['4.5', '11.3', '1.6', '9.4', '10.2', '-7.3'] <-- unsorted ['-7.3', '1.6', '10.2', '11.3', '4.5', '9.4'] <-- sorted as strings ['-7.3', '1.6', '4.5', '9.4', '10.2', '11.3'] <-- sorted as floats """
May 'the Google' be with you!
I was working with patient information and came up with this list of instances that made it relatively easy to find specific information:
python Syntax (Toggle Plain Text)
# creating and processing one list of class objects import operator class Patient(object): """__init__() functions as the class constructor""" def __init__(self, fname=None, sname=None, id=None): self.fname = fname self.sname = sname self.id = id def __repr__(self): """ if you print the instance of the class this format will display """ # use the class dictionary iterator class_dictiter = self.__dict__.iteritems() return " ".join(["%s: %s" % (k,v) for k,v in class_dictiter]) # make list of class Patient instances # instance --> surname, firstname, id patientList = [] patientList.append(Patient("Elmer", "Fudd", "1234")) patientList.append(Patient("Donald", "Duck", "1235")) patientList.append(Patient("Mighty", "Mouse", "1236")) patientList.append(Patient("Fargo", "Ferkel", "1237")) print "Show/test the whole patientList via __repr__ overload:" print patientList print '-'*60 print "Just one instance in the list via __repr__ overload:" print patientList[3] print '-'*60 print "Show one particular item:" print patientList[0].sname print '-'*60 print "Sort the patientList in place by sname ..." patientList.sort(key=operator.attrgetter('sname')) print "... then show all patients info in one nice table:" for patient in patientList: print "sname: %-20s fname= %-20s id=%s" % \ (patient.sname, patient.fname, patient.id) """ my output --> Show/test the whole patientList via __repr__ overload: [sname: Fudd id: 1234 fname: Elmer, sname: Duck id: 1235 fname: Donald, sname: Mouse id: 1236 fname: Mighty, sname: Ferkel id: 1237 fname: Fargo] ------------------------------------------------------------ Just one instance in the list via __repr__ overload: sname: Ferkel id: 1237 fname: Fargo ------------------------------------------------------------ Show one particular item: Fudd ------------------------------------------------------------ Sort the patientList in place by sname ... ... then show all patients info in one nice table: sname: Duck fname= Donald id=1235 sname: Ferkel fname= Fargo id=1237 sname: Fudd fname= Elmer id=1234 sname: Mouse fname= Mighty id=1236 """
Should you find Irony, you can keep her!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,470
Reputation:
Rep Power: 10
Solved Threads: 176
The module pygame makes it easy to load, display and move images around the screen ...
python Syntax (Toggle Plain Text)
# experiments with module pygame # free from: http://www.pygame.org/ # load, display and move an image import pygame as pg # initialize pygame pg.init() # pick an image you have (.bmp .jpg .png .gif) # if the image file is not in the working folder, # use the full pathname like "C:/Images/gifs/Pooh.gif" image_file = "Pooh.gif" # RGB color tuple used by pygame white = (255, 255, 255) # create a 300x300 white screen screen = pg.display.set_mode((300,300)) screen.fill(white) # load the image from a file # convert() unifies the pixel format for faster blit image = pg.image.load(image_file).convert() # draw image, position the image ulc at x=50, y=20 screen.blit(image, (50, 20)) # get the rectangle the image occupies # rec(x, y, w, h) start_rect = image.get_rect() # set up the timed event loop x = 0 y = 0 clock = pg.time.Clock() keepGoing = True while keepGoing: # set rate of move clock.tick(30) for event in pg.event.get(): # quit when user clicks on window x if event.type == pg.QUIT: keepGoing = False # move the image ... x += 1 y += 1 # stop when x exceeds limit if x > 270: keepGoing = False image_rect = start_rect.move(x, y) # this erases the old sreen with white screen.fill(white) # put the image on the screen at new location screen.blit(image, image_rect) # update screen pg.display.flip()
Last edited by vegaseat : 13 Days Ago at 2:23 pm. Reason: tags adjusted
May 'the Google' be with you!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,470
Reputation:
Rep Power: 10
Solved Threads: 176
You can use the module pygame to load, rotate and zoom an image ...
python Syntax (Toggle Plain Text)
# experiments with module pygame # free from: http://www.pygame.org/ # load, rotate, zoom and display an image import pygame as pg # initialize pygame pg.init() # pick an image you have (.bmp .jpg .png .gif) # if the image file is not in the working folder, # use the full pathname like "C:/Images/gifs/Froggy.jpg" image_file = "Froggy.jpg" # RGB color tuple used by pygame black = (0, 0, 0) white = (255, 255, 255) # create a 450x420 black screen screen = pg.display.set_mode((450,420)) screen.fill(black) # load the image from a file image = pg.image.load(image_file).convert() # this will rotate the image using angle and zoom using scale # pygame.transform.rotozoom(surface, angle, scale) angle = 45.5 scale = 1.5 image = pg.transform.rotozoom(image, angle, scale) # draw image, position the image ulc at x=15, y=5 screen.blit(image, (15, 5)) # nothing gets displayed until one updates the screen pg.display.flip() # start eventloop and wait until # the user clicks on the window corner x while True: for event in pg.event.get(): if event.type == pg.QUIT: raise SystemExit
Last edited by vegaseat : 12 Days Ago at 9:46 am. Reason: removed extra stuff
May 'the Google' be with you!
Something simple for a change, some Python code to use Newton's method to approximate a square root:
python Syntax (Toggle Plain Text)
# use Newton's method to get the square root of a a = 144 # any initial approximation x = 4.0 while True: print x # Newton's square root approximation y = (x + a/x) / 2 # with floats it's safer to compute the absolute value # of the difference between them rather then using y == x # make delta something small delta = 0.000000001 if abs(y - x) < delta: break # now asign y to x and go again # the approximation gets closer with every loop x = y """ my output ---> 4.0 20.0 13.6 12.0941176471 12.0003662165 12.0000000056 12.0 """
No one died when Clinton lied.
Just an application for lambda, and the use of a dictionary to mimic C's switch/case statement:
python Syntax (Toggle Plain Text)
# lambda creates an anonymous function # returnedExpr must be an expression, not a statement # this code could form a simple calculator import math def do_op(op, a=1, b=1): """use of a dictionary similar to C's switch/case""" return { '+': lambda: a + b, '-': lambda: a - b, '*': lambda: a * b, '/': lambda: a / b, '//': lambda: a // b, # floor '**': lambda: a ** b, # power 'sin': lambda: math.sin(a), 'cos': lambda: math.cos(a), 'asin': lambda: math.asin(a), 'acos': lambda: math.acos(a) }[op]() # 355/113.0 pi approx. print do_op('/', 355, 113.0) # 3.14159292035 # sqroot(25) print do_op('**', 25, 0.5) # 5.0 # asin(sin(0.5)) print do_op('asin', do_op('sin', 0.5)) # 0.5
drink her pretty
![]() |
•
•
•
•
•
•
•
•
DaniWeb Python Marketplace
•
•
•
•
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
- Clear the console screen (Python)
- Re: Starting Python (Python)
Other Threads in the Python Forum
- Previous Thread: Strange return of dictionnary
- Next Thread: tkinter class



Linear Mode