Python 学习小结

python 学习小结

python 简明教程

1.python 文件

#!/etc/bin/python
#coding=utf-8

2.main()函数

if __name__ == '__main__':

3.物理行与逻辑行;

下面是一个在多个物理行中写一个逻辑行的例子。它被称为明确的行连接。
s = 'This is a string. \
This continues the string.'
print s
它的输出:
This is a string. This continues the string. 

有时候,有一种暗示的假设,可以使你不需要使用反斜杠。这种情况出现在逻辑行中使用了圆

括号、方括号或波形括号的时候。这被称为暗示的行连接。

4.缩进

    如何缩进
    不要混合使用制表符和空格来缩进,因为这在跨越不同的平台的时候,无法正常工作。我 强
烈建议 你在每个缩进层次使用 单个制表符 或 两个或四个空格 。
选择这三种缩进风格之一。更加重要的是,选择一种风格,然后一贯地使用它,即 只 使用这
一种风格。 
tab 是4个空格

5.运算符

6.终端输入

guess = int(raw_input('Enter an integer : '))

7. while 循环

    while语句有一个可选的else从句。
number = 23
running = True
while running:
 guess = int(raw_input('Enter an integer : '))
 if guess == number:
 print 'Congratulations, you guessed it.'
 running = False # this causes the while loop to stop
 elif guess < number:
 print 'No, it is a little higher than that'
 else:
 print 'No, it is a little lower than that'
else:
 print 'The while loop is over.'
 # Do anything else you want to do here
print 'Done' 

8.for 循环

for i in range(1, 5):
 print i
else:
 print 'The for loop is over' 

9.range 函数

range返回一个序列的数。这个序列从第一个数开始到第二个数
为止。例如,range(1,5)给出序列[1, 2, 3, 4]。默认地,range的步长为1。如果我们为range提供第
三个数,那么它将成为步长。例如,range(1,5,2)给出[1,3]。记住,range 向上 延伸到第二个
数,即它不包含第二个数。

10. break continue 语句

break语句是用来 终止 循环语句的,即哪怕循环条件没有称为False或序列还没有被完全递归,
也停止执行循环语句。

continue语句被用来告诉Python跳过当前循环块中的剩余语句,然后 继续 进行下一轮循环。

11.数据结构

  • 1.列表:
    shoplist = ['apple', 'mango', 'carrot', 'banana']

  • 2.元组:
    元组和列表十分类似,只不过元组和字符串一样是 不可变的 即你不能修改元组。
    zoo = ('wolf', 'elephant', 'penguin')

    元组最通常的用法是用在打印语句中,下面是一个例子:

    age = 22
    name = 'Swaroop'
    print '%s is %d years old' % (name, age)
    print 'Why is %s playing with that python?' % name 
    
    
  • 3.字典:

    ab = { 'Swaroop' : 'swaroopch@byteofpython.info',
    

'Larry' : 'larry@wall.org',
'Matsumoto' : 'matz@ruby-lang.org',
'Spammer' : 'spammer@hotmail.com'
}
print "Swaroop's address is %s" % ab['Swaroop']

Adding a key/value pair

ab['Guido'] = 'guido@python.org'

Deleting a key/value pair

del ab['Spammer']
print '\nThere are %d contacts in the address-book\n' % len(ab)
for name, address in ab.items():
print 'Contact %s at %s' % (name, address)
if 'Guido' in ab: # OR ab.has_key('Guido')
print "\nGuido's address is %s" % ab['Guido']
````

  • 4.序列

列表、元组和字符串都是序列,但是序列是什么,它们为什么如此特别呢?序列的两个主要特
点是索引操作符和切片操作符。索引操作符让我们可以从序列中抓取一个特定项目。切片操作
符让我们能够获取序列的一个切片,即一部分序列。
````

12.引用

当你创建一个对象并给它赋一个变量的时候,这个变量仅仅 引用 那个对象,而不是表示这个
对象本身!也就是说,变量名指向你计算机中存储那个对象的内存。这被称作名称到对象的绑
定。
如果你想要复制一个列表或者类似的序
列或者其他复杂的对象(不是如整数那样的简单 对象 ),那么你必须使用切片操作符来取得
拷贝。

shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist # mylist is just another name pointing to the same object!
mylist = shoplist[:] # make a copy by doing a full slice

13.字符串

  • 1.自然字符串
如果你想要指示某些不需要如转义符那样的特别处理的字符串,那么你需要指定一个自 然字符串。自然字符串通过给字符串加上前缀r或R来指定。例如r"Newlines are indicated by \n"。
  • 2.使用三引号('''或""")
    利用三引号,你可以指示一个多行的字符串。你可以在三引号中自由的使用单引号和双
       引号。例如:
    '''
    This is a multi-line string. This is the first line. This is the second line.
    "What's your name?," I asked.
    He said "Bond, James Bond."
    '''
    
  • 3.转义符
    假设你想要在一个字符串中包含一个单引号('),那么你该怎么指示这个字符串?例 如,这个字符串是What's your name?。你肯定不会用'What's your name?'来指示它,因为 Python会弄不明白这个字符串从何处开始,何处结束。所以,你需要指明单引号而不是 字符串的结尾。可以通过 转义符 来完成这个任务。你用\'来指示单引号——注意这个反 斜杠。现在你可以把字符串表示为'What\'s your name?'。
    

另一个表示这个特别的字符串的方法是"What's your name?",即用双引号。类似地,要在 双引号字符串中使用双引号本身的时候,也可以借助于转义符。另外,你可以用转义符 \来指示反斜杠本身。
值得注意的一件事是,在一个字符串中,行末的单独一个反斜杠表示字符串在下一行继
续,而不是开始一个新的行。例如:
"This is the first sentence.\ This is the second sentence."
等价于"This is the first sentence. This is the second sentence."
````

delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print delimiter.join(mylist) 

Brazil_*_Russia_*_India_*_China


name = 'Swaroop' 
if name.startswith('Swa'):
if 'a' in name:

14.面向对象

  • 1.self

类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称,但是
在调用这个方法的时候你不为这个参数赋值,Python会提供这个值。这个特别的变量指对象本
身,按照惯例它的名称是self。
````

  • 2.__init__方法
__init__方法在类的一个对象被建立时,马上运行。这个方法可以用来对你的对象做一些你希
望的 初始化 。注意,这个名称的开始和结尾都是双下划线。

例如:

  • 3.类与对象方法
    请参考:

  • 4.继承 ,有空再看

15. 画图

import matplotlib.pyplot as plt

plt.figure(figsize=(8,6))
plt.plot(sp500['Close'])
plt.grid(True)
plt.xlabel('time step')
plt.ylabel('index level')
plt.show()

16.函数式编程

在 Python 级别上尽可能避免循环被视为"好的习惯".列表推到和函数式编程工具(如 map, filter 和 reduce) 提供了编写紧凑(一般来说也更易于理解)的无循环代码的手段. lambda 或者匿名函数也是这方面的强大工具.

def f(x):
    return x ** 2
print f(2)
def even(x):
    return x % 2 == 0
print even(3)

print map(even, range(10))
print filter(even, range(15))

print map(lambda x: x ** 2, range(10))
def make_repeater(n):
    return lambda s:s*n
twice = make_repeater(2)
print twice('word')

print reduce(lambda x, y:x+y, range(10))

17.写文件

 lines = open('/Users/zzy/PycharmProjects/testQuantification/source/ex.txt', 'r').readlines()
 lines = [line.replace(' ','') for line in lines]
 print lines[:6],

 for line in lines[3883:3890]:
    print line[41:],

 new_file = open('/Users/zzy/PycharmProjects/testQuantification/source/es50.txt', 'w')
 new_file.writelines('date' + lines[3][:-1] + ';DEL' + lines[3][-1])
 new_file.writelines(lines[4:])
 new_file.close()

110.注意

1.应该避免使用from..import而使用import语句,因为这样可以使你的程序更加易读,也可以避免名称的冲突。
2.  在print语句的结尾使用了一个 逗号 来消除每个print语句自动打印的换行符。

   for item in shoplist:
        print item,

3. 是%s表示字符串或%d表示整数。

4. pass 代表一个空的语句块
posted @ 2016-08-09 11:26  农民阿姨  阅读(383)  评论(0编辑  收藏  举报