python 相关

 

规范:

在Python中, pydoc以及单元测试要求模块必须是可导入的. 你的代码应该在执行主程序前总是检查 if __name__ == '__main__' , 这样当模块被导入时主程序就不会被执行.

def main():
      ...

if __name__ == '__main__':
    main()

 

终端执行python命令方法:

chmod 777 main.py 给程序可执行的许可

./main.py

在Python中有4种类型的数——整数、长整数、浮点数和复数。

字符串:单引号' ' 双引号" " 三引号 ' ' ' ' ' ' / """ """ 使用三引号时,可包括多行字符串,引号里面可随意使用单引号和双引号。

转义字符:"\" 表示\后面是一个单引号,不然会出错 : 'What\'s your name?'

行末使用\ 代表在下一行接着继续,而不是开启新的一行

 

缩进很重要

运算符和用法:

 

运算符优先级:

 

 

结合规律

运算符通常由左向右结合,即具有相同优先级的运算符按照从左向右的顺序计算。例如,2 + 3 + 4被 计算成(2 + 3) + 4。一些如赋值运算符那样的运算符是由右向左结合的,即a = b = c被处理为a = (b = c)。

 

输入一个int的值

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

 

if ** :

elif ** :

else:

print ' **'

加参数:print 'x is', x

while ** :

break continue

 

定义函数:(*代表空格缩进)

def sayhello() :

****print 'hello python'

sayhello()

def printmax(a,b):

****if a>b:

********print '...'

****else: a<b:

********print '...'

printmax(3,2)

x=4

y=5

printmax(x,y)

global关键字

声明变量为全局变量

如图程序输出为:

x is 50

Changed global x to 2

Value of x is 2

默认参数值:

def test(mesg,count=2):
    print mesg*count
test('hello')
test('hello',5)

输出: hellohello

hellohellohellohellohello

关键参数: def func(a,b=2,c=3)

func(3, 7) a=3 b=7 c=3

func(25,c=24) a=25,b=2,c=24

func(c=50,a=100) a=100,b=2,c=50

return 关键字

DocStrings 文档字符串 作用是:在函数的第一行字符串视为文档字符串。

def printMax(x, y):
    '''Prints the maximum of two numbers.
    The two values must be integers.'''
    x = int(x)
    y = int(y)
    if x > y:
        print x, 'is maximum'						
    else:												 
        print y, 'is maximum'						    
printMax(3, 5)
print printMax.__doc__



输出:5 is maximum
Prints the maximum of two numbers.
 The two values must be integers.

 

import / from..import

导入自己的模块: import name 导入模块名为name的模块

使用: name.funname()

from name import funname 导入模块中指定的函数

dir()函数

列出模块定义的标识符。标识符有函数、类和变量。

list

listname=['..','..','..']

len(listname) list的长度

for item in listname

print item, 遍历输入list

listname.append('..') 添加元素

listname.sort() 排序

listname[0] 获取第一个元素 del listname[0] 删除第一个元素

 

元组 元组类似list但是是不可变的

yzname=('1a','1b','1c')

len(yzname) 输出:3

yzname2=('2d','2e',yzname)

len(yzname2) 输出:3

print yzname2 输出:('2d','2e',('1a','1b','1c'))

print yzname2[2] 输出:('1a','1b','1c')

print yzname[2][2] 输出:'1c'

 

元组与打印语句

age = 22

name = 'Swaroop'

print '%s is %d years old' % (name, age)

print 'Why is %s playing with that python?' % name

结果:Swaroop is 22 years old

Why is Swaroop playing with that python?

 

字典dict name={key1:value1,key2:value2}

key不能重复,不能更改

添加元素: name[key3]=value3 删除元素: del name[key1]

计算元素数:len(name)

循环遍历:for name, address in ab.items():

print 'Contact %s at %s' % (name, address)

 

序列:

shoplist = ['apple', 'mango', 'carrot', 'banana']

shoplist[0] apple shoplist[1] mango

shoplist[-1] banana shoplist[-2] carrot

shoplist[1:3] mango,carrot shoplist[2:] carrot ,banana 索引从0开始,包含左,不包含右

shoplist[1:-1] mango,carrot shoplist[:] apple,mango,carrot,banana

name = 'swaroop'

name[1:3] wa name[2:] aroop

name[1:-1] waroo name[:] swaroop

 

参考

当你创建一个对象并给它赋一个变量的时候,这个变量仅仅 参考 那个对象,而不是表示这个对象本身!也 就是说,变量名指向你计算机中存储那个对象的内存。这被称作名称到对象的绑定。参考值的改变并不影响对象值的改变,对象值的改变必然影响参考值的改变。

shoplist = ['apple', 'mango', 'carrot', 'banana']

mylist = shoplist

字符串的方法:

name = 'Swaroop'

if name.startswith('Swa'): ture

if 'a' in name: true

if name.find('war') != -1: true

sjh = '_*_'

mylist = ['Brazil', 'Russia', 'India', 'China']

print sjh.join(mylist) 输出:Brazil_*_Russia_*_India_*_China

