Starting Python

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

Join Date: Oct 2004
Posts: 4,069
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: 938
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #51
Mar 13th, 2006
Just an example how to work with Tkinter's color pick dialog ...
  1. # select a color and color the root window
  2.  
  3. from Tkinter import *
  4. import tkColorChooser
  5.  
  6. #help('tkColorChooser')
  7.  
  8. root = Tk()
  9.  
  10. colorTuple = tkColorChooser.askcolor()
  11.  
  12. print colorTuple # for red = ((255, 0, 0), '#ff0000')
  13. print colorTuple[1] # #ff0000
  14.  
  15. root.configure(bg=colorTuple[1])
  16.  
  17. root.mainloop()
Last edited by vegaseat; May 15th, 2007 at 7:02 pm. Reason: replaced old php tags
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,069
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: 938
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #52
Mar 14th, 2006
This little code effort came out of one of the forum questions. The function calendar.prmonth(2006, 3) prints a neat little monthly calendar, can the output be assigned to a string for other uses? Here is one way to do this ...
  1. # pipe the output of calendar.prmonth() to a string
  2.  
  3. import subprocess
  4.  
  5. code_str = \
  6. """
  7. import calendar
  8. calendar.prmonth(2006, 3)
  9. """
  10.  
  11. # save the code
  12. filename = "mar2006.py"
  13. fout = open(filename, "w")
  14. fout.write(code_str)
  15. fout.close()
  16.  
  17. # execute the code and pipe the result to a string
  18. test = "python " + filename
  19. process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE)
  20. process.wait()
  21. print process.returncode # 0 = success, optional check
  22. # read the result to a string
  23. month_str = process.stdout.read()
  24.  
  25. print month_str

There are simpler methods, but this is a good example of the os.popen() function, or the more updated subprocess.Popen().

