Starting Python

Reply

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

Re: Starting Python

 
0
  #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 )
The same procedure applies to other objects like variables, tuples, sets, dictionaries and so on.
Last edited by vegaseat; Aug 16th, 2009 at 10:33 pm. Reason: [code=python] tag, Python3 update
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,947
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: 914
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #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. # Python3 uses input() instead of raw_input()
  8. year = int(raw_input("Enter the year (eg. 2005): "))
  9. print('')
  10. calendar.prcal(year)
  11. print('')
  12. raw_input("Press Enter to go on ...") # wait
  13. # with Pytho3 use ...
  14. #input("Press Enter to go on ...") # wait
Note, print('') prints an empty line in Python2 and Python3.
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; Aug 16th, 2009 at 10:37 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,947
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: 914
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #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; Aug 16th, 2009 at 10:39 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,947
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: 914
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #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; Aug 16th, 2009 at 10:41 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,947
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: 914
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #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. # tested with Python 2.5.4
  4.  
  5. import urllib2
  6.  
  7. urlStr = 'http://www.python.org/'
  8. try:
  9. fileHandle = urllib2.urlopen(urlStr)
  10. str1 = fileHandle.read()
  11. fileHandle.close()
  12. print '-'*50
  13. print 'HTML code of URL =', urlStr
  14. print '-'*50
  15. except IOError:
  16. print 'Cannot open URL %s for reading' % urlStr
  17. str1 = 'error!'
  18.  
  19. print str1
Notice that we have added the try/except exception handling to this code.

Note: Python3 uses urllib.request.urlopen() instead of urllib2.urlopen()
If you use Python3, try this code ...
  1. # get html code of given URL
  2. # Python3 uses urllib.request.urlopen()
  3. # instead of Python2's urllib.urlopen() or urllib2.urlopen()
  4. # also urllib is a package in Python3
  5. # tested with Python 3.1
  6.  
  7. import urllib.request
  8.  
  9. fp = urllib.request.urlopen("http://www.python.org")
  10. # Python3 does not read the html code as string
  11. # but as html code bytearray
  12. mybytes = fp.read()
  13. fp.close()
  14.  
  15. # try utf8 to decode the bytearray to a string
  16. mystr = mybytes.decode("utf8")
  17. print(mystr)
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. # tested with Python 2.5.4
  3.  
  4. import os
  5.  
  6. def isSSL():
  7. """ return true if there is a SSL (https) connection """
  8. if (os.environ.get('SSL_PROTOCOL', '') != ''):
  9. return true
  10. else:
  11. return false
  12.  
  13. if isSSL:
  14. print( "We have a SSL connection" )
  15. else:
  16. print( "No SSL connection" )
Click on "Toggle Plain Text" so you can highlight and copy the code to your editor.
Last edited by vegaseat; Aug 29th, 2009 at 5:28 pm. Reason: [code=python] tag, Python3 note
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,947
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: 914
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #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 later
  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; Aug 16th, 2009 at 10:52 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,947
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: 914
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #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; Aug 16th, 2009 at 10:53 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,947
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: 914
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #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. # tested with Python 2.5.4
  3.  
  4. import random
  5.  
  6. # create a sequence, here a tuple, of words to choose from
  7. WORDS = ("python", "jumble", "easy", "difficult", "answer", "babysitter")
  8.  
  9. # pick one word randomly from the sequence
  10. word = random.choice(WORDS)
  11.  
  12. # create a variable to use later to see if the guess is correct
  13. correct = word
  14.  
  15. # create a jumbled version of the word
  16. # start with an empty string to be built up in the while loop
  17. jumble = ""
  18. # word is reduced in size by one character each time through the loop
  19. # when it is empty it will be equal to None(False) and the loop stops
  20. while word:
  21. print( word, ' ', jumble ) # for test only
  22. position = random.randrange(len(word))
  23. jumble += word[position]
  24. word = word[:position] + word[(position + 1):]
  25.  
  26.  
  27. 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; Aug 29th, 2009 at 5:31 pm. Reason: [code=python] tag, Python3 ready
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,947
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: 914
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #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; Aug 29th, 2009 at 5:32 pm. Reason: [code=python] tag. Python3 ready
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,947
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: 914
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #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 6:44 pm.
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Reply

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