Starting Python

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Aug 2005
Posts: 1,546
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 174
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Posting Virtuoso

Re: Starting Python

 
0
  #91
Dec 24th, 2006
The Fibonacci series of integers was orignally used in biology to predict the population increase of rodents, or the branching of the veins in a leaf (top to stem).

A Fibonacci number series is made by adding the current number to the previous number to get the next mumber. According to http://en.wikipedia.org/wiki/Fibonacci_number the series starts with 0, 1

This is one of the fastest ways to calculate the Fibonacci series:
  1. def fibo3( n ):
  2. (current, previous) = (0, 1)
  3. k = n
  4. while k > 0:
  5. # use a tuple swap
  6. (current, previous) = (previous, current + previous)
  7. k -= 1
  8. return current
  9.  
  10. for n in range(13):
  11. print fibo3(n),
  12.  
  13. """
  14. example output:
  15. 0 1 1 2 3 5 8 13 21 34 55 89 144
  16. """
This is probably the sweetest way to create a list of the series:
  1. fibo_list = [0,1]
  2. for n in range(input('Enter an integer (>0): ')-1):
  3. fibo_list.append(fibo_list[-2] + fibo_list[-1])
  4. print fibo_list
  5.  
  6. """
  7. example output:
  8. Enter an integer (>0): 12
  9. [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
  10. """
Note: changed php code field tags, don't work properly any more.
Last edited by vegaseat; May 15th, 2007 at 8:06 pm. Reason: spelling req. EU
drink her pretty
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 1,546
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 174
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Posting Virtuoso

Re: Starting Python

 
0
  #92
Dec 29th, 2006
So, you want to do a Google search from your Python program, here is the code:
  1. # search Google
  2.  
  3. import webbrowser
  4.  
  5. search_str = raw_input("Enter Google search string: ")
  6.  
  7. # convert to a list and process
  8. qlist = search_str.split(None)
  9. list1 = []
  10. for q in qlist:
  11. if '+' in q:
  12. q = q.replace('+', '%2B')
  13. if ' ' in q:
  14. q = '"%s"' % q
  15. q = q.replace(' ', '+')
  16. list1.append(q)
  17.  
  18. # convert back to a string
  19. query = '+'.join(list1)
  20. url = "http://www.google.com/search?q=%s" % query
  21.  
  22. webbrowser.open(url)
Last edited by vegaseat; May 15th, 2007 at 8:16 pm. Reason: comments and php tags
drink her pretty
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,042
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 933
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #93
Dec 30th, 2006
Let's say you would like to print 105 numbers and like to show 10 numbers to a row. Here is an example how you can do this using tuple indexing ...
  1. # creating a table of list items
  2. # shows width list items separated by a tab in each row
  3. # uses tuple indexing, selects tuple index False=0 or True=1
  4. # depending on k % width == width-1 compare result
  5.  
  6. # items per row
  7. width = 10
  8. for k, item in enumerate(range(1, 106)):
  9. # indexes width-1 tabs followed by one newline
  10. tab_or_newline = ('\t', '\n')[k % width == width-1]
  11. print "%3s%s" % (item, tab_or_newline),
  12.  
  13. print
