1.
variable1,variable2...=value1,value2...
2.
if condition1:
action1
elif condition2:
action2
else:
#default_condition:
default_action
3.
while condition:
4.
from os.path import exists
from sys import argv
arg1,arg2,arg3,...=argv
#当argv是list或者table类型时可用
def function(argv):
5.文件操作
file=open(file_name,'w')
txt=file.read()
print file.read()#read all the txt
print file.readline()#read one line at a time ,and automatically turns to next line when finished,next time you call readline() ,it will return next line.
file.seek(),file.seek(offset[ ,whence])
#Help on method_descriptor:
#seek(...)
# seek(offset[, whence]) -> None. Move to new file position.
# Argument offset is a byte count. Optional argument whence defaults to
# 0 (offset from start of file, offset should be >= 0); other values are 1
# (move relative to current position, positive or negative), and 2 (move
# relative to end of file, usually negative, although many platforms allow
# seeking beyond the end of a file). If the file is opened in text mode,
# only offsets returned by tell() are legal. Use of other offsets causes
# undefined behavior.
# Note that not all file objects are seekable.
file.close()
file.seek()#to attain the function rewind()
str.split(char)#seperate the str into elements of list with the charactere "char“
6.list
list=>[ , , ,]
list.append(char)
list.pop()
list
7.sorted
sorted(["ban","abandon","control",”bon"])
8.dictionary type
dictionary=>
dic={keyword1:word1,keyword2:word2…}
del dic[keyword]
dic[new_keyword]=new_word
9.raw_input returns a string
choice=raw_input(">") #choice is a str,'cause the input function raw_input returns a string
if '1' in choice:
for
elif pass:
else : #every if must be composed with a else
...
10.Rules for If-Statements
Every if-statement must have an else.
If this else should never run because it doesn’t make sense, then you must use a die function in the else that prints out an error message and dies, just like we did in the last exercise. This will find many errors.#必须有exit(0)
Never nest if-statements more than two deep and always try to do them one deep.
Treat if-statements like paragraphs, where each if-elif-else grouping is like a set of sentences. Put blank lines before and after.
Your boolean tests should be simple. If they are complex, move their calculations to variables earlier in your function and use a good name for the variable.
Rules for Loops
Use a while-loop only to loop forever, and that means probably never. This only applies to Python; other languages are different.
Use a for-loop for all other kinds of looping, especially if there is a fixed or limited number of things to loop over.
11.how to def a function ,the paraments of a function should contain
$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Thing(object):
... def test(hi):
... print "hi"
...
>>> a = Thing()
>>> a.test("hello")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: test() takes exactly 1 argument (2 given)
>>>
What was all that? Well, this is me typing into the Python shell and showing you some magic. You haven't seen class yet but we'll get into that later. For now you see how Python said test() takes exactly 1 argument (2 given). If you see this it means that Python changed a.test("hello") to test(a, "hello") and that somewhere someone messed up and didn't add the argument for a.
#self.function(argv) when in the computer-running time ,this function is executived as function(self,argv),but in the defination of the function ,there is only one argv being declared,so we should define the functuin test()like this:
def test(self,hi):
#and then solved
12.dictionary ,map
# create a mapping of state to abbreviation
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}
# create a basic set of states and some cities in them
cities = {
'CA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
}
# add some more cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
# print out some cities
print '-' * 10
print "NY State has: ", cities['NY']
print "OR State has: ", cities['OR']
# print some states
print '-' * 10
print "Michigan's abbreviation is: ", states['Michigan']
print "Florida's abbreviation is: ", states['Florida']
# do it by using the state then cities dict
print '-' * 10
print "Michigan has: ", cities[states['Michigan']]
print "Florida has: ", cities[states['Florida']]
# print every state abbreviation
dict.items()
print '-' * 10
for state, abbrev in states.items():
print "%s is abbreviated %s" % (state, abbrev)
# print every city in state
print '-' * 10
for abbrev, city in cities.items():
print "%s has the city %s" % (abbrev, city)
# now do both at the same time
print '-' * 10
for state, abbrev in states.items():
print "%s state is abbreviated %s and has city %s" % (
state, abbrev, cities[abbrev])
print '-' * 10
# safely get a abbreviation by state that might not be there
state = states.get('Texas')
if not state:
print "Sorry, no Texas."
# get a city with a default value
city = cities.get('TX', 'Does Not Exist')
print "The city for the state 'TX' is: %s" % city
for abbrev, city in cities.items():
print "%s has the city %s" % (abbrev, city)
13.enumerate:
Help on class enumerate in module __builtin__:
class enumerate(object)
| enumerate(iterable[, start]) -> iterator for index, value of iterable
|
| Return an enumerate object. iterable must be another object that supports
| iteration. The enumerate object yields pairs containing a count (from
| start, which defaults to zero) and a value yielded by the iterable argument.
| enumerate is useful for obtaining an indexed list:
| (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
|
| Methods defined here:
|
| __getattribute__(...)
| x.__getattribute__('name') <==> x.name
|
| __iter__(...)
| x.__iter__() <==> iter(x)
|
| next(...)
| x.next() -> the next value, or raise StopIteration
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __new__ = <built-in method __new__ of type object>
| T.__new__(S, ...) -> a new object with type S, a subtype of T
14.hash
Help on built-in function hash in module __builtin__:
hash(...)
hash(object) -> integer
Return a hash value for the object. Two objects with the same value have
the same hash value. The reverse is not necessarily true, but likely.
15.super
super(class1,object)
#returns a class2 that the class1 of the object inherit from;*
16.**和*
**
两个乘号就是乘方,比如2**4,结果就是2的4次方,结果是16
一个乘号*,如果操作数是两个数字,就是这两个数字相乘,如2*4,结果为8
*
*如果是字符串、列表、元组与一个整数N相乘,返回一个其所有元素重复N次的同类型对象,比如”str”*3将返回字符串”strstrstr”
如果是函数定义中参数前的表示的是将调用时的多个参数放入元组中,*则表示将调用函数时的关键字参数放入一个字典中
如定义以下函数
def func(*args):print(args)
当用func(1,2,3)调用函数时,参数args就是元组(1,2,3)
定义以下函数
def func(**args):print(args)
当用func(a=1,b=2)调用函数时,参数args将会是字典{‘a’:1,’b’:2}如果是在函数调用中,*args表示将可迭代对象扩展为函数的参数列表
args=(1,2,3)
func=(*args)
等价于函数调用func(1,2,3)
函数调用的**表示将字典扩展为关键字参数
args={‘a’:1,’b’:2}
func(**args)
等价于函数调用 func(a=1,b=2)