Starting Python

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

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

Starting Python

 
2
  #1
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!


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
Python31 July2009
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:
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 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.
  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 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

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


A detailed and interesting essay about Python's creation and architecture:
http://stride-online.com/filestorage/Python.pdf

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.
Last edited by vegaseat; Aug 23rd, 2009 at 11:44 am. Reason: Python31 updates
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,047
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: 935
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #2
Mar 23rd, 2005
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!
Last edited by vegaseat; Dec 22nd, 2008 at 4:20 pm.
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,047
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: 935
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #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. 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 ....
  1. def get_name():
  2. """this function only returns arguments"""
  3. first = "Fred"
  4. last = "Ferkel"
  5. return first, last
  6.  
  7. def show_name(name):
  8. """this function only receives an argument"""
  9. print( name )
  10.  
  11. def process_name(first, last):
  12. """this function reveives 2 arguments, returns 1 argument"""
  13. name = "Mr. " + first +" " + last
  14. return name
  15.  
  16. def main():
  17. """
  18. this function handles the other functions in order
  19. and deals with the arguments received and to be passed
  20. """
  21. first, last = get_name()
  22. name = process_name(first, last)
  23. show_name(name)
  24.  
  25. # start the program with this function call
  26. main()
  27.  
  28. """my output -->
  29. Mr. Fred Ferkel
  30. """
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 or 2.6 and wxPython2.8 on Windows XP and Vista.
Last edited by vegaseat; 7 Days Ago at 10:28 am. Reason: IDEs, Python31 update
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,047
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: 935
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #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...')
  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 ...
  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. """
You can apply slicing to any indexed sequence, here is a list example ...
  1. # exploring Python's slicing operator
  2. # can be used with any indexed sequence like strings, lists, ...
  3. # syntax --> seq[begin : end : step]
  4. # step is optional
  5. # 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] ) # [3,4,5]
  14. # if either index is omitted, beginning or end of sequence is assumed
  15. print( a[:3] ) # [0,1,2]
  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] ) # [2,3,4,5,6]
  20. print( a[-4:] ) # [5,6,7,8]
  21.  
  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 ) # [0, 1, 2, 3, 4, 5, 6, 7, 8]
  41. print( b ) # [0, 1, 2, 9, 9, 9, 9, 3, 4, 5, 6, 7, 8]
Last edited by vegaseat; 29 Days Ago at 3:05 pm. Reason: slicing examples
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,047
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: 935
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #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 1:43 pm. Reason: code tags updated
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,047
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: 935
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

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

Re: Starting Python

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

Re: Starting Python

 
0
  #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. # explore the Tkinter GUI toolkit
  2.  
  3. try:
  4. # for Python2
  5. import Tkinter as tk
  6. except ImportError:
  7. # for Python3
  8. import tkinter as tk
  9.  
  10. # create a window frame
  11. frame1 = tk.Tk()
  12. # create a label
  13. label1 = tk.Label(frame1, text="Hello, world!")
  14. # pack the label into the window frame
  15. label1.pack()
  16.  
  17. 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.

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

Re: Starting Python

 
0
  #9
Mar 30th, 2005
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 ...
  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) # input(prompt) in Python3
  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 )
Since Python2's raw_input() will not work with Python3, you can use try/except to make your program work with both versions ...
  1. # use module datetime to show age in days
  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. bd = raw_input(prompt)
  10. except NameError:
  11. # Python3
  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; 10 Days Ago at 11:04 am. Reason: code=python tag remark, Python3 update
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,047
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: 935
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #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; Aug 16th, 2009 at 10:31 pm. Reason: [code=python] tag
May 'the Google' be with you!
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