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 375,207 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,294 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.
Please support our Python advertiser:
Views: 49936 | Replies: 140
Reply
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation: vegaseat is on a distinguished road 
Rep Power: 8
Solved Threads: 171
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Starting Python

  #1  
Mar 23rd, 2005
The latest version of Python, as of this date, is Python24. If you have Windows on your computer, then go to website www.python.org and download python-2.4.1c2.msi (or python-2.4.1.msi), this is the selfextracting MS Installer file. The file is 10.7 Meg in size, but includes a lot of goodies.

Editors note: Python25 as of 19sep2006, and latest version as of 22feb2008 is 2.5.2

Of course, there are similar files and goodies for the Linux users! 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:\Python24 folder after the installation. The first step is to create a subfolder (subdirectory) for all your test programs, like D:\Python24\Atest then get the editor going that comes with Python.

It's 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:\Python24\Lib\idlelib\idle.py

The .py extension is used for Python code files. With Windows, all you need to do is to double click on idle.py and after a fraction of a second the compiled program appears on your screen.

If your version of IDLE sarts 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 (many, many ugly >>>).

Once you are in the Edit Window with its simple flashing cursor, type in your first Python program:
  1. print "Hello Monty Python!"
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 ...
  1. str1 = "Hello Monty Python!"
  2. # this is a comment
  3. # notice you don't have to declare the variable type
  4. print str1
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 ...
  1. str1 = "Hello Monty Python!"
  2. # let's replace the M with Spam
  3. str2 = str1.replace('M', 'Spam')
  4. # one more Spam for the P
  5. str3 = str2.replace('P', 'Spam')
  6. # now look at the result
  7. print str1
  8. print str2
  9. print str3
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 Python24 folder.

For convenience sake make a shortcut of idle.py 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).

Editor's Note ...
as of September 19th, 2006, the final production release of Python 2.5 can be downloaded from:
http://www.python.org/download/releases/2.5/

Windows users should download the self installer: python-2.5.msi
Versions for Linux and Mac users are also available on the same site.

Highlights are listed at:
http://www.python.org/download/releases/2.5/highlights/

The updated version of wxPython for GUI programs is already available at:
http://www.wxpython.org/download.php

The Python Image Library (PIL) has been updated to Python25:
http://www.pythonware.com/products/pil/index.htm

For those of you who like 3D graphics check the updates at:
http://vpython.org/
and
http://sourceforge.net/projects/numpy

PyGame has released for Python25, free downlod from:
http://www.pygame.org/ftp/pygame-1.7...in32-py2.5.exe

A detailed and interesting essay about Python's creation and architecture:
http://stride-online.com/filestorage/Python.pdf
Last edited by vegaseat : 18 Hours Ago at 8:17 am. Reason: Python25 updates, Monty corr
May 'the Google' be with you!
AddThis Social Bookmark Button
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation: vegaseat is on a distinguished road 
Rep Power: 8
Solved Threads: 171
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Help Re: Starting Python

  #2  
Mar 23rd, 2005
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!
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation: vegaseat is on a distinguished road 
Rep Power: 8
Solved Threads: 171
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #3  
Mar 23rd, 2005
For beginners in Python, this shows you how to define a function. Notice the format (parameters are often called arguments):
  1. def function_name(arg1, arg2, ...):
  2. statement block
  3. return arg3, arg4, ...
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.
  1. # a function to format to $ currency
  2. def formatDollar(amount):
  3. return "$%.2f" % amount
  4.  
  5. print formatDollar(123.9 * 0.07)
  6. print formatDollar(19)
Many Pythonians prefer this style of commenting functions ...
  1. def formatDollar(amount):
  2. """
  3. a function to format to $ currency
  4. (this allows for multiline comments)
  5. """
  6. return "$%.2f" % amount
  7.  
  8. print formatDollar(123.9 * 0.07)
  9. print formatDollar(19)