Last edited by vegaseat; May 26th, 2007 at 5:08 pm. Reason: more generic code
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,042
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 933
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #94
Jan 14th, 2007
To better familiarize you with Python's 'for loop', here are some experiments ...
  1. # playing around with Python 'for loops'
  2. # for large ranges replace range() with the more efficient xrange()
  3.  
  4. print "iterate over 0 to <6:"
  5. for k in range(6):
  6. print k
  7. print '-'*30 # print 30 dashes
  8.  
  9. print "show odd numbers from 1 to 5:"
  10. for k in range(1, 6, 2):
  11. print k
  12. print '-'*30
  13.  
  14. print "print a table of square roots:"
  15. for x in range(1, 7):
  16. print "the squareroot of %d is %0.4f" % (x, x**0.5)
  17. print '-'*30
  18.  
  19. print "iterate over 0 to <10 and skip a few numbers:"
  20. for k in range(10):
  21. # skip values > 3 or < 7
  22. if 3 < k < 7:
  23. continue
  24. print k
  25. print '-'*30
  26.  
  27. print "start at 11, finish > 0 and decrement by 2:"
  28. for x in range(11, 0, -2):
  29. print x
  30. print '-'*30
  31.  
  32. print "iterate over a tuple of choices:"
  33. for cuisine in "spam", "eggs", "cumquats":
  34. print "I do love", cuisine
  35. print '-'*30
  36.  
  37. print "spell out a string:"
  38. for c in "hello":
  39. print c
  40. print '-'*30
  41.  
  42. print "create a string of 'a' to 'z' characters:"
  43. s = ""
  44. for c in range(ord('a'), ord('z') + 1):
  45. s += chr(c)
  46. print s
  47. print '-'*30
  48.  
  49. print "create a simple histogram:"
  50. data = 1, 3, 6, 9, 7, 4, 2
  51. for x in data:
  52. print '*' * x
  53. print '-'*30
  54.  
  55. def qrange(start, stop=None, step=1):
  56. """
  57. similar to xrange() but handles floats
  58. """
  59. # when only one arg is given ...
  60. if stop == None:
  61. stop = start
  62. start = 0
  63. # allow for decrement
  64. if step < 0:
  65. while start > stop:
  66. # yield makes this a generator
  67. yield start
  68. start += step
  69. else:
  70. while start < stop:
  71. yield start
  72. start += step
  73.  
  74. print "testing list(qrange(0.2, 10, 1.5)):"
  75. print list(qrange(0, 10, 1.5))
  76. print '-'*30
  77.  
  78. print "the 'for loop' iterates over qrange(1, 2, 0.3):"
  79. for x in qrange(1, 2, 0.3):
  80. print x
  81.  
  82. """
  83. output -->
  84. iterate over 0 to <6:
  85. 0
  86. 1
  87. 2
  88. 3
  89. 4
  90. 5
  91. ------------------------------
  92. show odd numbers from 1 to 5:
  93. 1
  94. 3
  95. 5
  96. ------------------------------
  97. print a table of square roots:
  98. the squareroot of 1 is 1.0000
  99. the squareroot of 2 is 1.4142
  100. the squareroot of 3 is 1.7321
  101. the squareroot of 4 is 2.0000
  102. the squareroot of 5 is 2.2361
  103. the squareroot of 6 is 2.4495
  104. ------------------------------
  105. iterate over 0 to <10 and skip a few numbers:
  106. 0
  107. 1
  108. 2
  109. 3
  110. 7
  111. 8
  112. 9
  113. ------------------------------
  114. start at 11, finish > 0 and decrement by 2:
  115. 11
  116. 9
  117. 7
  118. 5
  119. 3
  120. 1
  121. ------------------------------
  122. iterate over a tuple of choices:
  123. I do love spam
  124. I do love eggs
  125. I do love cumquats
  126. ------------------------------
  127. spell out a string:
  128. h
  129. e
  130. l
  131. l
  132. o
  133. ------------------------------
  134. create a string of 'a' to 'z' characters:
  135. abcdefghijklmnopqrstuvwxyz
  136. ------------------------------
  137. create a simple histogram:
  138. *
  139. ***
  140. ******
  141. *********
  142. *******
  143. ****
  144. **
  145. ------------------------------
  146. testing the list(qrange(0.2, 10, 1.5)):
  147. [0, 1.5, 3.0, 4.5, 6.0, 7.5, 9.0]
  148. ------------------------------
  149. the 'for loop' iterates over qrange(1, 2, 0.3):
  150. 1
  151. 1.3
  152. 1.6
  153. 1.9
  154. """
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,042
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 933
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #95
Jan 20th, 2007
Grandma Vegaseat gets her Social Security Payment deposited on the third Wednesday of each month, so I wrote her this little Python program ...
  1. # print out the third Wednesdays of each month in a given year
  2.  
  3. import calendar
  4.  
  5. # makes Monday first day of week (this is the default)
  6. calendar.setfirstweekday(calendar.MONDAY)
  7.  
  8. year = int(raw_input("Enter year: "))
  9. print "The third Wednesdays of each month in %d:" % year
  10. for month in range(1, 13):
  11. k = 0
  12. for day in range(1, 32):
  13. try:
  14. weekday = calendar.weekday( year, month, day)
  15. except ValueError:
  16. continue
  17. if weekday == calendar.WEDNESDAY:
  18. k += 1
  19. if k == 3:
  20. # format the result
  21. print "%02d/%02d/%d" % (month, day, year)
  22.  
  23. """
  24. Enter year: 2007
  25. The third Wednesdays of each month in 2007:
  26. 01/17/2007
  27. 02/21/2007
  28. 03/21/2007
  29. 04/18/2007
  30. 05/16/2007
  31. 06/20/2007
  32. 07/18/2007
  33. 08/15/2007
  34. 09/19/2007
  35. 10/17/2007
  36. 11/21/2007
  37. 12/19/2007
  38. """
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,042
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 933
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #96
Jan 22nd, 2007
Just a couple of code samples to show you how you can get started with Graphics User Interface (GUI) programming. I am using the Tkinter GUI toolkit since it is simple to use and is included in most Python installations.

