Python Cheat Sheet
When learning about a new technical area there's often a bewildering amount of detail to keep track of. Generations of techies have made use of cheat sheets to have an easy reference to these details. A more detailed alternative is provided by the Python Quick Reference. If you want to print it out or save it locally several forms are available
Constants (Number types):
- integers, e.g. 18, -341. A suffix L indicates a long integer, e.g. 34251673L.
- floating point values, e.g. 3.001
/for division (watch for integer division, e.g. 19 / 4 = 4, not 4.75)
%for remainder or modulo, e.g. 19 % 4 = 3
**for exponentiation, e.g. 2 ** 4 = 16
"This is a string"
=for assignment, e.g.
name = "Tim Topper"
+for concatenation, e.g.
"Hi" + "Ho"-->
*for repetition, e.g.
3 * "Ho"-->
Strings can be delimited by either double quotes
"Tim"or single quotes
Multiline values can be assigned to a string by triple quoting the contents, e.g.
silly = """Two Lines"""
Trying the same thing without triple quoting results in an error, e.g.
silly = "Two Lines"
Another method is to embed control codes for newline characters into the string, e.g.
silly = "Two\nLines"
The most common control codes are:
\nfor newline and
\tfor tab. The Python Quick Reference provides a complete list.
Like lists Python strings are a sequence type so many list commands also work with strings.
s[ i ]accesses element number
iof the string
Testing string contents:
s.endswith( suffix )
s.startswith( prefix )
Finding things in strings:
s.count( substring )
s.find( substring )
s.index( substring )
s.rfind( substring )
s.rindex( substring )
Changing strings. Remember that strings are immutable so to make a change "stick" you have to do, e.g.
s = s.title().
s.lstrip( chars )
s.rstrip( chars )
String to list:
list = s.split( list )
List to string:
s.join( list )where s is the string to join the elements of list with.
= to assign a name to a value, e.g.
distance = 48.1,
name = "Tim Topper". Remember that the name has to be on the left hand side of the
48.1 = distance is an error.
Displays the value of each item in the list. Puts a space between each pair of values. Example:
print "The answer is", 5 + 2, "." displays:
The answer is 7 .
Appending a comma to the end of a print statement holds the current output line open, e.g. the code
print "The answer is", print 5 + 2, "."
The answer is 7 .
on a single line.
For more control over output appearance embed formatting codes into output strings. See section 188.8.131.52 String Formatting Operations of the Python Library Reference for the gory details.
input to get numerical data from the user,
input( string )
raw_input to get string data.
Both display string (if given) and then read a line of input, by default from the keyboard. The difference is that
raw_input just returns the string, while
input evaluates it as a Python exprssion and returns the result.
distance = input( "Enter the distance in miles: " ) name = raw_input( "What is your name? " )
N.B. the spaces before the second
" in each case.
Use if to execute one block of code or another, but not both.
if test: statements elif test: statements else: statements
else statements are optional as shown in the first two examples below.
if x < 0: print x, "is negative"
if flip == 1: print "You got heads" else: print "You got tails"
if num < 0: print "The number", num, "is negative." elif num == 0: print "The number", num, "is neither positive nor negative." else: print "The number", num, "is positive."
while to execute a block of code multiple times.
while test: statements
x = 1 while x < 10 print x x = x + 1
num = input( "Enter a number between 1 and 100: " ) while num < 1 or num > 100: print "Oops, your input value (", num, ") is out of range." num = input( "Be sure to enter a value between 1 and 100: " )
Play again? Repeating a program
again = "y" while again == "y" or again == "Y" or again == "yes" or again == "Yes": # # Put the body of your program here # again = raw_input( "Play again (y/n)? " ) print "Thanks for playing"
Unlike many languages Python provides a built-in list type. A list constant is just a list of items separated by commas and placed inside square brackets, e.g.
[ "Tim", 42, "Molly" ].
Python provides for a wealth of list operations (complete list in reference manual):
list1 + list2: concatenates
list[ i ]: access element number i in
len( list ): returns the number of elements in
del list[ i ]: deletes element number i from
list.append( value ): appends
list.sort(): sorts the elements in
list.reverse(): reverses the order of the elements in
list.index( value ): returns the position of the first occurrence of
list.insert( i, value ): inserts
listat position i
list.count( value ): returns a count of the number of times
list.remove( value ): deletes the first occurrence of
list.pop(): deletes and returns the last value in
value in list: is
valueoccurs in list and
Text file processing
To read from a file a line at a time:
infilename = raw_input( "Name of file to read from: " ) infile = open( infilename, "r" ) for line in infile: # Do stuff with line. # Remember that line is a string even if it looks like a number, # e.g. num = int( line ) infile.close()
There's more than this of course. You can also read the entire file into a string in one fell swoop using
infile.read(), read the entire file into a list of strings (one per line in the file) using
infile.readlines(), or read a certain number of bytes using
infile.read( N ) where
N gives the number of bytes to read.
To write to a file:
outfilename = raw_input( "Name of file to write to: " ) outfile = open( outfilename, "w" ) print >> outfile, ... outfile.close()
For more see the Python library reference on File Objects.
Python provides a built-in lookup table type it calls a dictionary (often called hash tables in other languages).
A dictionary constant consists of a series of key-value pairs enclosed by curly braces, e.g.
d = z 'Tim' : 775, 'Brian' : 869 . This creates a dictionary we can visualize as:
Common dictionary operations include:
d[ 'Tim' ]Accessing an element.
d[ 'A-S' ] = 770Modifying or inserting a value.
d.has_key( 'Brian' )Checking to see if there is a value for a particular key.
d.keys()Get a list of all the keys in the dictionary. Often used for iterating through the entries in the dictionary.
d.values()Get a list of all the values that occur in the dictionary.
del( d[ 'Tim' ] )Delete an entry in the dictionary.
d.clear()Delete all the entries in a dictionary.
Publicado el 08/03/2011Páginas de interés