There is another use for the triple quoted comment or documentation string. You can access it like this ...
  1. # accessing the documentation string
  2. # (these are double underlines around doc)
  3. print formatDollar.__doc__
A more complete example ...
  1. import math
  2.  
  3. def getDistance(x1, y1, x2, y2):
  4. """
  5. getDistance(x1, y1, x2, y2)
  6. returns distance between two points using the pythagorean theorem
  7. the function parameters are the coordinates of the two points
  8. """
  9. dx = x2 - x1
  10. dy = y2 - y1
  11. return math.sqrt(dx**2 + dy**2)
  12.  
  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:
  1. def getDistance(x1, y1, x2, y2):
  2. """
  3. getDistance(x1, y1, x2, y2)
  4. returns distance between two points using the pythagorean theorem
  5. the function parameters are the coordinates of the two points
  6. """
  7. dx = x2 - x1
  8. dy = y2 - y1
  9. return math.sqrt(dx**2 + dy**2)

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:
  1. builtin_fuction_list = dir(__builtins__)
  2. print builtin_fuction_list
  3.  
  4. print "-"*70 # print a decorative line of 70 dashes
  5.  
  6. # or each function on a line using a for loop
  7. for funk in builtin_fuction_list:
  8. print funk
  9.  
  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.

To get a list of Python keywords use:
  1. from keyword import kwlist
  2.  
  3. print kwlist
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 and wxPython2.8 on Windows XP and Vista.
Last edited by vegaseat : Jul 7th, 2007 at 10:07 pm. Reason: IDEs
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation: vegaseat is on a distinguished road 
Rep Power: 8
Solved Threads: 171
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #4  
Mar 23rd, 2005
When you write a Python program like ...
  1. # use slicing to spell a string in reverse
  2.  
  3. str1 = "Winners never quit, quitters never win!"
  4. # slicing uses [begin : end : step]
  5. # end is exclusive
  6. # defaults are begin = 0, end = len of string, step = 1
  7. # use step = -1 to step from end
  8. print "reverse = ", str1[::-1]
... 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.

  1. # use slicing to spell a string in reverse
  2.  
  3. str1 = "Winners never quit, quitters never win!"
  4. # slicing uses [begin : end : step]
  5. # end is exclusive
  6. # defaults are begin = 0, end = len of string, step = 1
  7. # use step = -1 to step from end
  8. print "reverse = ", str1[::-1]
  9.  
  10. # optional wait for keypress
  11. raw_input('Press Enter...')
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 ...
  1. # slicing uses [start:<end:step]
  2.  
  3. s4 = "hippopotamus"
  4.  
  5. print "first 2 char = ", s4[0:2]
  6. print "next 2 char = ", s4[2:4]
  7. print "last 2 char = ", s4[-2:]
  8. print "exclude first 3 char = ", s4[3: ]
  9. print "exclude last 4 char = ", s4[:-4]
  10. print "reverse the string = ", s4[::-1] # step is -1
  11. print "the whole word again = ", s4
  12. print "spell skipping 2 char = ", s4[::2] # step is 2
  13. """
  14. my output -->
  15. first 2 char = hi
  16. next 2 char = pp
  17. last 2 char = us
  18. exclude first 3 char = popotamus
  19. exclude last 4 char = hippopot
  20. reverse the string = sumatopoppih
  21. the whole word again = hippopotamus
  22. spell skipping 2 char = hpooau
  23. """