Just remember to stick with a proportional font like Courier to line things up correctly.
Last edited by vegaseat; May 15th, 2007 at 7:05 pm. Reason: replaced old php tags (don't work any more)
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,069
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: 938
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #53
Mar 18th, 2006
You can create a list by concatination and multiplication. The example below shows you a practical approach ...
  1. # in English you print first as 1st, second as 2nd and so on
  2. # create a list of suffixes for the days of the month (1 to 31)
  3. # rather than typing 17 'th' for numbers 4 to 20 you can use 17*['th']
  4.  
  5. day_suffix = ['st', 'nd', 'rd'] + 17*['th'] + ['st', 'nd', 'rd'] + 7*['th'] + ['st']
  6. print day_suffix
  7. """
  8. result =
  9. ['st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th',
  10. 'th', 'th', 'th', 'th', 'th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st']
  11. """
  12.  
  13. # now test it
  14. for x in range(1, 32):
  15. print "%d%s" % (x, day_suffix[x-1])
  16.  
  17. """
  18. result =
  19. 1st
  20. 2nd
  21. 3rd
  22. 4th
  23. 5th
  24. ...
  25. 30th
  26. 31st
  27. """
Last edited by vegaseat; May 15th, 2007 at 7:07 pm. Reason: replace nonfunctioning php tags
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,069
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: 938
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #54
May 4th, 2006
So you want to add an image to your Tkinter GUI program, here is an example ...
  1. from Tkinter import *
  2.  
  3. root = Tk()
  4.  
  5. # reads only GIF and PGM/PPM images
  6. # for additional formats use Image, ImageTk from PIL
  7. # pick a GIF file you have in your working directory
  8. imagefile = "Flowers.gif"
  9. photo1 = PhotoImage(file=imagefile)
  10.  
  11. width1 = photo1.width()
  12. height1 = photo1.height()
  13. canvas1 = Canvas(width=width1, height=height1)
  14. canvas1.create_image(width1/2.0, height1/2.0, image=photo1)
  15. canvas1.pack()
  16. root.mainloop()
Last edited by vegaseat; May 15th, 2007 at 7:08 pm. Reason: php
May 'the Google' be with you!
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
  #55
May 21st, 2006
You can use a global variable within a function by prefixing it with the word "global". Here is an example:
  1. # keep track of how many times a function has been accessed
  2. # using a global variable, somewhat frowned upon
  3. def counter1():
  4. global count
  5. # your regular code here
  6. count += 1
  7. return count
  8.  
  9. # test it
  10. count = 0 # a global variable
  11. print counter1() # 1
  12. print counter1() # 2
  13. print count # 2 variable count has changed
  14. print
The trouble with a global variable is with using it somewhere else in a large program. Everytime you call this function its value will change and may lead to buggy code.

One solution is to use the namespace of the function, making the variable more unique. It gives you a hint where it is used, for example:
  1. # avoid the global variable and use the function namespace
  2. def counter2():
  3. # your regular code here
  4. counter2.count += 1
  5. return counter2.count
  6.  
  7. # test it
  8. counter2.count = 0 # now count has counter2 namespace, notice the period
  9. print counter2() # 1
  10. print counter2() # 2
  11. print
drink her pretty
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
  #56
May 31st, 2006
Ever wrote a Python program and wanted to use passwords? What good is password, if the user can simply look at your code and see it?

The module md5 comes to the rescue! It converts the password string to string containing series of hexadecimal numbers. You do that in program1, then copy and paste this hex string into your program (program2).

Here is program1 (keep that to yourself in save place):
  1. # program 1, code to generate a hashed password
  2. # the result is a series of hexadecimal numbers
  3. # it is saved to one text file, so you can
  4. # copy and paste it to program2 from any editor
  5.  
  6. import md5
  7.  
  8. # pick a password you can remember
  9. password = "gummy"
  10. pw_hashed = md5.md5(password).hexdigest()
  11. print pw_hashed # just testing
  12. fout = open("MyHashedPassword.txt", "w")
  13. fout.write(pw_hashed)
  14. fout.close()
This is program2, showing only hex string hashed password, but user has to enter password 'gummy' for md5 to match:
  1. # program2, copy hashed password from program1 and assign
  2. # it to MYPASSWORDHASH as string, this is all user would see,
  3. # if looking at your code
  4.  
  5. import md5
  6.  
  7. MYPASSWORDHASH = "c1944508a0d871c55b501624c36e0f68"
  8. def get_password():
  9. # give it three tries
  10. for i in range(3):
  11. password = md5.md5(raw_input("Enter your password: "))
  12. password = password.hexdigest()
  13. if password == MYPASSWORDHASH:
  14. return True
  15. return False
  16.  
  17. def main():
  18. if get_password():
  19. print "Success"
  20. # do something here with rest of the program code
  21. else:
  22. print "Failure"
  23. # do something else here
  24.  
  25. if __name__ == "__main__":
  26. main()
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
  #57
Jun 1st, 2006
Python allows you to combine a number of statements into one-liner:
  1. str1 = "we willing women want warm winter woollies"
  2.  
  3. list1 = str1.split()
  4. print list1 # ['we', 'willing', 'women', 'want', 'warm', 'winter', 'woollies']
  5.  
  6. list2 = [frag[:2] for frag in list1]
  7. print list2 # ['we', 'wi', 'wo', 'wa', 'wa', 'wi', 'wo']
  8.  
  9. str2 = "".join(list2)
  10. print str2 # wewiwowawawiwo
  11.  
  12. # combine all three statements
  13. print "".join([frag[:2] for frag in str1.split()])
Here you have it, but watch out it becomes hard to read and understand at times. Me thinks, me just invented a new word "wewiwowawawiwo". Has nifty ring to it!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,069
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: 938
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #58
Jun 10th, 2006
An example how to run a number of different games or utilities from a menu. The menu is within an infinite while loop with a quit option to break out of the loop. The games or utilities are implemented with a function call ...
  1. import random
  2. import time
  3. import calendar
  4.  
  5. def guess_number():
  6. # random integer 1 to 99
  7. n = random.randint(1, 99)
  8. #print n # test
  9.  
  10. while True:
  11. print
  12. guess = int(raw_input("Enter an integer from 1 to 99: "))
  13. if guess < n:
  14. print "guess is low"
  15. elif guess > n:
  16. print "guess is high"
  17. else:
  18. print "you guessed it!"
  19. print
  20. break
  21.  
  22. def calendar_now():
  23. """show the calendar for the present month"""
  24. year_month = time.localtime()[:2]
  25. print
  26. calendar.prmonth(year_month[0], year_month[1])
  27. print
  28.  
  29. while True:
  30. print "-" * 30
  31. print " Menu"
  32. print "to guess a number enter n"
  33. print "for a monthly calendar enter m"
  34. # more ...
  35. print "to quit enter q"
  36. print "-" * 30
  37. # also convert any upper case choice to lower case
  38. choice = raw_input("enter your choice: ").lower()
  39. if choice == 'n':
  40. guess_number()
  41. elif choice == 'm':
  42. calendar_now()
  43. # more elif here ...
  44. elif choice == 'q':
  45. print
  46. print "thanks for using my program!"
  47. break
  48. else:
  49. print "enter the correct choice!"
  50. print
Last edited by vegaseat; May 15th, 2007 at 7:46 pm. Reason: php
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,069
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: 938
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #59
Jun 11th, 2006
Someone should write a palindrome program for every computer language there is. Python knows how to handle strings and makes it relatively easy ...
  1. # check if a phrase is a palindrome
  2.  
  3. def isPalindrome(phrase):
  4. """
  5. take a phrase and convert to all lowercase letters
  6. if it matches the reverse spelling then it is a palindrome
  7. """
  8. phrase_letters = [c for c in phrase.lower() if c.isalpha()]
  9. print phrase_letters # test
  10. return (phrase_letters == phrase_letters[::-1])
  11.  
  12.  
  13. #phrase = "A man, a plan, a canal, Panama!"
  14. phrase = "Madam in Eden I'm Adam"
  15. if isPalindrome(phrase):
  16. print '"%s" is a palindrome' % phrase
  17. else:
  18. print '"%s" is not a palindrome' % phrase
Last edited by vegaseat; May 15th, 2007 at 7:47 pm. Reason: php tags changed
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
  #60
Jun 13th, 2006
You can use Python program to extract picture from web page and save it. I have tested this with Windows XP, might work with other OS:
  1. # load given picture from web page and save it
  2. # (you have to be on the internet to do this)
  3.  
  4. import urllib2
  5. import webbrowser
  6. import os
  7.  
  8. # find yourself a picture on a web page you like
  9. # (right click on the picture, look under properties and copy the address)
  10. picture_page = "http://www.google.com/intl/en/images/logo.gif"
  11.  
  12. #webbrowser.open(picture_page) # test
  13.  
  14. # open the web page picture and read it into variable
  15. opener1 = urllib2.build_opener()
  16. page1 = opener1.open(picture_page)
  17. my_picture = page1.read()
  18.  
  19. # open file for binary write and save picture
  20. # picture_page[-4:] extracts extension eg. .gif
  21. # (most image file extensions have three letters, otherwise modify)
  22. filename = "my_image" + picture_page[-4:]
  23. print filename # test
  24. fout = open(filename, "wb")
  25. fout.write(my_picture)
  26. fout.close()
  27.  
  28. # was it saved correctly?
  29. # test it out ...
  30. webbrowser.open(filename)
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