Here is the simple and rather blah console version ...
  1. print "Hello, world!"
  2.  
  3. raw_input("Press Enter to go on ... ") # console output wait
Tkinter to the rescue, to create at least a window ...
  1. # a simple "Hello, world!" Tkinter GUI
  2.  
  3. # import Tkinter as namespace tk
  4. import Tkinter as tk
  5.  
  6. # create the basic window, let's call it 'root'
  7. root = tk.Tk()
  8.  
  9. # create a label
  10. label1 = tk.Label(root, text="Hello, world!")
  11. # pack the label into the window
  12. label1.pack()
  13.  
  14. # run the GUI event loop
  15. root.mainloop()
Still blah, let's add some color ...
  1. # a simple "Hello, world!" Tkinter GUI
  2. # add some color
  3.  
  4. # import Tkinter as namespace tk
  5. import Tkinter as tk
  6.  
  7. # create the basic window, let's call it 'root'
  8. root = tk.Tk()
  9.  
  10. # create a label with colors in it
  11. label1 = tk.Label(root, text="Hello, world!", fg='red', bg='yellow')
  12. # pack the label into the window
  13. label1.pack()
  14.  
  15. # run the GUI event loop
  16. root.mainloop()
Looks a little better, but we should really make the text stand out ...
  1. # a simple "Hello, world!" Tkinter GUI
  2. # add some color and a larger text font
  3.  
  4. # import Tkinter as namespace tk
  5. import Tkinter as tk
  6.  
  7. # create the basic window, let's call it 'root'
  8. root = tk.Tk()
  9.  
  10. # create a label with colors in it
  11. # note that the label auto-expands to fit the large text
  12. font1 = ('times', 30, 'bold')
  13. label1 = tk.Label(root, text="Hello, world!", font=font1, fg='red', bg='yellow')
  14. # pack the label into the window
  15. label1.pack()
  16.  
  17. # run the GUI event loop
  18. root.mainloop()
Hey, looks flashy, can we change the colors? Maybe with a button click ...
  1. # a simple "Hello, world!" Tkinter GUI
  2. # add some color and a larger text font
  3. # add buttons to change text color
  4.  
  5. # import Tkinter as namespace tk
  6. import Tkinter as tk
  7.  
  8. def white_blue():
  9. label1.config(fg='white', bg='blue')
  10.  
  11. def blue_green():
  12. label1.config(fg='blue', bg='green')
  13.  
  14. # create the basic window, let's call it 'root'
  15. root = tk.Tk()
  16.  
  17. # create a label with colors in it
  18. font1 = ('times', 30, 'bold')
  19. label1 = tk.Label(root, text="Hello, world!", font=font1, fg='red', bg='yellow')
  20. # let's use a grid to put the label into the window
  21. # make it span two grid columns
  22. label1.grid(row=0, column=0, columnspan=2)
  23. # create 2 buttons to click for text color change
  24. # use the two grid positions below the label
  25. # (by default the button will take up the center of each grid space)
  26. button1 = tk.Button(root, text="white on blue", command=white_blue)
  27. button1.grid(row=1, column=0)
  28. button2 = tk.Button(root, text="blue on green", command=blue_green)
  29. button2.grid(row=1, column=1)
  30.  
  31. # run the GUI event loop
  32. root.mainloop()
