Escolar Documentos
Profissional Documentos
Cultura Documentos
http://www.daniweb.com/software-development/python/threads/20774
Software Development
Web Development
Internet Marketing
Business Exchange
Community Center
Unsolved
Views: 126946
Like
Tweet
Page 1
11
Next
Last
Permalink
Starting Python
vegaseat
DaniWeb's Hypocrite Offline 5,754 posts since Oct 2004
11
Expand Post
The idea of this thread is to help the beginning Python programmer with hints and helpful code. Please feel free to contribute! If you have any questions start your own thread!
The creators of Python are very active, improving the language all the time. Here is a little of the version history: Python24 March 2005 Python25 Sept 2006 Python26 Sept 2008 Python27 July 2010 (final version of the Python2 series) Python31 July2009 Python32 February 2011 You can download the version you like free from: www.python.org Selfextracting MS Installer files have a .msi extension and contain the version number, for instance python-3.1.msi. Editors note: Similar Threads
CGPA calculator in Python Beginning: Starting Python in Python Clear the console screen in Python Re: Starting Python in Python
Quote ...
Python3 versions are not totally campatible with Python2 versions. A few clumsy things have been removed to modernize the language. One obvious one is the print statement, which is now a print() function. See: http://www.daniweb.com/forums/showpo...&postcount=154 The good news is that it contains a conversion program 2to3.py that will convert your present Python2 code to Python3 code. You can find an excellent discussion of Python2 to Python3 changes here: http://diveintopython3.org/porting-code ... -2to3.html
Linux users can install Python installers from: http://www.activestate.com/activepython/python3/ For the folks who like to do the unusual, Python is equally at home on the Apple computers. It is my understanding that Linux and Apple OS X have Python already installed. Apple users should check http://undefined.org/python/ I installed my Python on the D: drive, so I ended up with a D:\Python31 folder after the installation. The first step is to create a
1 of 16
12/14/2011 2:14 AM
http://www.daniweb.com/software-development/python/threads/20774
subfolder (subdirectory) for all your test programs, like D:\Python31 \Atest31. There is a Python editor included with the Python installation. The program is called IDLE, a small, but capable Integrated Development Environment (IDE), that you can use to write, edit, run and debug your code from. The problem is that it is hidden in subfolders. I found it in D:\Python31\Lib\idlelib\idle.pyw The .py or .pyw extension is used for Python code files. With Windows, all you need to do is to double click on idle.pyw and after a fraction of a second the compiled program appears on your screen. If your version of IDLE starts up in the Shell Window, the one with the >>> prompts, go to 'Options' on the top line and then click on 'Configure IDLE'. In the configure menu go to the 'General' page and set the 'Open Edit Window' at startup option, then click on 'Apply'. I think that coding in the interactive shell, also called the command line option, is limited to one liners, simple calculations and calls for help. Anything else is just major confusion, and has turned off a lot of fine folks from using Python! Lamentably, much of the Python docs are littered with command line examples with its many >>> prompts and ... line indent markers. Do not use those >>> prompts and markers in your code editor. Once you are in the Edit Window with its simple flashing cursor, type in your first Python program (no, the line number is not part of the code). Press (Toggle Plain Text), if you want to copy and paste into your editor.
On the top menu bar click on File and save the short program in the Atest folder as HelloMP1.py now press the F5 key (or click on Run then on Run Module). The Python interactive Shell appears telling what version of Python you are running, and wedged between >>> prompts is Hello Monty Python! Not much, but it worked, your first Python program. After you admired this for a while, press the Alt and F4 keys at the same time (or File then Close) to leave the Shell and get back to the Editor. Let's create a second version of the simple program. Replace 'print' with 'str1 =' and add a few more lines ...
2 of 16
12/14/2011 2:14 AM
http://www.daniweb.com/software-development/python/threads/20774
If you want to, you can save this under a different filename, then press F5. The result looks the same, but we introduced a string variable and the fact that Python does not require us to declare the type. Oh gee! My C brain is going nuts! One more change for the fun of it ...
Notice, as you type 'str1.replace(' a hint line pops up showing you what can be entered between the function's parentheses, a cool thing. When you are done typing the code, press F5 and enjoy your labor. I leave it to you to dream up better stuff! Also notice, that in all of this the original string str1 has not changed. Want more? When you are in the IDLE editor simply press the F1 key and a copy of the Python documentation comes up. There you can click on Tutorial and now you have a ton of sample code to play with. Just cut and paste and experiment. If you are in the Python interactive Shell, the one with the >>> prompt, you can just type help('string') to get a list of string functions and constants. A little cryptic at first, but still useful. In the Shell you can also do calculator stuff and get the result. For instance type 12345679 * 63 then press enter. By the way, you can also get into a somewhat uglier looking Shell when you simply run Python.exe from the Python31 folder. For convenience sake make a shortcut of idle.pyw and drag it onto your desktop. Just a note, I said earlier that with Python you don't have to declare the type of a variable. That is not totally true, you have to give Python an idea what it is. By inference Python figures out that if you type z = 77 then z is the reference to an integer object. Conversely z = "Hello" would be a string, z = 7.12 is a floating point number, and z = [] is a list (in this case an empty list ready to be populated).
There are a fair number of free third party modules (some of them still limited to Python2 versions), for instance ... The wxPython GUI toolkit is available at: http://www.wxpython.org/download.php The PyQT GUI toolkit is available for Python 3.1 already: http://www.riverbankcomputing.com
3 of 16
12/14/2011 2:14 AM
http://www.daniweb.com/software-development/python/threads/20774
The Python Image Library (PIL) is at: http://www.pythonware.com/products/pil/index.htm The PyGame module for game programming is at: http://www.pygame.org Also look at this site for other Python third party modules: http://www.lfd.uci.edu/~gohlke/pythonlibs/ Has the rare PIL versions for Python27 and Python31 A detailed and interesting essay about Python's creation and architecture: http://stride-online.com/filestorage/Python.pdf Another good introduction into the design philosophy of Python: http://en.wikipedia.org/wiki/Python_...mming_language Google offers a great Starting Python Class online: http://code.google.com/edu/languages...-python-class/ Nice humor ... http://xkcd.com/353/ A Foolish Consistency is the Hobgoblin of Little Minds ... for recommended Python code writing style see: http://www.python.org/dev/peps/pep-0008/ Editor's note: I have started to update some of the posts to reflect changes in Python3. Also changed some of the code to make it work with Python2 and Python3 versions. This is work in progress, tough for my old tired eyes. You will see the somewhat odd print( text ) rather than the recommended print(text), just a visual aid for me that I changed this from Python2. Remember in Python readability rules!
Last edited by vegaseat; Apr 10th, 2011 at 10:02 am. Reason: Python3 updates
Permalink
Again, please do not clutter this thread with questions and homework problems! The idea of this thread is to help the beginning Python programmer with hints and helpful code. Please feel free to contribute! If you have any questions start your own thread!
Permalink
For beginners in Python, this shows you how to define a function. Notice the format (parameters are often called arguments):
4 of 16
12/14/2011 2:14 AM
http://www.daniweb.com/software-development/python/threads/20774
The statement lines that are part of the function have to be indented, since Python does not have a begin/end or {} pair for such things. The size of the indentation is a matter of preference. To me 2 spaces are more readable, the more or less official standard is 4 spaces. One word of advice, don't mix spaces and tabs for indentations! I avoid tabs. In general, if a statement line ends with a colon (like a function define, a class, a for or while loop, or an if, elif, else), you have to indent the statement block that belongs to this line. You must define a function before you call it. It is good practice to comment the function. It is also good practice to prefix a function with an action verb like format, get, convert, set etc. Here is an example of a number of functions receiving and passing arguments and working together in the classical data in, data process and data out fashion ....
7. def show_name(name): 8. """this function only receives an argument""" 9. 10. print( name )
11. def process_name(first, last): 12. """this function reveives 2 arguments, returns 1 argument""" name = "Mr. " + first +" " + last 13. 14. 15. return name
16. def main(): 17. """ 18. this function handles the other functions in order 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. and deals with the arguments received and to be passed """ first, last = get_name() name = process_name(first, last) show_name(name) # start the program with this function call main() """my output --> Mr. Fred Ferkel """
The Python interpreter compiles all the defined functions to byte code, but does not use them until called. To avoid any problems, follow the simple rule of defining all functions in the beginning of your program ...
5 of 16
12/14/2011 2:14 AM
http://www.daniweb.com/software-development/python/threads/20774
13. # all function have been defined 14. # this will work fine 15. f1()
4. f2() 5. 6. # oops, premature call, this will give 7. # NameError: global name 'f2' is not defined 8. f1() 9. 10. def f2(): 11. 12. 13. 15. print('f2') f3()
There is another use for the triple quoted comment or documentation string. You can access it like this ...
6 of 16
12/14/2011 2:14 AM
http://www.daniweb.com/software-development/python/threads/20774
2. 3. def getDistance(x1, y1, x2, y2): 4. """ 5. 6. 7. 8. 9. 10. 11. 12. getDistance(x1, y1, x2, y2) returns distance between two points using the pythagorean theorem the function parameters are the coordinates of the two points """ dx = x2 - x1 dy = y2 - y1 return math.sqrt(dx**2 + dy**2)
13. print( "Distance between point(1,3) and point(4,7) is", getDistance(1,3,4,7) ) 14. print( "Distance between point(1,3) and point(11,19) is", getDistance(1,3,11,19) ) 15. 16. print( '-'*50 ) # print 50 dashes, cosmetic 17. print( "The function's documentation string:" ) 18. # shows comment between the triple quotes 19. print( getDistance.__doc__ )
Actually, if your documentation string is just a one-liner, you could enclose it in just single quotes on the same line. If you don't like the indentation to show up in the documentation string, Python relaxes the indentation rules within a multiline string, so you can use use something like this:
Just a note on function or variable names, avoid using Python language keywords or Python's builtin function names. For a list of Python's builtin functions (also called methods) you can use this little code:
10. print( "-"*70 ) 11. 12. # or each function on a line joining the list to a string 13. print( '\n'.join(builtin_fuction_list) ) 14. 15. print( "-"*70 ) 16. 17. # or, a little more advanced, combine it all and do a case insensitive sort too 18. print( '\n'.join(sorted(dir(__builtins__), key = str.lower)) )
Sorry, couldn't resist showing off the different ways to present the data.
7 of 16
12/14/2011 2:14 AM
http://www.daniweb.com/software-development/python/threads/20774
One more note, don't use names of variables you are using in your program for function names. They will compete within the Python interpreter internal dictionary and may lead to errors! Since the correct indentations are so critical in Python code, it is best to use an editor written for Python. Those editors will auto-indent properly, warn you of mixed tab/space indentations and do some other hand holding. I have experimented with IDLE, PythonWin, DrPython, pyPE, and BOA constructor. They all have certain features I like. If you fiddle, I mean experiment with the code a lot, DrPython or PyPE comes in the handiest. BOA constructor makes GUI programming with wxPython much easier! For a listing of Integrated Development Environment (IDE) programs for Python see: http://wiki.python.org/moin/PythonEditors Also not strictly an IDE, this is a very nice editor (written in Python/wxPython) with great features (multiple windows, syntax highlighting, find/replace, line numbers, autocomplete, macros, fold/expand functions and classes, bookmarks, todo, Python Shell, run your code, hotkeys, spellcheck and much more). Simply extract the zip file into your Python folder. Execute the program by running 'pype.pyw'. You can run your code with 'Run current file' and it will display in a nice output window (similar to the IDLE shell) (written for Windows, but also tested on Linux, latest version PyPE-2.8-src.zip 12/14/2006) http://pype.sourceforge.net/index.shtml Another very nice IDE for Python is PyScripter (still beta). This one is written with Delphi and is a standalone executable file. You can download the free setup file (for Windows only) from: http://mmm-experts.com/Downloads.aspx?ProductId=4 This free IDE is more general, but has a truckload full of real nice programmer's features: http://www.pspad.com/en/ Boa Constructor is an IDE with a visual frame builder/designer built in (like Delphi). It is still alive and kicking, and the latest version is nicely improved. Download the Windows version for free from: http://sourceforge.net/project/downl...p.exe&74856058 Boa uses wxPython and works with Python2.5 or 2.6 and wxPython2.8 on Windows XP and Vista.
Last edited by vegaseat; Apr 16th, 2011 at 1:56 pm. Reason: IDEs, Python3 update
Permalink
8 of 16
12/14/2011 2:14 AM
http://www.daniweb.com/software-development/python/threads/20774
... you can save it for instance as 'reverse.py' to a folder. If Python is installed on a Windows computer, you can simply double-click on the filename and run the program. The extension .py is usually associated with the Python interpreter. Since this is a console program, you will run into the old troublemaker of the console output, the program runs but closes quickly. You have to add a line of code at the end of the program to make the console wait for some key input.
8. print( "reverse = ", str1[::-1] ) 9. 10. # optional wait for keypress 11. raw_input('Press Enter...') 12. # with Python3 'raw_input()' has become 'input()'
This is not needed, if you run from an IDE that has its own output window. BTW, if you are lost with the slicing thing str1[::-1] just fill in the defaults and it gets clearer str1[0 : len(str1) : -1] . Just a few more slicing examples ...
8. print( "exclude first 3 char 9. print( "exclude last 4 char 10. print( "reverse the string 11. print( "the whole word again 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. print( "spell skipping 2 """ my output --> first 2 char = hi next 2 char = pp last 2 char = us exclude first 3 char = exclude last 4 char = reverse the string = the whole word again = spell skipping 2 char = """
You can apply slicing to any indexed sequence, here is a list example ...
9 of 16
12/14/2011 2:14 AM
http://www.daniweb.com/software-development/python/threads/20774
1. 2. 3. 4. 5.
# # # # #
exploring Python's slicing operator can be used with any indexed sequence like strings, lists, ... syntax --> seq[begin : end : step] step is optional defaults are index begin=0, index end=len(seq)-1, step=1
6. # -begin or -end --> count from the end backwards 7. # step = -1 reverses sequence 8. # if you feel lost, put in the defaults in your mind 9. 10. # use a list as a test sequence 11. a = [0, 1, 2, 3, 4, 5, 6, 7, 8] 12. 13. print( a[3:6] ) 15. print( a[:3] ) # [3,4,5] # [0,1,2] 14. # if either index is omitted, beginning or end of sequence is assumed 16. print( a[5:] ) # [5,6,7,8] 17. 18. # negative index is taken from the end of the sequence 19. print( a[2:-2] ) 20. print( a[-4:] ) 21. # [2,3,4,5,6] # [5,6,7,8]
22. # extract every second element 23. print( a[::2] ) # [0, 2, 4, 6, 8] 24. 25. # step=-1 will reverse the sequence 26. print( a[::-1] ) # [8, 7, 6, 5, 4, 3, 2, 1, 0] 27. 28. # no indices just makes a copy (which is sometimes useful) 29. b = a[:] 30. print( b ) # [0, 1, 2, 3, 4, 5, 6, 7, 8] 31. 32. # slice in (replace) an element at index 3 33. b[3:4] = [100] 34. print( b ) # [0, 1, 2, 100, 4, 5, 6, 7, 8] 35. # make another copy, since b has changed 36. b = a[:] 37. 38. # slice in (insert) a few elements starting at index 3 39. b[3:] = [9, 9, 9, 9] + b[3:] 40. print( a ) 41. print( b ) # [0, 1, 2, 3, 4, 5, 6, 7, 8] # [0, 1, 2, 9, 9, 9, 9, 3, 4, 5, 6, 7, 8]
Last edited by vegaseat; Nov 5th, 2009 at 3:05 pm. Reason: slicing examples
Permalink
Python has a very helpful feature called help(). Here is a sample ...
10 of 16
12/14/2011 2:14 AM
http://www.daniweb.com/software-development/python/threads/20774
12. 13. # file stuff ... 14. help("file") 15. 16. # down to method/function level ... 17. help("os.read")
That means you can use help in the program code, or at the interactive page >>> prompt. Not many other languages offer this handiness! To copy the help result into a help file see: http://www.daniweb.com/forums/post13...ml#post1306519 If you want other people to read and help with your code, you might want to follow the Python style guide, written by GVR himself: http://www.python.org/peps/pep-0008.html
Last edited by vegaseat; Aug 15th, 2010 at 3:39 pm. Reason: code tags updated
Permalink
One more helpful hint to get this thing off to a hopefully good start. How do we read a simple text file in Python? Also, what can we do with the data after we read it?
Want more help about split()? At the interactive page >>> prompt enter help("string.split")
Last edited by vegaseat; Aug 16th, 2009 at 10:14 pm. Reason: [code=python], Python3 update
Permalink
One more function sample to show you that a function can decide internally what type of number to return. Also shows an example of try/except exception handling.
11 of 16
12/14/2011 2:14 AM
http://www.daniweb.com/software-development/python/threads/20774
1. # a function to return the numeric content of a cost item 2. # for instance $12.99 or -$123456789.01 (deficit spenders) 3. def getVal(txt): 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. if txt[0] == "$": txt = txt[1:] if txt[1] == "$": # could be -$xxx txt = txt[0] + txt[2:] while txt: try: f = float(txt) i = int(f) if f == i: return i return f except TypeError: txt = txt[:-1] return 0 # removes possible trailing stuff # select float or integer return # remove leading dollar sign
Click on "Toggle Plain Text" so you can highlight and copy the code to your editor without the line numbers.
Last edited by vegaseat; Aug 16th, 2009 at 10:15 pm. Reason: [code=python] tag
Permalink
The IDLE integrated development environment that comes with the normal Python installation is really a GUI program. It uses Tkinter as the GUI toolkit which is part of the normal Python installation. Tkinter uses tcl script language to do the work. Here is a typical Python code example using Tkinter ...
This code should run on Windows and Unix (PC or Mac). On a Windows machine save the program with a .pyw extension. This way it associates with pythonw.exe and avoids the ugly black DOS display popping up. You can also find much Tkinter detail at:
12 of 16
12/14/2011 2:14 AM
http://www.daniweb.com/software-development/python/threads/20774
http://infohost.nmt.edu/tcc/help/pub...ter/index.html There is another GUI library worth mentioning, it's wxPython based on C++. The code is more efficient for GUI stuff. The download of the installer is free, look at http://wiki.wxpython.org/ You can get wxPython for either Windows, Linux or Unix. You can find quite a few wxPython GUI code examples in the DaniWeb Python Code Snippets and in the Starting wxPython sticky. Here is a very nice wxPython tutorial I like to recommend, it will give you a good overview: http://wiki.wxpython.org/index.cgi/AnotherTutorial Note: GUI stands for Graphical User Interface. It's the usual Window matter like frames, buttons, labels, editboxes.
Last edited by vegaseat; Jan 24th, 2010 at 8:02 am. Reason: [code=python] tag
Permalink
To get string input from the user you can use the raw_input() function with Python2 and the input() function with Python3. . Here is an example of an input loop that checks the data you enter. The function get_list(prompt) is generic and can be used whenever you want to enter a series of numbers (accepts integer or float). It returns a list of the entered numbers. It's up to you to process the list of numbers ...
Since Python2's raw_input() will not work with Python3, you can use try/except to make your program work with both versions ...
13 of 16
12/14/2011 2:14 AM
http://www.daniweb.com/software-development/python/threads/20774
2. # modified to work with Python2 and Python3 3. 4. import datetime as dt 5. 6. prompt = "Enter your birthday (format = mm/dd/yyyy): " 7. try: 8. # Python2 9. 11. bd = raw_input(prompt) # Python3 10. except NameError: 12. bd = input(prompt) 13. 14. # split the bd string into month, day, year 15. month, day, year = bd.split("/") 16. 17. # convert to format datetime.date(year, month, day)) 18. birthday = dt.date(int(year), int(month), int(day)) 19. 20. # get todays date 21. today = dt.date.today() 22. 23. # calculate age since birth 24. age = (today - birthday) 25. 26. print( "You are %d days old!" % age.days )
Click on "Toggle Plain Text" so you can highlight and copy the code to your editor. A note on importing modules: Python is a modular language and comes with many thoroughly tested and optimized modules. To code in Python means you have to use those modules to your advantage. Python syntax may be easy, but remembering all those modules may use all the power of your brain!
Last edited by vegaseat; Dec 22nd, 2009 at 9:55 am. Reason: code=python tag remark, Python3 update
Permalink
I need to write a function that can return more than one item. This is a simple example how to do it ...
14 of 16
12/14/2011 2:14 AM
http://www.daniweb.com/software-development/python/threads/20774
This example has not only a multiple argument return, but also allows you to call it with multiple arguments of flexible size/number ...
10. 11. # notice that the first element is the args tuple we send to the function 12. print( sum_average(2, 5, 6, 7) ) # ((2, 5, 6, 7), 20, 5.0) 13. 14. # or unpack into a tuple of appropriate variables 15. args_tuple, sum2, average = sum_average(2, 5, 6, 7) 16. 17. print( "sum of %s = %d" % (args_tuple, sum2) ) 18. # sum of (2, 5, 6, 7) = 20
19. print( "average of %s = %0.2f" % (args_tuple, average) ) # average of (2, 5, 6, 7) = 5.00 20. 21. # or just pick one return value, here value at index 1 = the sum 22. print( "sum =", sum_average(2, 5, 6, 7)[1] ) # sum = 20
Click on "Toggle Plain Text" so you can highlight and copy the code to your editor.
Last edited by vegaseat; Aug 16th, 2009 at 10:31 pm. Reason: [code=python] tag
Page 1
11
Next
Last
Message:
1
Tweet
2
Like
Previous Thread in Python Forum Timeline: Next Thread in Python Forum Timeline:
Tags
code , hints , python , tricks , tutorial
code
coding color count crypto csv database dictionary django error event excel
expression file for-loop fruitcake function functions game generator global graphic gui help! html idle image import input install int integer interpreter java javascript jython key line list
15 of 16
12/14/2011 2:14 AM
http://www.daniweb.com/software-development/python/threads/20774
lists loop module multiple noob password php program programing programming py2exe pygame pypy
python
question regular replace scanner shedskin simple slice socket software sort source speed string syntax system text timer tkinter tutorial update variable vb vb.net web website
Follow us on
16 of 16
12/14/2011 2:14 AM