User Name Password Register
DaniWeb IT Discussion Community
All
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
Reply
Join Date: Oct 2006
Posts: 1,443
Reputation: sneekula is on a distinguished road 
Rep Power: 4
Solved Threads: 44
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Virtuoso

Re: Starting Python

  #141  
Jul 16th, 2008
The module xlrd can read Excel spreadsheets without the use of COM:
  1. # module xlrd is used to extract data from Excel spreadsheets.
  2. # Handles older and newer formats. Can be used on any platform.
  3. # Has support for Excel dates and is unicode-aware.
  4. # download installer xlrd-0.6.1.win32.exe from:
  5. # http://pypi.python.org/pypi/xlrd
  6. # or:
  7. # http://www.lexicon.net/sjmachin/xlrd.htm
  8.  
  9. import xlrd
  10.  
  11. # pick an Excel file you have
  12. book = xlrd.open_workbook("myfile.xls")
  13.  
  14. sheet = book.sheet_by_index(0)
  15.  
  16. for row in range(sheet.nrows):
  17. print sheet.row(row)
Last edited by sneekula : Jul 16th, 2008 at 4:39 pm.
No one died when Clinton lied.
Reply With Quote  
Join Date: Aug 2008
Posts: 1
Reputation: shrikant.telkar is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 0
shrikant.telkar shrikant.telkar is offline Offline
Newbie Poster

Re: Starting Python

  #142  
Aug 1st, 2008
very nice information
Thank u....
Reply With Quote  
Join Date: Jul 2008
Posts: 1
Reputation: Aneftaoratos is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 0
Aneftaoratos Aneftaoratos is offline Offline
Newbie Poster

Re: Starting Python

  #143  
Aug 1st, 2008
Thanks for the post!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,470
Reputation: vegaseat will become famous soon enough vegaseat will become famous soon enough 
Rep Power: 10
Solved Threads: 176
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Re: Starting Python

  #144  
Aug 14th, 2008
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 ...
  1. def cmp_float(s1, s2):
  2. """
  3. s1 and s2 are numeric strings in a list
  4. compare to sort as floats low to high
  5. """
  6. if float(s1) > float(s2): return 1
  7. elif float(s2) > float(s1): return -1
  8. else: return 0
  9.  
  10.  
  11. q = ['4.5', '11.3', '1.6', '9.4', '10.2', '-7.3']
  12.  
  13. print q
  14. print sorted(q)
  15. # you need to supply a custom compare function
  16. print sorted(q, cmp=cmp_float)
  17.  
  18. """
  19. my output -->
  20. ['4.5', '11.3', '1.6', '9.4', '10.2', '-7.3'] <-- unsorted
  21. ['-7.3', '1.6', '10.2', '11.3', '4.5', '9.4'] <-- sorted as strings
  22. ['-7.3', '1.6', '4.5', '9.4', '10.2', '11.3'] <-- sorted as floats
  23. """
May 'the Google' be with you!
Reply With Quote  
Join Date: Jul 2005
Location: France
Posts: 1,005
Reputation: bumsfeld is an unknown quantity at this point 
Rep Power: 6
Solved Threads: 45
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Veteran Poster

Re: Starting Python

  #145  