Last edited by vegaseat : Jun 5th, 2007 at 12:42 pm. Reason: slicing examples
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation: vegaseat is on a distinguished road 
Rep Power: 8
Solved Threads: 171
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #5  
Mar 23rd, 2005
Python has a very helpful feature called help(). Here is a sample ...
  1. # list all the modules Python currently knows about ...
  2. help("modules")
  3.  
  4. # now pick a module from that list you want to know
  5. # more about ...
  6.  
  7. # to get help about module calendar ...
  8. help("calendar")
  9.  
  10. # dito for the math module
  11. help("math")
  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!

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 : Jun 5th, 2007 at 12:43 pm. Reason: code tags updated
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation: vegaseat is on a distinguished road 
Rep Power: 8
Solved Threads: 171
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #6  
Mar 23rd, 2005
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?
  1. # read a text file to a string and create a list of words
  2.  
  3. # use any text file you have ...
  4. textf = open('xmas.txt', 'r')
  5. str1 = textf.read()
  6. textf.close()
  7.  
  8. print "The text file as one string:"
  9. print str1
  10.  
  11. # splits at the usual whitespaces
  12. wordlist = str1.split(None)
  13. print "\nThe string as a list of words:"
  14. print wordlist
  15.  
  16. print "\nThere are %d words in the list." % len(wordlist)
Want more help about split()? At the interactive page >>> prompt enter
help("string.split")
Last edited by vegaseat : Feb 5th, 2008 at 1:50 am. Reason: [code=python]
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation: vegaseat is on a distinguished road 
Rep Power: 8
Solved Threads: 171
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #7  
Mar 27th, 2005
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.
  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. if txt[0] == "$": # remove leading dollar sign
  5. txt = txt[1:]
  6. if txt[1] == "$": # could be -$xxx
  7. txt = txt[0] + txt[2:]
  8.  
  9. while txt: # select float or integer return
  10. try:
  11. f = float(txt)
  12. i = int(f)
  13. if f == i:
  14. return i
  15. return f
  16. except TypeError: # removes possible trailing stuff
  17. txt = txt[:-1]
  18. return 0
  19.  
  20. # test the function ...
  21. print getVal('-$123.45')
Click on "Toggle Plain Text" so you can highlight and copy the code to your editor without the line numbers.
Last edited by vegaseat : Mar 1st, 2007 at 3:09 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation: vegaseat is on a distinguished road 
Rep Power: 8
Solved Threads: 171
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #8  
Mar 27th, 2005
The IDLE integrated development environment that comes with the normal Python installation is really a GUI program. It uses Tkinter as the GUI interface/library, also part of the normal installation. Tkinter uses tcl script language to do the work.

Here is a typical Python code example using Tkinter ...
  1. # import all the Tkinter methods
  2. from Tkinter import *
  3.  
  4. # create a window frame
  5. frame1 = Tk()
  6. # create a label
  7. label1 = Label(frame1, text="Hello, world!")
  8. # pack the label into the window frame
  9. label1.pack()
  10.  
  11. frame1.mainloop() # run the event-loop/program
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.

If you want to know more about Tkinter, you can run help("Tkinter") from IDLE. This will bring up all of Tkinter's documentations strings. You can also find much Tkinter detail at:
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 or Linux. There are some wxPython GUI examples in the DaniWeb Python Code Snippets. Here is a very nice wxPython tutorial I like to recommend, it will give you a good overview (examples work on Windows, Linux, or Unix):
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 : May 19th, 2007 at 2:51 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation: vegaseat is on a distinguished road 
Rep Power: 8
Solved Threads: 171
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #9  
Mar 30th, 2005
To get input from the user you can use the raw_input() or the input() function. Let's explore the difference. To give you a good idea enter 355/113.0 at each prompt.
  1. # raw_input() reads every input as a string
  2. # then it's up to you to process the string
  3. str1 = raw_input("Enter anything:")
  4. print "raw_input =", str1
  5.  
  6. # input() actually uses raw_input() and then tries to
  7. # convert the input data to a number using eval()
  8. # hence you could enter a math expression
  9. # gives an error if input is not numeric eg. $34.95
  10. x = input("Enter a number:")
  11. print "input =", x
