•
•
•
•
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
![]() |
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation:
Rep Power: 8
Solved Threads: 171
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:
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 ...
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 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
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:
python Syntax (Toggle Plain Text)
print "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 ...
python Syntax (Toggle Plain Text)
str1 = "Hello Monty Python!" # this is a comment # notice you don't have to declare the variable type print str1
One more change for the fun of it ...
python Syntax (Toggle Plain Text)
str1 = "Hello Monty Python!" # let's replace the M with Spam str2 = str1.replace('M', 'Spam') # one more Spam for the P str3 = str2.replace('P', 'Spam') # now look at the result print str1 print str2 print str3
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!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation:
Rep Power: 8
Solved Threads: 171
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation:
Rep Power: 8
Solved Threads: 171
For beginners in Python, this shows you how to define a function. Notice the format (parameters are often called arguments):
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.
Many Pythonians prefer this style of commenting functions ...
There is another use for the triple quoted comment or documentation string. You can access it like this ...
A more complete example ...
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:
Sorry, couldn't resist showing off the different ways to present the data.
To get a list of Python keywords use:
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.
python Syntax (Toggle Plain Text)
def function_name(arg1, arg2, ...): statement block return arg3, arg4, ...
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.
python Syntax (Toggle Plain Text)
# a function to format to $ currency def formatDollar(amount): return "$%.2f" % amount print formatDollar(123.9 * 0.07) print formatDollar(19)
python Syntax (Toggle Plain Text)
def formatDollar(amount): """ a function to format to $ currency (this allows for multiline comments) """ return "$%.2f" % amount print formatDollar(123.9 * 0.07) print formatDollar(19)
python Syntax (Toggle Plain Text)
# accessing the documentation string # (these are double underlines around doc) print formatDollar.__doc__
python Syntax (Toggle Plain Text)
import math def getDistance(x1, y1, x2, y2): """ 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) print "Distance between point(1,3) and point(4,7) is", getDistance(1,3,4,7) print "Distance between point(1,3) and point(11,19) is", getDistance(1,3,11,19) print '-'*50 # print 50 dashes, cosmetic print "The function's documentation string:" # shows comment between the triple quotes print getDistance.__doc__
python Syntax (Toggle Plain Text)
def getDistance(x1, y1, x2, y2): """ 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)
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:
python Syntax (Toggle Plain Text)
builtin_fuction_list = dir(__builtins__) print builtin_fuction_list print "-"*70 # print a decorative line of 70 dashes # or each function on a line using a for loop for funk in builtin_fuction_list: print funk print "-"*70 # or each function on a line joining the list to a string print '\n'.join(builtin_fuction_list) print "-"*70 # or, a little more advanced, combine it all and do a case insensitive sort too print '\n'.join(sorted(dir(__builtins__), key = str.lower))
To get a list of Python keywords use:
python Syntax (Toggle Plain Text)
from keyword import kwlist print kwlist
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!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation:
Rep Power: 8
Solved Threads: 171
When you write a Python program like ...
... 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.
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 ...
python Syntax (Toggle Plain Text)
# use slicing to spell a string in reverse str1 = "Winners never quit, quitters never win!" # slicing uses [begin : end : step] # end is exclusive # defaults are begin = 0, end = len of string, step = 1 # use step = -1 to step from end print "reverse = ", str1[::-1]
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.
python Syntax (Toggle Plain Text)
# use slicing to spell a string in reverse str1 = "Winners never quit, quitters never win!" # slicing uses [begin : end : step] # end is exclusive # defaults are begin = 0, end = len of string, step = 1 # use step = -1 to step from end print "reverse = ", str1[::-1] # optional wait for keypress raw_input('Press Enter...')
str1[0 : len(str1) : -1] .
Just a few more slicing examples ...
python Syntax (Toggle Plain Text)
# slicing uses [start:<end:step] s4 = "hippopotamus" print "first 2 char = ", s4[0:2] print "next 2 char = ", s4[2:4] print "last 2 char = ", s4[-2:] print "exclude first 3 char = ", s4[3: ] print "exclude last 4 char = ", s4[:-4] print "reverse the string = ", s4[::-1] # step is -1 print "the whole word again = ", s4 print "spell skipping 2 char = ", s4[::2] # step is 2 """ my output --> first 2 char = hi next 2 char = pp last 2 char = us exclude first 3 char = popotamus exclude last 4 char = hippopot reverse the string = sumatopoppih the whole word again = hippopotamus spell skipping 2 char = hpooau """
Last edited by vegaseat : Jun 5th, 2007 at 12:42 pm. Reason: slicing examples
May 'the Google' be with you!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation:
Rep Power: 8
Solved Threads: 171
Python has a very helpful feature called help(). Here is a sample ...
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
python Syntax (Toggle Plain Text)
# list all the modules Python currently knows about ... help("modules") # now pick a module from that list you want to know # more about ... # to get help about module calendar ... help("calendar") # dito for the math module help("math") # file stuff ... help("file") # down to method/function level ... help("os.read")
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!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation:
Rep Power: 8
Solved Threads: 171
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")
python Syntax (Toggle Plain Text)
# read a text file to a string and create a list of words # use any text file you have ... textf = open('xmas.txt', 'r') str1 = textf.read() textf.close() print "The text file as one string:" print str1 # splits at the usual whitespaces wordlist = str1.split(None) print "\nThe string as a list of words:" print wordlist print "\nThere are %d words in the list." % len(wordlist)
help("string.split")
Last edited by vegaseat : Feb 5th, 2008 at 1:50 am. Reason: [code=python]
May 'the Google' be with you!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation:
Rep Power: 8
Solved Threads: 171
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.
Click on "Toggle Plain Text" so you can highlight and copy the code to your editor without the line numbers.
python Syntax (Toggle Plain Text)
# a function to return the numeric content of a cost item # for instance $12.99 or -$123456789.01 (deficit spenders) def getVal(txt): if txt[0] == "$": # remove leading dollar sign txt = txt[1:] if txt[1] == "$": # could be -$xxx txt = txt[0] + txt[2:] while txt: # select float or integer return try: f = float(txt) i = int(f) if f == i: return i return f except TypeError: # removes possible trailing stuff txt = txt[:-1] return 0 # test the function ... print getVal('-$123.45')
Last edited by vegaseat : Mar 1st, 2007 at 3:09 pm. Reason: [code=python] tag
May 'the Google' be with you!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation:
Rep Power: 8
Solved Threads: 171
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 ...
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.
Here is a typical Python code example using Tkinter ...
python Syntax (Toggle Plain Text)
# import all the Tkinter methods from Tkinter import * # create a window frame frame1 = Tk() # create a label label1 = Label(frame1, text="Hello, world!") # pack the label into the window frame label1.pack() frame1.mainloop() # run the event-loop/program
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!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation:
Rep Power: 8
Solved Threads: 171
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.
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 ...
So we can use raw_input() for strings and input() for numbers, but there are some other applications for input() ...
Click on "Toggle Plain Text" so you can highlight and copy the code to your editor.
python Syntax (Toggle Plain Text)
# raw_input() reads every input as a string # then it's up to you to process the string str1 = raw_input("Enter anything:") print "raw_input =", str1 # input() actually uses raw_input() and then tries to # convert the input data to a number using eval() # hence you could enter a math expression # gives an error if input is not numeric eg. $34.95 x = input("Enter a number:") print "input =", x
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 ...
python Syntax (Toggle Plain Text)
print "The grade point average (GPA) calculator:" def get_list(prompt): """ loops until acceptable data or q (quit) is given returns a list of the entered data """ data_list = [] while True: sin = raw_input(prompt) if sin == 'q': return data_list try: data = float(sin) data_list.append(data) except ValueError: print "Enter numeric data!" gp_list = get_list("Enter grade point (q to quit): ") print gp_list # test # process the list ... # calculate the average (sum of items divided by total items) gpa = sum(gp_list)/len(gp_list) print "The grade point average is:", gpa
python Syntax (Toggle Plain Text)
# Python's input() is mainly used for entering numbers age = input("Enter your age: ") print age """ for instance --> 25 """ # however, you can enter a mathematical expression result = input("Enter a mathematical expression: ") print result """ for instance the user enters 7 * 7 --> 49 """ # you can enter a complete list, tuple or dictionary using input mylist = input("Enter a list: ") print mylist, type(mylist) """ for instance --> [1, 2, 3, 5] <type 'list'> """ # you can enter a string if you put it in quotes mystring = input("Enter a string in quotes") print mystring, type(mystring) """ for instance --> hello <type 'str'> """ # you can enter and execute a python statement code = input("Enter __import__('calendar').prmonth(2007, 6) ") """ result --> June 2007 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 """ # however, here is a potential problem # let's say you declare x = 777 # now you add more code here # ... # ... # then you use a somewhat unclear input prompt # and the user actually enters x rather than the value for x xvalue = input("Enter x: ") print xvalue """ an oops, if user enters x --> 777 """
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!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation:
Rep Power: 8
Solved Threads: 171
I need to write a function that can return more than one item. This is a simple example how to do it ...
This example has not only a multiple argument return, but also allows you to call it with multiple arguments of flexible size/number ...
Click on "Toggle Plain Text" so you can highlight and copy the code to your editor.
python Syntax (Toggle Plain Text)
# use a tuple to return multiple items from a function # a tuple is a set of values separated by commas def multiReturn(): return 3.14, "frivolous lawsuits", "Good 'N' Plenty" # show the returned tuple # notice that it is enclosed in () print multiReturn() # load to a tuple of variables num, str1, str2 = multiReturn() print num print str1 print str2 # or pick just the element at index 1, should be same as str1 # tuples start at index zero just like lists etc. print multiReturn()[1]
python Syntax (Toggle Plain Text)
# explore the argument tuple designated by *args # used for cases where you don't know the number of arguments def sum_average(*args): size = len(args) sum1 = sum(args) average = sum1/float(size) # return a tuple of three arguments # args is the tuple we passed to the function return args, sum1, average # notice that the first element is the args tuple we send to the function print sum_average(2, 5, 6, 7) # ((2, 5, 6, 7), 20, 5.0) # or unpack into a tuple of appropriate variables args_tuple, sum2, average = sum_average(2, 5, 6, 7) print "sum of %s = %d" % (args_tuple, sum2) # sum of (2, 5, 6, 7) = 20 print "average of %s = %0.2f" % (args_tuple, average) # average of (2, 5, 6, 7) = 5.00 # or just pick one return value, here value at index 1 = the sum print "sum =", sum_average(2, 5, 6, 7)[1] # sum = 20
Last edited by vegaseat : Mar 10th, 2007 at 11:35 pm. Reason: [code=python] tag
May 'the Google' be with you!
![]() |