Aug 15th, 2008
I was working with patient information and came up with this list of instances that made it relatively easy to find specific information:
  1. # creating and processing one list of class objects
  2.  
  3. import operator
  4.  
  5. class Patient(object):
  6. """__init__() functions as the class constructor"""
  7. def __init__(self, fname=None, sname=None, id=None):
  8. self.fname = fname
  9. self.sname = sname
  10. self.id = id
  11.  
  12. def __repr__(self):
  13. """
  14. if you print the instance of the class this format will display
  15. """
  16. # use the class dictionary iterator
  17. class_dictiter = self.__dict__.iteritems()
  18. return " ".join(["%s: %s" % (k,v) for k,v in class_dictiter])
  19.  
  20.  
  21. # make list of class Patient instances
  22. # instance --> surname, firstname, id
  23. patientList = []
  24. patientList.append(Patient("Elmer", "Fudd", "1234"))
  25. patientList.append(Patient("Donald", "Duck", "1235"))
  26. patientList.append(Patient("Mighty", "Mouse", "1236"))
  27. patientList.append(Patient("Fargo", "Ferkel", "1237"))
  28.  
  29. print "Show/test the whole patientList via __repr__ overload:"
  30. print patientList
  31.  
  32. print '-'*60
  33.  
  34. print "Just one instance in the list via __repr__ overload:"
  35. print patientList[3]
  36.  
  37. print '-'*60
  38.  
  39. print "Show one particular item:"
  40. print patientList[0].sname
  41.  
  42. print '-'*60
  43.  
  44. print "Sort the patientList in place by sname ..."
  45. patientList.sort(key=operator.attrgetter('sname'))
  46.  
  47. print
  48.  
  49. print "... then show all patients info in one nice table:"
  50. for patient in patientList:
  51. print "sname: %-20s fname= %-20s id=%s" % \
  52. (patient.sname, patient.fname, patient.id)
  53.  
  54.  
  55. """
  56. my output -->
  57.  
  58. Show/test the whole patientList via __repr__ overload:
  59. [sname: Fudd id: 1234 fname: Elmer, sname: Duck id: 1235 fname: Donald,
  60. sname: Mouse id: 1236 fname: Mighty, sname: Ferkel id: 1237 fname: Fargo]
  61. ------------------------------------------------------------
  62. Just one instance in the list via __repr__ overload:
  63. sname: Ferkel id: 1237 fname: Fargo
  64. ------------------------------------------------------------
  65. Show one particular item:
  66. Fudd
  67. ------------------------------------------------------------
  68. Sort the patientList in place by sname ...
  69.  
  70. ... then show all patients info in one nice table:
  71. sname: Duck fname= Donald id=1235
  72. sname: Ferkel fname= Fargo id=1237
  73. sname: Fudd fname= Elmer id=1234
  74. sname: Mouse fname= Mighty id=1236
  75.  
  76. """
Should you find Irony, you can keep her!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,470
Reputation: vegaseat will become famous soon enough vegaseat will become famous soon enough 
Rep Power: 10
Solved Threads: 176
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Re: Starting Python

  #146  
13 Days Ago
The module pygame makes it easy to load, display and move images around the screen ...
  1. # experiments with module pygame
  2. # free from: http://www.pygame.org/
  3. # load, display and move an image
  4.  
  5. import pygame as pg
  6.  
  7. # initialize pygame
  8. pg.init()
  9.  
  10. # pick an image you have (.bmp .jpg .png .gif)
  11. # if the image file is not in the working folder,
  12. # use the full pathname like "C:/Images/gifs/Pooh.gif"
  13. image_file = "Pooh.gif"
  14.  
  15. # RGB color tuple used by pygame
  16. white = (255, 255, 255)
  17.  
  18. # create a 300x300 white screen
  19. screen = pg.display.set_mode((300,300))
  20. screen.fill(white)
  21.  
  22. # load the image from a file
  23. # convert() unifies the pixel format for faster blit
  24. image = pg.image.load(image_file).convert()
  25.  
  26. # draw image, position the image ulc at x=50, y=20
  27. screen.blit(image, (50, 20))
  28.  
  29. # get the rectangle the image occupies
  30. # rec(x, y, w, h)
  31. start_rect = image.get_rect()
  32.  
  33. # set up the timed event loop
  34. x = 0
  35. y = 0
  36. clock = pg.time.Clock()
  37. keepGoing = True
  38. while keepGoing:
  39. # set rate of move
  40. clock.tick(30)
  41. for event in pg.event.get():
  42. # quit when user clicks on window x
  43. if event.type == pg.QUIT:
  44. keepGoing = False
  45. # move the image ...
  46. x += 1
  47. y += 1
  48. # stop when x exceeds limit
  49. if x > 270:
  50. keepGoing = False
  51. image_rect = start_rect.move(x, y)
  52. # this erases the old sreen with white
  53. screen.fill(white)
  54. # put the image on the screen at new location
  55. screen.blit(image, image_rect)
  56. # update screen
  57. pg.display.flip()
Last edited by vegaseat : 13 Days Ago at 2:23 pm. Reason: tags adjusted
Attached Images
File Type: gif Pooh.gif (5.3 KB, 27 views)
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,470
Reputation: vegaseat will become famous soon enough vegaseat will become famous soon enough 
Rep Power: 10
Solved Threads: 176
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Re: Starting Python

  #147  