Almost there, let's fancy up the buttons and give the window a befitting title ...
  1. # a simple "Hello, world!" Tkinter GUI
  2. # add some color and a larger text font
  3. # add buttons to change text color and fancy them up
  4.  
  5. # import Tkinter as namespace tk
  6. import Tkinter as tk
  7.  
  8. def white_blue():
  9. label1.config(fg='white', bg='blue')
  10.  
  11. def blue_green():
  12. label1.config(fg='blue', bg='green')
  13.  
  14. # create the basic window, let's call it 'root'
  15. root = tk.Tk()
  16. # why not add a title
  17. root.title("Hello World from DaniWeb!")
  18.  
  19. # create a label with colors in it
  20. font1 = ('times', 36, 'bold')
  21. label1 = tk.Label(root, text="Hello, world!", font=font1, fg='red', bg='yellow')
  22. # let's use a grid to put the label into the window
  23. # make it span two grid columns
  24. label1.grid(row=0, column=0, columnspan=2)
  25. # create 2 buttons to click for text color change
  26. # use the two grid positions below the label
  27. # (by default the button will take up the center of each grid space)
  28. # give the buttons some y-axis space and a ridge style
  29. button1 = tk.Button(root, text="white on blue", relief='ridge', command=white_blue)
  30. button1.grid(row=1, column=0, pady=5)
  31. button2 = tk.Button(root, text="blue on green", relief='ridge', command=blue_green)
  32. button2.grid(row=1, column=1, pady=5)
  33.  
  34. # run the GUI event loop
  35. root.mainloop()
I hope the development of the GUI code made sense to you, and you are willing to convert one of your console programs to the colorful world of mouse clicks.

John Zelle has written a graphics module (a thin wrapper for Tkinter) that makes GUI coding fairly simple. This module is popular with a number of schools ...
http://mcsp.wartburg.edu/zelle/python/graphics.py
He also has provided nice documentation ...
http://mcsp.wartburg.edu/zelle/pytho...s/graphics.pdf
Last edited by vegaseat; Jan 24th, 2007 at 5:32 pm. Reason: more info
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,042
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 933
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #97
Feb 2nd, 2007
Every computer language has to have its bouncing ball code example. Here is the bouncing ball using Python's pygame module ...
  1. # experiments with module pygame
  2. # free from: [url]http://www.pygame.org/[/url]
  3. # bounce a red ball
  4.  
  5. import pygame as pg
  6.  
  7. # initialize pygame
  8. pg.init()
  9.  
  10. # use this image file or an image file you have
  11. # pygame allows these image formats .bmp .jpg .png .gif
  12. image_file = "ball_r.gif"
  13.  
  14. # image moves [x, y] at a time
  15. im_dir = [2, 1]
  16.  
  17. # pygame uses an RGB color tuple
  18. black = (0,0,0)
  19. # screen width and height
  20. sw = 600
  21. sh = 480
  22. # create a screen
  23. screen = pg.display.set_mode((sw, sh))
  24. # give the screen a title
  25. pg.display.set_caption('bouncing ball (press escape to exit)')
  26.  
  27. # load the ball image file
  28. image = pg.image.load(image_file).convert()
  29. # get the rectangle the image occupies
  30. im_rect = image.get_rect()
  31.  
  32. # the event loop also loops the animation code
  33. while True:
  34. pg.event.pump()
  35. keyinput = pg.key.get_pressed()
  36. # exit on corner 'x' click or escape key press
  37. if keyinput[pg.K_ESCAPE] or pg.event.peek(pg.QUIT):
  38. raise SystemExit
  39.  
  40. # set the move
  41. im_rect = im_rect.move(im_dir)
  42. # detect the boundaries and change directions
  43. # left/right boundaries are 0 to sreen width
  44. if im_rect.left < 0 or im_rect.right > sw:
  45. im_dir[0] = -im_dir[0]
  46. # top/bottom boundaries are 0 to screen height
  47. if im_rect.top < 0 or im_rect.bottom > sh:
  48. im_dir[1] = -im_dir[1]
  49. # this erases the old sreen with black
  50. screen.fill(black)
  51. # put the image on the screen
  52. screen.blit(image, im_rect)
  53. # update screen
  54. pg.display.flip()