程序实例:

1.场景:重要文件需要备份。

要求:需要备份的文件和目录由一个列表指定。

备份应该保存在主备份目录中。

文件备份成一个zip文件。

zip存档的名称是当前的日期和时间。

#!usr/bin/env python
# -*- coding:UTF-8 -*-
import os
import time

source = '/Users/sunjiahui/PycharmProjects/test'    #需要备份文件的路径
target_dir = '/Users/sunjiahui/testzip/'               #备份后文件的路径
today = target_dir + time.strftime('%Y%m%d')    #获取当天日期,组成备份文件自路径
now = time.strftime('%H%M%S')       #获取时间
if not os.path.exists(today):       #判断备份文件子路径是否创建,未创建则创建
    os.mkdir(today)
    print 'Successfully created directory', today
target = today + os.sep + now + '.zip'          #指定备份后的文件路径以及文件名,文件后缀名
zip_command="zip -qr '%s' %s" % (target,source)        #组成可执行的shell命令
if os.system(zip_command) == 0:             #执行shell命令并判断是否执行成功
    print 'Successful backup to', target
else:
    print 'Backup FAILED'

 

python面向对象部分:self “相当于”java中的this,但并不是this

 

#!/usr/bin/python
# Filename: method.py
class Person:
def sayHi (self):
print 'Hello, how are you?' 
p = Person()											
p.sayHi()											

创建一个类

 输出:Hello, how are you?

 

__init__方法 给对象初始化

class Person:
def __init__(self, name):
self.name = name 
def sayHi (self):
print 'Hello, my name is', self.name 
p = Person('Swaroop')
p.sayHi()

 

继承 将父类名加括号写在子类名后面

子类初始化时,在__init__方法第一行先初始化父类:父类名.__init__(父类参数)

 

输入/输出 raw_input和print

文件

通过创建一个file类的对象来打开一个文件,分别使用file类 的read、readline或write方法来恰当地读写文件。最后调用close方法结束对文件的使用

#!/usr/bin/python
# -*- coding:UTF-8 -*-
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python! '''
f = file('/Users/sunjiahui/testzip/poem.txt', 'w')   #写入poemtxt  'w'写模式
f.write(poem)
f.close()       # close the file
f = file('/Users/sunjiahui/testzip/poem.txt')    #读取文件  'r'  读模式(默认)
while True:
    line = f.readline()
    if len(line) == 0: # 判断文件是否输入结束
        break
    print line,
f.close()

如果不使用本地绝对路径,则将会在项目下创建poem.txt

存储器 pickle/cpickle cpickle使用C编写,速度比前者快1000倍,用法相同

可以在一个文件中储存任何Python对象,之后你 又可以把它完整无缺地取出来。这被称为 持久地 储存对象。

import cPickle as p

shoplistfile = 'shoplist.data'

shoplist = ['apple', 'mango', 'carrot']

f = file(shoplistfile, 'w')

p.dump(shoplist, f) 存

storedlist = p.load(f) 取

异常

处理异常:try..except

举例:

import sys
try:
s = raw_input('Enter something --> ') 
except EOFError:
print '\n具体异常'
sys.exit()
except:
print '\n总异常.'

自定义异常类:

class ShortInputException(Exception):
 '''A user-defined exception class.''' 
def __init__(self, length, atleast):
Exception.__init__(self) 
self.length = length 
self.atleast = atleast

try..finally 与java的finally一样

特殊的方法

列表综合

举例: 想把原来列表中大于2的数扩大二倍,并成为一个新的列表(不包括不满足条件的)

listone = [2, 3, 4]

listtwo = [2*i for i in listone if i > 2] 输出:[6,8]

在函数中接收元组和列表 使用* 或者 **

def powersum(power, *args):
'''Return the sum of each argument raised to specified power.'''
total = 0
for i in args:
total += pow(i, power) 
return total
powersum(2, 3, 4) 					#输出:25
powersum(2, 10)						#输出:100

由于在args变量前有*前缀,所有多余的函数参数都会作为一个元组存储在args中。如果使用的是**前 缀,多余的参数则会被认为是一个字典的键/值对。

lambda形式

lambda语句被用来创建新的函数对象,并且在运行时返回它们。

def make_repeater(n): 
return lambda s: s*n
twice = make_repeater(2)
print twice('word')						#输出:wordword
 print twice(5)                       #输出:10

exec和eval语句

exec语句用来执行储存在字符串或文件中的Python语句。例如,我们可以在运行时生成一个包含Python 代码的字符串,然后使用exec语句执行这些语句。eval语句用来计算存储在字符串中的有效Python表达式。

exec 'print "Hello World"' 输出:Hello World

eval('2*3') 输出:6

assert语句

assert语句用来声明某个条件是真的。例如,如果你非常确信某个你使用的列表中至少有一个元素,而 你想要检验这一点,并且在它非真的时候引发一个错误,那么assert语句是应用在这种情形下的理想语 句。当assert语句失败的时候,会引发一个AssertionError。

mylist = ['item']

assert len(mylist) >= 1

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值