13 Days Ago
You can use the module pygame to load, rotate and zoom an image ...
  1. # experiments with module pygame
  2. # free from: http://www.pygame.org/
  3. # load, rotate, zoom and display an image
  4.  
  5. import pygame as pg
  6.  
  7. # initialize pygame
  8. pg.init()
  9.  
  10. # pick an image you have (.bmp .jpg .png .gif)
  11. # if the image file is not in the working folder,
  12. # use the full pathname like "C:/Images/gifs/Froggy.jpg"
  13. image_file = "Froggy.jpg"
  14.  
  15. # RGB color tuple used by pygame
  16. black = (0, 0, 0)
  17. white = (255, 255, 255)
  18.  
  19. # create a 450x420 black screen
  20. screen = pg.display.set_mode((450,420))
  21. screen.fill(black)
  22.  
  23. # load the image from a file
  24. image = pg.image.load(image_file).convert()
  25.  
  26. # this will rotate the image using angle and zoom using scale
  27. # pygame.transform.rotozoom(surface, angle, scale)
  28. angle = 45.5
  29. scale = 1.5
  30. image = pg.transform.rotozoom(image, angle, scale)
  31.  
  32. # draw image, position the image ulc at x=15, y=5
  33. screen.blit(image, (15, 5))
  34.  
  35. # nothing gets displayed until one updates the screen
  36. pg.display.flip()
  37.  
  38. # start eventloop and wait until
  39. # the user clicks on the window corner x
  40. while True:
  41. for event in pg.event.get():
  42. if event.type == pg.QUIT:
  43. raise SystemExit
Last edited by vegaseat : 12 Days Ago at 9:46 am. Reason: removed extra stuff
Attached Images
File Type: jpg Froggy.jpg (7.5 KB, 1 views)
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2006
Posts: 1,443
Reputation: sneekula is on a distinguished road 
Rep Power: 4
Solved Threads: 44
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Virtuoso

Re: Starting Python

  #148  
10 Days Ago
Something simple for a change, some Python code to use Newton's method to approximate a square root:
  1. # use Newton's method to get the square root of a
  2. a = 144
  3.  
  4. # any initial approximation
  5. x = 4.0
  6. while True:
  7. print x
  8. # Newton's square root approximation
  9. y = (x + a/x) / 2
  10. # with floats it's safer to compute the absolute value
  11. # of the difference between them rather then using y == x
  12. # make delta something small
  13. delta = 0.000000001
  14. if abs(y - x) < delta:
  15. break
  16. # now asign y to x and go again
  17. # the approximation gets closer with every loop
  18. x = y
  19.  
  20. """
  21. my output --->
  22. 4.0
  23. 20.0
  24. 13.6
  25. 12.0941176471
  26. 12.0003662165
  27. 12.0000000056
  28. 12.0
  29. """
No one died when Clinton lied.
Reply With Quote  
Join Date: Oct 2008
Posts: 1
Reputation: bonstein is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 0
bonstein bonstein is offline Offline
Newbie Poster

Re: Starting Python

  #149  
6 Days Ago
thanks for all the little hints, i'm new to programming, i'm pully out my hair and have a blast at the same time
Reply With Quote  
Join Date: Aug 2005
Posts: 1,135
Reputation: Ene Uran is an unknown quantity at this point 
Rep Power: 6
Solved Threads: 66
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Veteran Poster

Re: Starting Python

  #150  
4 Days Ago
Just an application for lambda, and the use of a dictionary to mimic C's switch/case statement:
  1. # lambda creates an anonymous function
  2. # returnedExpr must be an expression, not a statement
  3. # this code could form a simple calculator
  4.  
  5. import math
  6.  
  7. def do_op(op, a=1, b=1):
  8. """use of a dictionary similar to C's switch/case"""
  9. return {
  10. '+': lambda: a + b,
  11. '-': lambda: a - b,
  12. '*': lambda: a * b,
  13. '/': lambda: a / b,
  14. '//': lambda: a // b, # floor
  15. '**': lambda: a ** b, # power
  16. 'sin': lambda: math.sin(a),
  17. 'cos': lambda: math.cos(a),
  18. 'asin': lambda: math.asin(a),
  19. 'acos': lambda: math.acos(a)
  20. }[op]()
  21.  
  22. # 355/113.0 pi approx.
  23. print do_op('/', 355, 113.0) # 3.14159292035
  24.  
  25. # sqroot(25)
  26. print do_op('**', 25, 0.5) # 5.0
  27.  
  28. # asin(sin(0.5))
  29. print do_op('asin', do_op('sin', 0.5)) # 0.5
drink her pretty
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.

DaniWeb Python Marketplace
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)

 

Thread Tools Display Modes

Similar Threads
Other Threads in the Python Forum

All times are GMT -4. The time now is 8:10 am.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC