|
Python Tips
By Robert John Stevens, CEO of WriteExpress Corporation
Getting started in any new language is tough. One slowly acquires knowledge and discovers tips and tricks. Here are my notes:
Python Tutorial—From
the Python website
How to start the IDLE
c:\python32\pythonw c:\python32\lib\idlelib\idle.py (There must be a better way to do this.)
Python IDLE—Help for the Python IDE
What's cool about Python
No curly braces—Indentation is used instead of begin/end statements.
You can share your code on PyPI (Python's central code repository) or download code written by others.
Python delays syntax and code validity checking until it runs. This means you can call functions before they are declared or defined.
Online Python Documentation
with—The with statement, combined with open, lets you open files in a try/except block. If open fails, Python automatically closes the file for you.
Optional arguments with default values—Plus when calling a function you can pick and choose which parameter values you assign by specifically naming them and assigning values.
pickle—A standard Python persistance library that makes it easy and efficient for you to save or load almost any Python data object, including lists. With pickle you can store data to a disk file, database or transfer it over a network.
No semi-colons to end lines
Method chaining—lets you chain method calls together on a single line so the output of one becomes the input to another. Method chains are read left to right.
myText = data().strip().split(',')
Function chaining—lets you chain function calls together on a single line so the output of one becomes the input to another. Function chains are read right to left.
In this example, strip removes the unwanted leading and trailing white space in the text referenced by the variable data, and then the split extracts the strings separted by commas. A list is created and assigned to MyText. Notice that methods are executed from left to right.
print(sorted(data))
One-line iterative transformations on lists—For example, convert days to seconds:
>>> days=[1,2,3]
>>> secs=[d*24*60*60 for d in days]
>>> secs
[86400, 172800, 259200]
Python Definitions
BIF—Built-in function
Case Sensitivity—Yes, for example, print and PRINT are different.
IDLE—Python's integrated development environment
Python Built-in Functions (BIF)
From the IDLE (>>> prompt), create a list:
books=["Matthew","Mark",'Luke']
append()—Add a data item to the end of a list
books.append=("John")
insert()—Insert a data item before a specific location in a list
books.insert(0, "Malachi")
len()—Length of a list
print(len(books))
help()—and pass in an argument. Or, click the menu Help > Python Docs from IDLE
pop()—Removes a data item from the end of a list
books.pop()
print()—Prints to the screen
books.print()
remove()—Finds and removes a specific data item from a list
books.remove('Mark')
sort()—Sorts a list in ascending order in place. The sort by descending order, pass in the parameter reverse=True
sorted()—Sorts a list in ascending order and returns a reference to the new list. The original list is not modified.
str()—Converts any object to a string, if the object supports the conversion
except IOError as err:
print('The file error is: ' + str(err))
strip()—Removes unwanted white space from a string
myline.strip()
Python Language Constructs
Python Working with lists
Using lists within lists
>>> bible=['Old Testament', ['New Testament',['Matthew','Mark','Luke','John','Acts']]]
>>> print(bible)
['Old Testament', ['New Testament', ['Matthew', 'Mark', 'Luke', 'John', 'Acts']]]
>>> print(bible[0])
Old Testament
>>> print(bible[1][0])
New Testament
>>> print(bible[1][1][2])
Luke
Remove duplicates in a list
>>> NewTestament=['Matthew','Mark','Mark','Luke','John']
>>> NewTestament
['Matthew', 'Mark', 'Mark', 'Luke', 'John']
>>> NoDuplicates=[]
>>> for each_a in NewTestament:
>>> if each_a not in NoDuplicates:
>>> NoDuplicates.append(each_a)
>>> print(NoDuplicates)
['Matthew', 'Mark', 'Luke', 'John']
`
IDLE Commands
Alt-p—Move to the previous code statement
Alt-n—Move to the next code statement
import sys;sys.path—Shows folders where Python searches for modules
File Commands
Get the current working directory
import os
os.getcwd()
Change a directory
import os
os.chdir('c:\\')
open and read a line from a file
import os
with open('c:\\foo.txt') as fp:
data=fp.readline()
IDLE Gotchas
Python Commands
Python Distributions
Python Editors or Integrated Development Environments (Python IDEs)
Python Open Source
Python Programming Language
Function syntax—def function name (optional argument(s)):
IDLE—Python's integrated development environment
Lists—Zero-based array-like data structures that do not have a type (int, string, etc.). Lists are full blown Python collection objects meaning they have their own methods.
Comments—Use the triple quote '''for multiple-line comments. Start and end your comments with triple quotes. You can also use # for single-line quotes.
Module—A text file that contains Python code
|
Copyright © 2011 Robert Stevens. All rights reserved.
This article was commenced on April 18, 2011. Last update: April 22, 2011.
© 1996-2011 WriteExpress Corporation. All rights reserved. WriteExpress®, Rhymer® and Unblocking Writers' Block® are registered trademarks of WriteExpress Corporation.
|