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 401,449 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 2,889 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.
Views: 52315 | Replies: 144
Reply
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,425
Reputation: vegaseat will become famous soon enough vegaseat will become famous soon enough 
Rep Power: 9
Solved Threads: 173
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #11  
May 10th, 2005
The Python module pickle allows you to save objects to file as a byte stream that contains the object information. When you load the file back the object is intact. Here is a little code example ...
  1. import pickle
  2.  
  3. myList1 = [1, 2, 03, 04, 3.14, "Monte"]
  4. print "Original list:"
  5. print myList1
  6.  
  7. # save the list object to file
  8. file = open("list1.dat", "w")
  9. pickle.dump(myList1, file)
  10. file.close()
  11.  
  12. # load the file back into a list
  13. file = open("list1.dat", "r")
  14. myList2 = pickle.load(file)
  15. file.close()
  16.  
  17. # show that the list is still intact
  18. print "List after pickle.dump() and pickle.load():"
  19. print myList2
  20.  
The same procedure applies to other objects like variables, tuples, sets, dictionaries and so on.
Last edited by vegaseat : Mar 1st, 2007 at 2:32 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,425
Reputation: vegaseat will become famous soon enough vegaseat will become famous soon enough 
Rep Power: 9
Solved Threads: 173
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #12  
May 10th, 2005
The Python module calendar is another interesting collection of functions (methods). If you ever need to show all 12 monthly calendars for the year, use this code ...
  1. # print out a given year's monthly calendars
  2.  
  3. import calendar
  4.  
  5. calendar.prcal(2005)
If you just want June 2005 use ...
  1. import calendar
  2.  
  3. calendar.prmonth(2005, 6)
  4.  
  5. """
  6. result -->
  7. June 2005
  8. Mo Tu We Th Fr Sa Su
  9. 1 2 3 4 5
  10. 6 7 8 9 10 11 12
  11. 13 14 15 16 17 18 19
  12. 20 21 22 23 24 25 26
  13. 27 28 29 30
  14. """
Just for fun, ask a C++ programmer to do this in two lines of code. Now you know why Python is considered a high level language.

Here is a somewhat more complete program, asking the user for the year ...
  1. # allowing for user input
  2.  
  3. import calendar
  4.  
  5. print "Show a given year's monthly calendars ..."
  6. print
  7. year = int(raw_input("Enter the year (eg. 2005): "))
  8. print
  9. calendar.prcal(year)
  10. print
  11. raw_input("Press Enter to go on ...") # wait
Since I have Dev-C++ on my computer I tricked it into using Python and do the calendar thing.
  1. // needs the Python-2.4.1.DevPak installed into Dev-C++, download from:
  2. // http://prdownloads.sourceforge.net/devpaks/Python-2.4.1.DevPak?download
  3. // create project with File > New > Project... > Scripting > Python
  4.  
  5. #include <iostream>
  6. #include <string>
  7.  
  8. // run the Python interpreter eg. Python24.dll
  9. // this macro saves on typing!
  10. #define PY PyRun_SimpleString(input.c_str())
  11.  
  12. using namespace std;
  13.  
  14. // include the Python library header
  15. extern "C" {
  16. #include <python2.4/Python.h>
  17. }
  18.  
  19.  
  20. int main()
  21. {
  22. // initialize Python
  23. Py_Initialize();
  24.  
  25. // optional - display Python version information
  26. cout << "Python " << Py_GetVersion() << endl << endl << endl;
  27.  
  28. string input;
  29.  
  30. // this module is in Python24\lib as calendar.py
  31. // could include it in the working folder if problem
  32. input = "import calendar"; PY;
  33.  
  34. // print out the year's monthly calendar
  35. input = "calendar.prcal(2005)"; PY;
  36.  
  37. // finish up and close Python
  38. Py_Finalize();
  39.  
  40. cin.get(); // console wait
  41. return 0;
  42. }
Last edited by vegaseat : Mar 1st, 2007 at 2:36 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,425
Reputation: vegaseat will become famous soon enough vegaseat will become famous soon enough 
Rep Power: 9
Solved Threads: 173
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #13  
May 10th, 2005
Since we are on the subject of modules that come with Python, there is the operating system module called simply os. Here is one thing you can use it for ...
  1. # list all the configuration (.ini) files in C:\Windows
  2.  
  3. import os
  4.  
  5. fileList = [] # start with an empty list
  6. for filename in os.listdir("C:/Windows"):
  7. if filename.endswith(".ini"):
  8. fileList.append(filename)
  9.  
  10. # now show the list
  11. for filename in fileList:
  12. print filename
There are lots of things you can do with this module. I guess you just have to type help('os') in the interactive window (the one with the >>> prompt) .