The image file of a red ball is attached.

Note: Pygame hasn't been released for Python25 yet. They are asking fo a few more weeks to perfect Pygame181.
Last edited by vegaseat; Feb 2nd, 2007 at 11:12 pm.
Attached Images
 
Attached Files
File Type: zip ball_r.zip (1.8 KB, 14 views)
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 1,221
Reputation: bumsfeld will become famous soon enough bumsfeld will become famous soon enough 
Solved Threads: 137
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Nearly a Posting Virtuoso

Re: Starting Python

 
0
  #98
Feb 15th, 2007
Just short example how to build very simple pygame program (similar to vegaseat's Hello):
  1. # module pygame free from: http://www.pygame.org
  2. # "Hello World" with colour and nice font
  3.  
  4. import pygame as pg
  5.  
  6. # initialize pygame
  7. pg.init()
  8.  
  9. # RGB colour tuple pygame uses
  10. yellow = (255,255,0)
  11.  
  12. # create screen/surface of width=480 and height=80
  13. screen = pg.display.set_mode((380, 60))
  14. # add nice title
  15. pg.display.set_caption('Hello World from DaniWeb!')
  16.  
  17. # create surface (canvas) in memory
  18. surface = pg.Surface(screen.get_size())
  19. # fill surface
  20. surface.fill(yellow)
  21.  
  22. # display some text in given font
  23. font = pg.font.SysFont('Comic Sans MS', 36)
  24. text = font.render("Hello World!", 1, (10, 10, 10))
  25. textpos = text.get_rect()
  26. # have text center coincide with surface center position
  27. textpos.centerx = surface.get_rect().centerx
  28. # transfer text area to surface area (now centered)
  29. surface.blit(text, textpos)
  30.  
  31. # transfer surface area to screen area at ulc x=0,y=0
  32. screen.blit(surface, (0, 0))
  33. # update to show it on the computer display
  34. pg.display.flip()
  35.  
  36. # run event loop and provide exit conditions
  37. while True:
  38. for event in pg.event.get():
  39. # the title 'x' click
  40. if event.type == pg.QUIT:
  41. raise SystemExit
Last edited by bumsfeld; Feb 15th, 2007 at 2:14 pm.
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,042
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 933
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #99
May 14th, 2007
Here is an example of making a simple 'guess a number game' more appealing using the Tkinter GUI toolkit and multiple buttons ...
  1. # Tkinter 'guess an integer' game
  2.  
  3. from Tkinter import *
  4. import random
  5. import time
  6.  
  7. class NumberGuess(object):
  8. def __init__(self, root):
  9. self.root = root
  10. # let the user know what is going on
  11. self.label1 = Label(root, text="Guess a number between 1 and 10", bg='yellow')
  12. self.label1.place(x=10, y=10)
  13. # prompt the user
  14. self.label2 = Label(root, text="Click the button of your guess:")
  15. self.label2.place(x=10, y=35)
  16. # the result displays here
  17. self.label3 = Label(root, text="", bg='green')
  18. self.label3.place(x=10, y=100, width=200, height=20)
  19. # create a row of ten buttons
  20. self.make_buttons()
  21. # pick a random integer from 1 to 10
  22. self.rn = random.randrange(1, 11)
  23.  
  24. def make_buttons(self):
  25. """make ten buttons in a row labeled 1 to 10"""
  26. self.buttons = [None]
  27. x = 10
  28. for index in range(1,11):
  29. self.buttons.append(
  30. Button(self.root, text=index, fg="black", width=1,
  31. command=lambda i=index: self.click(i)))
  32. self.buttons[-1].place(x=x, y=60)
  33. x += 20
  34.  
  35. def reset_buttons(self):
  36. for index in range(1,11):
  37. self.buttons[index].configure(fg='black')
  38.  
  39. def click(self, index):
  40. root.title('Guess!')
  41. self.label3['bg'] ='green'
  42. # this will mark the number picked in red
  43. self.buttons[index].configure(fg='red')
  44. num = int(index)
  45. guess = " (%s)" % num
  46. # check it out
  47. if num > self.rn:
  48. self.label3['text'] = 'Lower!' + guess
  49. elif num < self.rn:
  50. self.label3['text'] = 'Higher!' + guess
  51. else:
  52. self.label3['bg'] ='red'
  53. self.label3['text'] = 'Guessed correctly!' + guess
  54. root.title('New game!')
  55. # reset all buttons to black
  56. self.reset_buttons()
  57. # new game, set new random number
  58. self.rn = random.randrange(1, 11)
  59.  
  60. root = Tk()
  61. root.title()
  62. root.geometry("240x130+30+30")
  63. app = NumberGuess(root)
  64. root.mainloop()
Last edited by vegaseat; May 14th, 2007 at 5:39 pm.
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: May 2007
Posts: 311
Reputation: BearofNH is on a distinguished road 
Solved Threads: 40
BearofNH's Avatar
BearofNH BearofNH is offline Offline
Posting Whiz

Starting Python -- generators

 
0
  #100
May 17th, 2007
I don't see much here on generators. They are a nice feature of Python that everyone should know.

Generators are neat ways of doing certain things that involve iterative work. For example, instead of calling a fibonacci function to return fibonacci numbers in a list (say), we create a generator object and iterate over it to return objects one at a time. That way we get them when we need them and can toss them when we're done. In its simplest form with no upper limit:
  1. >>> def fiball():
  2. ... x0 = 1
  3. ... x1 = 1
  4. ... yield x0
  5. ... while True:
  6. ... yield x1
  7. ... xNext = x0+x1
  8. ... x0=x1
  9. ... x1=xNext
  10. ...
  11. >>> fg = fiball()
  12. >>> fg
  13. <generator object at 0x00D87DA0>
  14. >>> fg.next()
  15. 1
  16. >>> fg.next()
  17. 1
  18. >>> fg.next()
  19. 2
  20. >>> fg.next()
  21. 3
  22. >>> fg.next()
  23. 5
  24. >>> for i in range(13):
  25. ... print fg.next(),
  26. ...
  27. 8 13 21 34 55 89 144 233 377 610 987 1597 2584
  28. >>>

Calling fiball() returns a generator object, rather than doing any calculations. Whenever you invoke the generator object's next()method, you cause the generator's code to execute until it hits a yield X, at which point it remembers its state and returns X. Further calls to next() continue the generator's execution after the yield statement, picking up right where it left off. So there's sort of a ping-pong effect, with next() invoking the generator where it left off, and yield returning the "next" value.

The generator code looks just like a function definition. The presence of a yield statement is what tells Python this is a generator instead of a function.

Sometimes you want to have a generator "stop generating", analagous to the way range(10) has a defined stopping point. The generator would do this by just returning. We can modify the above generator to accept an upper limit and return when we have exceeded that limit. The result looks like:
  1. def fibmax(upper_limit): # Parameter is new
  2. x0 = 1
  3. x1 = 1
  4. yield x0
  5. while x1 < upper_limit: # Not always true
  6. yield x1
  7. xNext = x0+x1
  8. x0=x1
  9. x1=xNext
  10. # Fall thru to here when we pass upper_limit, exiting the generator
  11.  
  12. fm = fibmax(1000) # Generate fibonacci's up to 1000
  13. for xx in fm: # Iterate over the fm object
  14. print xx,
Produces the output:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
Of course, you're not limited to making sequential calls to the next() method, you can execute arbitrary code between successive next() calls. And you can create multiple generators from the same object, each with their own separate context.

The best features of generators require Python 2.5 or later. There's good documentation at the python website.
Reply With Quote Quick reply to this message  
Reply

Tags
code, hints, python, tricks, tutorial

Message:



Similar Threads
Other Threads in the Python Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC