python简要

python用冒号代替{}开启语句块

  1. /usr/bin/python 加在脚本的头部, ./脚本

  2. help("str") : 查看命令帮助

  3. '''三引号可以打印换行字符串
    print(' ') 可以打印换行

  4. 表达式打印
    s = 10
    print 'asdasd',s

  5. if循环,python没有switch,取而代之的是字典

#!/usr/bin/python                                                                                   
guess = int(raw_input('Enter number ...'))
if guess==1:
    print '1'
elif guess ==2:
    print '2'
else:
    print '3'

  1. while循环,有可选的else从句
#!/usr/bin/python                                                                                   
flag = True
num=23
while flag:
    guess = int(raw_input('enter number'))
    if guess == num:
        print 'yes'
        flag = False
    elif guess>num:
        print 'big'
    else:
        print 'small'
else:
    print 'loop end'
  1. for
for i in range(1,5):
    print i

函数 :

#!/usr/bin/python                                                                                   
def getMax(a,b):
    if a>b:
        print a,'is max'
    else:
        print b,'is max'
 
getMax(1,'as')
 
67 

函数内部声明global变量,让该变量从上下文钟获取变量值

函数的返回值需要return声明,如果不声明,默认在在结尾return None

模块

  1. sys模块带有环境相关的参数
import sys
print 'console arg:'
for i in sys.argv:
    print i

print 'python path is',sys.path


列出模块的属性方法 : dir
删除模块的属性方法 : del

列表 : [elem1,elem2]
del list[index]:删除列表的元素
len(listname):list长度

applist = ['apple','orange','carrot']
print applist

for i in applist:
    print i

del applist[0]         #['orange', 'carrot']
applist.append('wo')   #['orange', 'carrot', 'wo']
print applist
applist.sort()         #['carrot', 'orange']
print applist

元祖:不可变的列表

zoo = ['wolf',1]

print zoo
print len(zoo)

newzoo = [2,3,zoo]  #2
print newzoo[2][1]  #1

占位打印

age = 22
name = 'zhangsan'

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

字典:map
{k:v,k2:v2}

map1 = {"zs":24,"lisi":25}
print map1["zs"]   #24
del map1["zs"]
print map1         #{'lisi': 25}

for name,age in map1.items():
    print '%s is %d' % (name,age)      #lisi is 25

if map1.has_key('lisi'):
    print 'lisi is %d' % map1['lisi']  #lisi is 25

序列:元组和列表都是序列
序列2中操作:
(1)索引操作:用脚标获取元素
(2)切片操作:2个角标确定切片,a:b,表示从a开始,到b结束,不包含b角标的子序列

python备份文件

import time
import os

source = ['/home/swaroop/byte','/home/swaroop/bin']
target_dir = '/mnt/e/backup/'
today = target_dir + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')   #文件明中加上注释
comment = raw_input('Enter a comment --> ')

if len(comment)==0:
    target = today + os.sep + now + '.zip'
else:
    target = today + os.sep + now + '_' + comment.replace('','_') + 'zip'

if not os.path.exists(today):
    os.mkdir(today)

zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))

if os.system(zip_command)==0:
    print 'Successful backup to', target
else:
    print 'Backup FAILED'

假设一个类MyClass,他的对象MyObject
类中的方法的第一个参数必须是self对象,即使是空参函数,也要有self
当对象调用MyObject.method(arg1, arg2)时,python会自动转换为MyClass.method(MyObject, arg1,arg2)

构造方法:
init(self,param):self.param = param

消亡方法
del

# -*- coding: utf-8 -*
class Person:
    # 类变量
    population = 0
    # 对象变量
    def __init__(self, name):   #对象初始化时调用
        self.name = name
        print '(Initializing %s)' % self.name
        Person.population += 1

    def __del__(self):          # 对象消亡,清空内存时使用
        print '%s says bye.' % self.name
        Person.population -= 1
        if Person.population == 0:
            print 'I am the last one.'
        else:
            print 'There are still %d people left.' % Person.population

    def sayHi(self):
        print 'Hi, my name is %s.' % self.name

    def howMany(self):
        if Person.population == 1:
            print 'I am the only person here.'
        else:
            print 'We have %d persons here.' % Person.population

swaroop = Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()

继承
把父类的类名作为一个元组放在声明子类的后面

class SchoolMember:
    '''Represents any school member.'''
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print '(Initialized SchoolMember: %s)' % self.name

    def tell(self):
        '''Tell my details.'''
        print 'Name:"%s" Age:"%s"' % (self.name, self.age)


class Teacher(SchoolMember):
    '''Represents a teacher.'''
    def __init__(self, name, age, salary):
        SchoolMember.__init__(self, name, age)
        self.salary = salary
        print '(Initialized Teacher: %s)' % self.name

    def tell(self):
        SchoolMember.tell(self)
        print 'Salary: "%d"' % self.salary


class Student(SchoolMember):
    '''Represents a student.'''
    def __init__(self, name, age, marks):
        SchoolMember.__init__(self, name, age)
        self.marks = marks
        print '(Initialized Student: %s)' % self.name

    def tell(self):
        SchoolMember.tell(self)
        print 'Marks: "%d"' % self.marks

t = Teacher('Mrs. Shrividya', 40, 30000)
s = Student('Swaroop', 22, 75)
print # prints a blank line
members = [t, s]
for member in members:
    member.tell() # works for both Teachers and Students

异常
try:
except EOFError:
except:
相当于: try .. catch .. catch ..

try:
finally:

eval("2+3")
5

exec 'print "hello world"'
hello world

原文地址:https://www.cnblogs.com/72808ljup/p/5671110.html