You Mac folks will have to change the folder/directory name and the extension.
Last edited by vegaseat : Mar 1st, 2007 at 2:37 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,425
Reputation: vegaseat will become famous soon enough vegaseat will become famous soon enough 
Rep Power: 9
Solved Threads: 173
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #14  
May 23rd, 2005
We have used the replace() function before. This time we use it in a for loop to create new words. The example also gives us a look at the if conditional statement ...
  1. # make your own words, when Q comes up we want to use Qu
  2. str1 = 'Aark'
  3. print "Replace A in %s with other letters:" % str1
  4. # go from B to Z
  5. for n in range(66, 91):
  6. ch = chr(n)
  7. if ch == 'Q': # special case Q, use Qu
  8. ch = ch + 'u'
  9. print str1.replace('A', ch)
A variation of the above to show off the if/else statement ...
  1. # make your own words, here we have to avoid one
  2. # word to get past the guardians of the nation's morals
  3. str1 = 'Auck'
  4. print "Replace A in %s with other letters:" % str1
  5. # go from B to Z
  6. for n in range(66, 91):
  7. ch = chr(n)
  8. if ch == 'Q': # special case Q, use Qu
  9. ch = ch + 'u'
  10. if ch == 'F': # skip the F word
  11. continue
  12. else:
  13. print str1.replace('A', ch)
These little code samples are fun to experiment with.

A note for the C programmers, Python treats characters as strings. This makes life a lot simpler!
Last edited by vegaseat : Mar 1st, 2007 at 2:38 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,425
Reputation: vegaseat will become famous soon enough vegaseat will become famous soon enough 
Rep Power: 9
Solved Threads: 173
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #15  
Jun 1st, 2005
Instead of reading a file, you can read the HTML code of a web site. Of course, you have to be connected to the internet to do this ...
  1. # if you are on the internet you can access the HTML code of a given web site
  2. # using the urlopen() method/function from the module urllib2
  3.  
  4. import urllib2
  5.  
  6. urlStr = 'http://www.python.org/'
  7. try:
  8. fileHandle = urllib2.urlopen(urlStr)
  9. str1 = fileHandle.read()
  10. fileHandle.close()
  11. print '-'*50
  12. print 'HTML code of URL =', urlStr
  13. print '-'*50
  14. except IOError:
  15. print 'Cannot open URL %s for reading' % urlStr
  16. str1 = 'error!'
  17.  
  18. print str1
Notice that we have added the try/except exception handling to this code.

If you are the curious type and want to know beforehand whether you are connected to the internet, this code might tell you ...
  1. # are we connected to the internet?
  2.  
  3. import os
  4.  
  5. def isSSL():
  6. """ return true if there is a SSL (https) connection """
  7. if (os.environ.get('SSL_PROTOCOL', '') != ''):
  8. return true
  9. else:
  10. return false
  11.  
  12. if isSSL:
  13. print "We have a SSL connection"
  14. else:
  15. print "No SSL connection"
Click on "Toggle Plain Text" so you can highlight and copy the code to your editor.
Last edited by vegaseat : Mar 1st, 2007 at 3:11 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,425
Reputation: vegaseat will become famous soon enough vegaseat will become famous soon enough 
Rep Power: 9
Solved Threads: 173
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #16  
Jun 1st, 2005
Do you want to impress your friends? Of course you do! Try this Python code example using the datetime module ...
  1. # how many days old is this person?
  2.  
  3. from datetime import date
  4.  
  5. # a typical birthday year, month, day
  6. # or change it to your own birthday...
  7. birthday = date(1983, 12, 31)
  8.  
  9. now = date.today()
  10.  
  11. print '-'*30 # 30 dashes
  12. print "Today's date is", now.strftime("%d%b%Y")
  13. print "Your birthday was on", birthday.strftime("%d%b%Y")
  14.  
  15. # calculate your age
  16. age = now - birthday
  17. print "You are", age.days, "days old"
The datetime module is smart enough to catch erroneous dates like date(1983, 12, 32) or date(1983, 2, 29).

Notice the variation of the import statement. Here we are just importing the date method from the datetime module. This saves you from having to code:
now = datetime.date.today()
Might be good for long code where you would have to write this twenty times.

Here is another practical code ...
  1. # calculate days till xmas
  2.  
  3. from datetime import date
  4.  
  5. now = date.today()
  6.  
  7. # you may need to change the year down the road
  8. xmas = date(2005, 12, 25)
  9.  
  10. tillXmas = xmas - now
  11.  
  12. print '-'*30 # 30 dashes
  13. print "There are", tillXmas.days, "shopping days till xmas!"
Calculations like this can lead to a lot of headscratching, Python does it for you without a scratch ...
  1. # add days to a given date
  2.  
  3. from datetime import date, timedelta
  4.  
  5. now = date.today()
  6.  
  7. delta = timedelta(days=77)
  8.  
  9. addDays = now + delta
  10.  
  11. print '-'*30 # 30 dashes
  12. print "Today's date is :", now.strftime("%d%b%Y")
  13. print "77 days from today:", addDays.strftime("%d%b%Y")
Impressed? I am!
Last edited by vegaseat : Mar 1st, 2007 at 2:40 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,425
Reputation: vegaseat will become famous soon enough vegaseat will become famous soon enough 
Rep Power: 9
Solved Threads: 173
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #17  
Jun 4th, 2005
This little fun with numbers program shows how range() and the for loop work together. A little trick I learned in fourth grade applied to Python.
  1. # call it "all the same"
  2.  
  3. num1 = 12345679 # the 8 is left out!
  4.  
  5. # k goes from 9 to <82 in steps of 9
  6. for k in range(9, 82, 9):
  7. print num1 * k
Last edited by vegaseat : Mar 1st, 2007 at 2:41 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,425
Reputation: vegaseat will become famous soon enough vegaseat will become famous soon enough 
Rep Power: 9
Solved Threads: 173
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #18  
Jun 15th, 2005
I took this from a recent thread, to show you how you can use a temporary print statement to figure out what is going on ...
  1. # create a jumbled word/string
  2.  
  3. import random
  4.  
  5. # create a sequence, here a tuple, of words to choose from
  6. WORDS = ("python", "jumble", "easy", "difficult", "answer", "babysitter")
  7.  
  8. # pick one word randomly from the sequence
  9. word = random.choice(WORDS)
  10.  
  11. # create a variable to use later to see if the guess is correct
  12. correct = word
  13.  
  14. # create a jumbled version of the word
  15. # start with an empty string to be built up in the while loop
  16. jumble = ""
  17. # word is reduced in size by one character each time through the loop
  18. # when it is empty it will be equal to None(False) and the loop stops
  19. while word:
  20. print word,' ', jumble # for test only
  21. position = random.randrange(len(word))
  22. jumble += word[position]
  23. word = word[:position] + word[(position + 1):]
  24.  
  25.  
  26. print jumble # now you can ask to guess the word ...
Just a little note, when you save this code, don't save it as random.py. Python will confuse this in the import statement! It will look for the module random.py in the working directory first, before it goes the \Lib directory where the proper module is located.
Last edited by vegaseat : Mar 1st, 2007 at 2:41 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,425
Reputation: vegaseat will become famous soon enough vegaseat will become famous soon enough 
Rep Power: 9
Solved Threads: 173
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #19  
Jun 30th, 2005
Strings are immutable, which means you cannot directly change an existing string, bummer! The following code would give you an error ...
  1. str1 = 'Hello World!'
  2. str1[0] = "J" # gives TypeError: object does not support item assignment
Where there is a will, there is a way around this obstacle ...
  1. str1 = 'Hello World!'
  2. # these statements give the intended result, since they create a new string
  3. # slicing and concatination
  4. str2 = 'J' + str1[1:]
  5. # using replace()
  6. str3 = str1.replace('H', 'J')
  7. # or change the string to a list of characters, do the operation, and join the
  8. # changed list back to a string
  9. charList = list(str1)
  10. charList[0] = 'J'
  11. str4 = "".join(charList)
  12.  
  13. print str1
  14. print str2
  15. print str3
  16. print str4
Along the last thought, lets have some word fun ...
  1. # just a little word fun ...
  2. import random
  3. str1 = "Mississippi"
  4. charList = list(str1)
  5. random.shuffle(charList)
  6. str2 = "".join(charList)
  7. print "\nString '%s' after random shuffle = '%s'" % (str1, str2)
The last code example could be the start of a "guess the word" game.
Last edited by vegaseat : Mar 1st, 2007 at 2:42 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,425
Reputation: vegaseat will become famous soon enough vegaseat will become famous soon enough 
Rep Power: 9
Solved Threads: 173
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #20  
Jul 7th, 2005
Another recent thread was the impetus for this hint.

As you run the Python interpreter on a Python text code file (.py), the file is internally compiled to a .pyc byte code file that speeds up the interpretation process. Most of the time this is transparent to you, as the byte code file for speed sake is created in memory only.

If a Python text code .py file is imported by another Python file, a corresponding .pyc is created on disk to speed up the reuse of that particular file. Using .pyc files speeds things up saving the compilation step.

There is an additional benefit, the compiled files are not readable with a text editor. You can distribute your .pyc file instead of the .py file, this way you can hide your source code a little from folks who like to fiddle with source code.

Let's say you have a file called MyPyFile.py and want to create the compiled file MyPyFile.pyc for higher speed and/or the prevention of unauthorized changes. Write a little one line program like this:
  1. import MyPyFile # converts MyPyFile.py to MyPyFile.pyc
Save it as CompileMyPyFile.py in the same folder as MyPyFile.py and run it. There now should be a MyPyFile.pyc file in that folder. Python.exe runs the source file or the compiled file.

Here is another way to create the compiled file ...
  1. # create a byte code compiled python file
  2.  
  3. import py_compile
  4. py_compile.compile("MyPyFile.py") # creates MyPyFile.pyc

Note: Changed code tags, looks like we lost the php tags!
Last edited by vegaseat : May 15th, 2007 at 5:44 pm.
May 'the Google' be with you!
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 1:08 am.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC