| | |
Starting Python
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
![]() |
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:
This is probably the sweetest way to create a list of the series:
Note: changed php code field tags, don't work properly any more.
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:
python Syntax (Toggle Plain Text)
def fibo3( n ): (current, previous) = (0, 1) k = n while k > 0: # use a tuple swap (current, previous) = (previous, current + previous) k -= 1 return current for n in range(13): print fibo3(n), """ example output: 0 1 1 2 3 5 8 13 21 34 55 89 144 """
python Syntax (Toggle Plain Text)
fibo_list = [0,1] for n in range(input('Enter an integer (>0): ')-1): fibo_list.append(fibo_list[-2] + fibo_list[-1]) print fibo_list """ example output: Enter an integer (>0): 12 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144] """
Last edited by vegaseat; May 15th, 2007 at 8:06 pm. Reason: spelling req. EU
drink her pretty
So, you want to do a Google search from your Python program, here is the code:
python Syntax (Toggle Plain Text)
# search Google import webbrowser search_str = raw_input("Enter Google search string: ") # convert to a list and process qlist = search_str.split(None) list1 = [] for q in qlist: if '+' in q: q = q.replace('+', '%2B') if ' ' in q: q = '"%s"' % q q = q.replace(' ', '+') list1.append(q) # convert back to a string query = '+'.join(list1) url = "http://www.google.com/search?q=%s" % query webbrowser.open(url)
Last edited by vegaseat; May 15th, 2007 at 8:16 pm. Reason: comments and php tags
drink her pretty
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 ...
python Syntax (Toggle Plain Text)
# creating a table of list items # shows width list items separated by a tab in each row # uses tuple indexing, selects tuple index False=0 or True=1 # depending on k % width == width-1 compare result # items per row width = 10 for k, item in enumerate(range(1, 106)): # indexes width-1 tabs followed by one newline tab_or_newline = ('\t', '\n')[k % width == width-1] print "%3s%s" % (item, tab_or_newline),
Last edited by vegaseat; May 26th, 2007 at 5:08 pm. Reason: more generic code
May 'the Google' be with you!
To better familiarize you with Python's 'for loop', here are some experiments ...
python Syntax (Toggle Plain Text)
# playing around with Python 'for loops' # for large ranges replace range() with the more efficient xrange() print "iterate over 0 to <6:" for k in range(6): print k print '-'*30 # print 30 dashes print "show odd numbers from 1 to 5:" for k in range(1, 6, 2): print k print '-'*30 print "print a table of square roots:" for x in range(1, 7): print "the squareroot of %d is %0.4f" % (x, x**0.5) print '-'*30 print "iterate over 0 to <10 and skip a few numbers:" for k in range(10): # skip values > 3 or < 7 if 3 < k < 7: continue print k print '-'*30 print "start at 11, finish > 0 and decrement by 2:" for x in range(11, 0, -2): print x print '-'*30 print "iterate over a tuple of choices:" for cuisine in "spam", "eggs", "cumquats": print "I do love", cuisine print '-'*30 print "spell out a string:" for c in "hello": print c print '-'*30 print "create a string of 'a' to 'z' characters:" s = "" for c in range(ord('a'), ord('z') + 1): s += chr(c) print s print '-'*30 print "create a simple histogram:" data = 1, 3, 6, 9, 7, 4, 2 for x in data: print '*' * x print '-'*30 def qrange(start, stop=None, step=1): """ similar to xrange() but handles floats """ # when only one arg is given ... if stop == None: stop = start start = 0 # allow for decrement if step < 0: while start > stop: # yield makes this a generator yield start start += step else: while start < stop: yield start start += step print "testing list(qrange(0.2, 10, 1.5)):" print list(qrange(0, 10, 1.5)) print '-'*30 print "the 'for loop' iterates over qrange(1, 2, 0.3):" for x in qrange(1, 2, 0.3): print x """ output --> iterate over 0 to <6: 0 1 2 3 4 5 ------------------------------ show odd numbers from 1 to 5: 1 3 5 ------------------------------ print a table of square roots: the squareroot of 1 is 1.0000 the squareroot of 2 is 1.4142 the squareroot of 3 is 1.7321 the squareroot of 4 is 2.0000 the squareroot of 5 is 2.2361 the squareroot of 6 is 2.4495 ------------------------------ iterate over 0 to <10 and skip a few numbers: 0 1 2 3 7 8 9 ------------------------------ start at 11, finish > 0 and decrement by 2: 11 9 7 5 3 1 ------------------------------ iterate over a tuple of choices: I do love spam I do love eggs I do love cumquats ------------------------------ spell out a string: h e l l o ------------------------------ create a string of 'a' to 'z' characters: abcdefghijklmnopqrstuvwxyz ------------------------------ create a simple histogram: * *** ****** ********* ******* **** ** ------------------------------ testing the list(qrange(0.2, 10, 1.5)): [0, 1.5, 3.0, 4.5, 6.0, 7.5, 9.0] ------------------------------ the 'for loop' iterates over qrange(1, 2, 0.3): 1 1.3 1.6 1.9 """
May 'the Google' be with you!
Grandma Vegaseat gets her Social Security Payment deposited on the third Wednesday of each month, so I wrote her this little Python program ...
Python Syntax (Toggle Plain Text)
# print out the third Wednesdays of each month in a given year import calendar # makes Monday first day of week (this is the default) calendar.setfirstweekday(calendar.MONDAY) year = int(raw_input("Enter year: ")) print "The third Wednesdays of each month in %d:" % year for month in range(1, 13): k = 0 for day in range(1, 32): try: weekday = calendar.weekday( year, month, day) except ValueError: continue if weekday == calendar.WEDNESDAY: k += 1 if k == 3: # format the result print "%02d/%02d/%d" % (month, day, year) """ Enter year: 2007 The third Wednesdays of each month in 2007: 01/17/2007 02/21/2007 03/21/2007 04/18/2007 05/16/2007 06/20/2007 07/18/2007 08/15/2007 09/19/2007 10/17/2007 11/21/2007 12/19/2007 """
May 'the Google' be with you!
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 ...
Tkinter to the rescue, to create at least a window ...
Still blah, let's add some color ...
Looks a little better, but we should really make the text stand out ...
Hey, looks flashy, can we change the colors? Maybe with a button click ...
Almost there, let's fancy up the buttons and give the window a befitting title ...
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
Here is the simple and rather blah console version ...
python Syntax (Toggle Plain Text)
print "Hello, world!" raw_input("Press Enter to go on ... ") # console output wait
python Syntax (Toggle Plain Text)
# a simple "Hello, world!" Tkinter GUI # import Tkinter as namespace tk import Tkinter as tk # create the basic window, let's call it 'root' root = tk.Tk() # create a label label1 = tk.Label(root, text="Hello, world!") # pack the label into the window label1.pack() # run the GUI event loop root.mainloop()
python Syntax (Toggle Plain Text)
# a simple "Hello, world!" Tkinter GUI # add some color # import Tkinter as namespace tk import Tkinter as tk # create the basic window, let's call it 'root' root = tk.Tk() # create a label with colors in it label1 = tk.Label(root, text="Hello, world!", fg='red', bg='yellow') # pack the label into the window label1.pack() # run the GUI event loop root.mainloop()
python Syntax (Toggle Plain Text)
# a simple "Hello, world!" Tkinter GUI # add some color and a larger text font # import Tkinter as namespace tk import Tkinter as tk # create the basic window, let's call it 'root' root = tk.Tk() # create a label with colors in it # note that the label auto-expands to fit the large text font1 = ('times', 30, 'bold') label1 = tk.Label(root, text="Hello, world!", font=font1, fg='red', bg='yellow') # pack the label into the window label1.pack() # run the GUI event loop root.mainloop()
python Syntax (Toggle Plain Text)
# a simple "Hello, world!" Tkinter GUI # add some color and a larger text font # add buttons to change text color # import Tkinter as namespace tk import Tkinter as tk def white_blue(): label1.config(fg='white', bg='blue') def blue_green(): label1.config(fg='blue', bg='green') # create the basic window, let's call it 'root' root = tk.Tk() # create a label with colors in it font1 = ('times', 30, 'bold') label1 = tk.Label(root, text="Hello, world!", font=font1, fg='red', bg='yellow') # let's use a grid to put the label into the window # make it span two grid columns label1.grid(row=0, column=0, columnspan=2) # create 2 buttons to click for text color change # use the two grid positions below the label # (by default the button will take up the center of each grid space) button1 = tk.Button(root, text="white on blue", command=white_blue) button1.grid(row=1, column=0) button2 = tk.Button(root, text="blue on green", command=blue_green) button2.grid(row=1, column=1) # run the GUI event loop root.mainloop()
python Syntax (Toggle Plain Text)
# a simple "Hello, world!" Tkinter GUI # add some color and a larger text font # add buttons to change text color and fancy them up # import Tkinter as namespace tk import Tkinter as tk def white_blue(): label1.config(fg='white', bg='blue') def blue_green(): label1.config(fg='blue', bg='green') # create the basic window, let's call it 'root' root = tk.Tk() # why not add a title root.title("Hello World from DaniWeb!") # create a label with colors in it font1 = ('times', 36, 'bold') label1 = tk.Label(root, text="Hello, world!", font=font1, fg='red', bg='yellow') # let's use a grid to put the label into the window # make it span two grid columns label1.grid(row=0, column=0, columnspan=2) # create 2 buttons to click for text color change # use the two grid positions below the label # (by default the button will take up the center of each grid space) # give the buttons some y-axis space and a ridge style button1 = tk.Button(root, text="white on blue", relief='ridge', command=white_blue) button1.grid(row=1, column=0, pady=5) button2 = tk.Button(root, text="blue on green", relief='ridge', command=blue_green) button2.grid(row=1, column=1, pady=5) # run the GUI event loop root.mainloop()
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!
Every computer language has to have its bouncing ball code example. Here is the bouncing ball using Python's pygame module ...
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.
python Syntax (Toggle Plain Text)
# experiments with module pygame # free from: [url]http://www.pygame.org/[/url] # bounce a red ball import pygame as pg # initialize pygame pg.init() # use this image file or an image file you have # pygame allows these image formats .bmp .jpg .png .gif image_file = "ball_r.gif" # image moves [x, y] at a time im_dir = [2, 1] # pygame uses an RGB color tuple black = (0,0,0) # screen width and height sw = 600 sh = 480 # create a screen screen = pg.display.set_mode((sw, sh)) # give the screen a title pg.display.set_caption('bouncing ball (press escape to exit)') # load the ball image file image = pg.image.load(image_file).convert() # get the rectangle the image occupies im_rect = image.get_rect() # the event loop also loops the animation code while True: pg.event.pump() keyinput = pg.key.get_pressed() # exit on corner 'x' click or escape key press if keyinput[pg.K_ESCAPE] or pg.event.peek(pg.QUIT): raise SystemExit # set the move im_rect = im_rect.move(im_dir) # detect the boundaries and change directions # left/right boundaries are 0 to sreen width if im_rect.left < 0 or im_rect.right > sw: im_dir[0] = -im_dir[0] # top/bottom boundaries are 0 to screen height if im_rect.top < 0 or im_rect.bottom > sh: im_dir[1] = -im_dir[1] # this erases the old sreen with black screen.fill(black) # put the image on the screen screen.blit(image, im_rect) # update screen pg.display.flip()
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.
May 'the Google' be with you!
Just short example how to build very simple pygame program (similar to vegaseat's Hello):
python Syntax (Toggle Plain Text)
# module pygame free from: http://www.pygame.org # "Hello World" with colour and nice font import pygame as pg # initialize pygame pg.init() # RGB colour tuple pygame uses yellow = (255,255,0) # create screen/surface of width=480 and height=80 screen = pg.display.set_mode((380, 60)) # add nice title pg.display.set_caption('Hello World from DaniWeb!') # create surface (canvas) in memory surface = pg.Surface(screen.get_size()) # fill surface surface.fill(yellow) # display some text in given font font = pg.font.SysFont('Comic Sans MS', 36) text = font.render("Hello World!", 1, (10, 10, 10)) textpos = text.get_rect() # have text center coincide with surface center position textpos.centerx = surface.get_rect().centerx # transfer text area to surface area (now centered) surface.blit(text, textpos) # transfer surface area to screen area at ulc x=0,y=0 screen.blit(surface, (0, 0)) # update to show it on the computer display pg.display.flip() # run event loop and provide exit conditions while True: for event in pg.event.get(): # the title 'x' click if event.type == pg.QUIT: raise SystemExit
Last edited by bumsfeld; Feb 15th, 2007 at 2:14 pm.
Here is an example of making a simple 'guess a number game' more appealing using the Tkinter GUI toolkit and multiple buttons ...
python Syntax (Toggle Plain Text)
# Tkinter 'guess an integer' game from Tkinter import * import random import time class NumberGuess(object): def __init__(self, root): self.root = root # let the user know what is going on self.label1 = Label(root, text="Guess a number between 1 and 10", bg='yellow') self.label1.place(x=10, y=10) # prompt the user self.label2 = Label(root, text="Click the button of your guess:") self.label2.place(x=10, y=35) # the result displays here self.label3 = Label(root, text="", bg='green') self.label3.place(x=10, y=100, width=200, height=20) # create a row of ten buttons self.make_buttons() # pick a random integer from 1 to 10 self.rn = random.randrange(1, 11) def make_buttons(self): """make ten buttons in a row labeled 1 to 10""" self.buttons = [None] x = 10 for index in range(1,11): self.buttons.append( Button(self.root, text=index, fg="black", width=1, command=lambda i=index: self.click(i))) self.buttons[-1].place(x=x, y=60) x += 20 def reset_buttons(self): for index in range(1,11): self.buttons[index].configure(fg='black') def click(self, index): root.title('Guess!') self.label3['bg'] ='green' # this will mark the number picked in red self.buttons[index].configure(fg='red') num = int(index) guess = " (%s)" % num # check it out if num > self.rn: self.label3['text'] = 'Lower!' + guess elif num < self.rn: self.label3['text'] = 'Higher!' + guess else: self.label3['bg'] ='red' self.label3['text'] = 'Guessed correctly!' + guess root.title('New game!') # reset all buttons to black self.reset_buttons() # new game, set new random number self.rn = random.randrange(1, 11) root = Tk() root.title() root.geometry("240x130+30+30") app = NumberGuess(root) root.mainloop()
Last edited by vegaseat; May 14th, 2007 at 5:39 pm.
May 'the Google' be with you!
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:
Calling
The generator code looks just like a function definition. The presence of a
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:
Produces the output:
Of course, you're not limited to making sequential calls to the
The best features of generators require Python 2.5 or later. There's good documentation at the python website.
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:
Python Syntax (Toggle Plain Text)
>>> def fiball(): ... x0 = 1 ... x1 = 1 ... yield x0 ... while True: ... yield x1 ... xNext = x0+x1 ... x0=x1 ... x1=xNext ... >>> fg = fiball() >>> fg <generator object at 0x00D87DA0> >>> fg.next() 1 >>> fg.next() 1 >>> fg.next() 2 >>> fg.next() 3 >>> fg.next() 5 >>> for i in range(13): ... print fg.next(), ... 8 13 21 34 55 89 144 233 377 610 987 1597 2584 >>>
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:
python Syntax (Toggle Plain Text)
def fibmax(upper_limit): # Parameter is new x0 = 1 x1 = 1 yield x0 while x1 < upper_limit: # Not always true yield x1 xNext = x0+x1 x0=x1 x1=xNext # Fall thru to here when we pass upper_limit, exiting the generator fm = fibmax(1000) # Generate fibonacci's up to 1000 for xx in fm: # Iterate over the fm object print xx,
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987Of 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.
![]() |
Similar Threads
- CGPA calculator (Python)
- Beginning: Starting Python (Python)
- Clear the console screen (Python)
- Re: Starting Python (Python)
Other Threads in the Python Forum
- Previous Thread: Decimal formatting
- Next Thread: Python - Using a text file to feed into a python dictionary
| Thread Tools | Search this Thread |
10 access ada advanced ajax api arax array bash beginner blogger blogging bug bugs c++ code combo convert creat csv cturtle daniweb data development dictionary dropdownlist embed event examples excel file format function game gdata google gui images innovation input java keycontrol linux list loan microsoft module mvcmodel2 net newb news obexftp parameters password php post problem profile program programming projects py2exe pygame pyopengl python random raw_input recursive reuse reverse rss ruby script shebang skinning source sprite string syntax table terminal threading time tkinter tooltip tutorial ubuntu url urllib urllib2 variable vb virus visual web web-scrape website wikipedia wxpython xml







