最近要用到一些Python的東西,開始學習一些基礎東西,做以記錄。
Python特點總結
1、每個語句佔一行,結尾沒有‘;’,
2、# 是行註釋
3、邏輯層次用縮進來區分,每個層次4個空格
4、沒有‘{}’,一個語句塊實在第一行末尾加一個‘:’
函數、類的定義,for,if,while語句塊等
總的來說Python對格式要求十分嚴格
#下面定義了一個函數
def printSomething():
"""2 的3次冪"""
a = 2 **3
a = 3;
b=2;
#print a>b;
"""強制取整"""
#print 7.0 //2;
#函數調用
printSomething()
Python數據類型
列表類型:
#定義一個列表
a = [1,4,3,2,1]
#在列表末尾添加一個元素
a.append(5)
for item in a:
print item
"""截取列表"""
print a[0:3]
del語句
#刪除list中的指定元素:
b = [1, 2, 3, 'fss']
del b[0]
元組類型
#元組不能增加或者刪除元素,一經創建就不能改變
(1,"123",45)
(2)#這不是元組,依舊只是常量2
字典:
dict={
"123":123,
456:"abc"
}
a={"123":123, 456:"abc"}
a["123"] == 123
a.keys()=["123",456]
a.values()=[123,"abc"]
get()語法:
dict.get(key, default=None)
參數:
下面是詳細參數:
key:key在字典中查找。
default:在key不存在的情況下返回值None。也可以指定默認值
字符串:
#以下四個字符串結果相同
a="hello python"
a="hello%s"%"python"
a="%s%s"%("hello","python")
a="%(verb)s%(name)s"%{"verb":"hello", "name":"python"}
Python中函數可以返回多個值
相當於返回一個元組
def returnSth(a,b,c=4):
return a,b-c
n1,n2=returnSth(2,9)
print n1,n2
Python模塊
每一個模塊也就意味着是一個包,要用到這個模塊裏的內容就要先導入;
一個模塊所在文件夾中必須有一個命名__init__.py
的文件,文件內容可以爲空,但不許存在。
格式爲:from 文件夾.文件 import 要導入的函數或者類名
當需要返回上一級目錄時,在文件夾名前面加一個點“.”。
Python面向對象
以一個實例說明類的定義:
#python2中需要object,,而3中是不需要的
class student(object):
sex = "man"
#這個函數名字是固定的,且必須存在,相當於有參構造函數,
#第一個參數必須是self(指向其本身),後面是屬性
def __init__(self,stuName,age):
self.stuName = stuName
self.age = age
#類中的方法第一個參數必須都是self
def growUp(self):
self.age += 1
def printInfo(self):
self.sex="famle"
print("%s is a %s, and %s years old"%(self.stuName, self.sex, self.age))
#類的繼承;()中是所繼承的父類的名稱
class monitor(student):
def __init__(self,stuName,age,career):
#super()中的參數只在Python2中存在
super(monitor,self).__init__(stuName,age)
self.career = career
def printCareer(self):
print("He/She is%s"%self.career)
#其他文件使用時:
from stuClass.students import student
from stuClass.students import monitor
stu = student("張士誠",123)
stu.growUp()
stu.printInfo()
mon = monitor("李四光",32,"scientist")
mon.printInfo()
mon.printCareer()
Python文件操作
#第二個參數有三種,r(read)/w(writ,並且文件清空後重新寫入)/a(append,直接在打開的文件後面添加)
f= file(src,'a')#也可用open函數,用法相同
f.write(content)
f.close()
#使用with時 不再需要手動關閉文件流
#沒有第二個參數時,默認爲讀取
with open(src) as f1:
while True:
line = f1.readline()
if len(line)== 0:
break;
#不想print之後換行就在最後加一個‘,’
print line,