Actually, you can enter a string using input(), but you have to inconvenience the user, asking to have the string enclosed in quotes. So raw_input() is the safe way.

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 ...
  1. print "The grade point average (GPA) calculator:"
  2.  
  3. def get_list(prompt):
  4. """
  5. loops until acceptable data or q (quit) is given
  6. returns a list of the entered data
  7. """
  8. data_list = []
  9. while True:
  10. sin = raw_input(prompt)
  11. if sin == 'q':
  12. return data_list
  13. try:
  14. data = float(sin)
  15. data_list.append(data)
  16. except ValueError:
  17. print "Enter numeric data!"
  18.  
  19. print
  20. gp_list = get_list("Enter grade point (q to quit): ")
  21. print gp_list # test
  22. # process the list ...
  23. # calculate the average (sum of items divided by total items)
  24. gpa = sum(gp_list)/len(gp_list)
  25.  
  26. print "The grade point average is:", gpa
So we can use raw_input() for strings and input() for numbers, but there are some other applications for input() ...
  1. # Python's input() is mainly used for entering numbers
  2. age = input("Enter your age: ")
  3. print age
  4. """
  5. for instance -->
  6. 25
  7. """
  8.  
  9. # however, you can enter a mathematical expression
  10. result = input("Enter a mathematical expression: ")
  11. print result
  12. """
  13. for instance the user enters 7 * 7 -->
  14. 49
  15. """
  16.  
  17. # you can enter a complete list, tuple or dictionary using input
  18. mylist = input("Enter a list: ")
  19. print mylist, type(mylist)
  20. """
  21. for instance -->
  22. [1, 2, 3, 5] <type 'list'>
  23. """
  24.  
  25. # you can enter a string if you put it in quotes
  26. mystring = input("Enter a string in quotes")
  27. print mystring, type(mystring)
  28. """
  29. for instance -->
  30. hello <type 'str'>
  31. """
  32.  
  33. # you can enter and execute a python statement
  34. code = input("Enter __import__('calendar').prmonth(2007, 6) ")
  35. """
  36. result -->
  37. June 2007
  38. Mo Tu We Th Fr Sa Su
  39. 1 2 3
  40. 4 5 6 7 8 9 10
  41. 11 12 13 14 15 16 17
  42. 18 19 20 21 22 23 24
  43. 25 26 27 28 29 30
  44. """
  45.  
  46. # however, here is a potential problem
  47. # let's say you declare
  48. x = 777
  49. # now you add more code here
  50. # ...
  51. # ...
  52. # then you use a somewhat unclear input prompt
  53. # and the user actually enters x rather than the value for x
  54. xvalue = input("Enter x: ")
  55. print xvalue
  56. """
  57. an oops, if user enters x -->
  58. 777
  59. """

Click on "Toggle Plain Text" so you can highlight and copy the code to your editor.
Last edited by vegaseat : Jun 5th, 2007 at 12:26 pm. Reason: code=python tag remark
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation: vegaseat is on a distinguished road 
Rep Power: 8
Solved Threads: 171
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #10  
Apr 29th, 2005
I need to write a function that can return more than one item. This is a simple example how to do it ...
  1. # use a tuple to return multiple items from a function
  2. # a tuple is a set of values separated by commas
  3. def multiReturn():
  4. return 3.14, "frivolous lawsuits", "Good 'N' Plenty"
  5.  
  6. # show the returned tuple
  7. # notice that it is enclosed in ()
  8. print multiReturn()
  9.  
  10. # load to a tuple of variables
  11. num, str1, str2 = multiReturn()
  12. print num
  13. print str1
  14. print str2
  15.  
  16. # or pick just the element at index 1, should be same as str1
  17. # tuples start at index zero just like lists etc.
  18. print multiReturn()[1]
This example has not only a multiple argument return, but also allows you to call it with multiple arguments of flexible size/number ...
  1. # explore the argument tuple designated by *args
  2. # used for cases where you don't know the number of arguments
  3. def sum_average(*args):
  4. size = len(args)
  5. sum1 = sum(args)
  6. average = sum1/float(size)
  7. # return a tuple of three arguments
  8. # args is the tuple we passed to the function
  9. return args, sum1, average
  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) # sum of (2, 5, 6, 7) = 20
  18.  
  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 : Mar 10th, 2007 at 11:35 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
Reply