Home » Python » Python entry notes (1)

Python entry notes (1)

1. variable assignment:


counter =0


miles = 1000.0


name ='xumesang'


n = 10


2. string:


str ='python'


str[0] = p


str[-1] = n


str * 2 ='pythonpython'


3. lists, tuples, and dictionaries:


list = [1,2,3,4] # variable elements


tuple = ('xumesang', 23, 101) # element variable


dict = {'host':'earth'}


dict['port'] = 80


dict.keys () = ['host','port']


for key in dict:


, print, key, dict[key]


4., loop, and range ():


print item, # nonbreaking


print # line


print,'We, are, the,%s, who, say,%s',%


... (who, ((what +), * 4))


range (3) = [0, 1, 2]


5. list parsing:


syntax:



[expr, for, iter_var, in iterable]
[expr,
for, iter_var, in, Iterable, , >if


The first kind of

Grammar: the first iteration all the contents of Iterable in each iteration, the corresponding Iterable content in the iter_var, then the application of iter_var in the expression of the content, finally by expression of the calculated values to generate a list of.


second syntax: add the judgment statement, only to meet the conditions of the content to Iterable in the corresponding content in the iter_var, then the application of iter_var in the expression of the content, finally by expression of the calculated values to generate a list of.


6. files and exceptions:


try:


fobj = open (filename,'r')


For eachLine in fobj:

, print, eachLine,


fobj.close ()


except, IOError, e:


, print,'File, open, error:', e


7. class:


class FooClass (object):


version = 0.1 # static variables, are all examples and methods of sharing


, def, __init__ (self, nm='xumesang'):


self.name = nm


fool = FooClass (

) # to create an instance of the class

8. module:


import module_name


module.function ()


module.variable

Latest