python語言基礎,讓入門更簡單

Python 基礎

前言:python基礎類型和文件操作,python入門的最佳選擇。

1.Python變量和數據類型

2.Python中輸入輸出
2.1.基本形式輸出
print();

2.2.格式化輸出
print(“我芳齡18歲”);
print(“我芳齡20歲”);
print(“我芳齡22歲”);

2.3.換行輸出

2.4.基本輸入
a=input(“sss”)
3.運算符
python支持以下幾種運算符

3.1.算術運算符

  • 加 +
  • 減 -
  • 乘 *
  • 除 /
  • 取整數 //
  • 取餘 %
  • 冪 **

3.2.賦值運算符
= 把右邊的結果,給左邊的變量
a,b=1,2

3.3.複合賦值運算符

3.4.比較運算符

3.5.邏輯運算符

3.5.1.and
兩個都爲真,則爲真。
從左到右計算表達式,若所有值均爲真,則返回最後一個值,若存在假,返回第一個假值

3.5.2.or
當有一個條件爲真時,該條件即爲真。
從左到右計算表達式,若爲真,則返回第一個真值,若爲假,則返回第二個假值

3.5.3.not
not True —>False
not False—>True

4.條件判斷
4.1.if 判斷語句
if 比較運算符
案例: 判斷是否是成年人

if 邏輯運算符
* or
案例: 有房子或者有車,都可以
* and
案例: 是否鑽石王老五
* not
案例:判斷數字範圍
a = 30
if not (a>0 and a<=50):
print(“在0到50之間…”)

4.2.if else判斷
高富帥案例

4.3.if elif else 判斷
案例:三好學生評選

5.while循環判斷
求偶數的和

6.for循環操作
和while循環類似,for循環可以完成循環的操作
在python中,for循環可以遍歷任何序列的項目,如一個列表或者一個字符串等。

6.1.for循環遍歷字符串
輸入任意一個字符串,將字符串中字母打印出來

6.2.for循環計算1-100的和

7.字符串切片
切片概念:切片是對操作的對象截取一部分的操作,字符串,列表,元組都支持切片操作。切片的語法[起始:結束:步長]

name[0:5]
name[1:5]
name[:3] 從0到3
name[::2] 從頭到尾 2步數
name[4:1] 沒有內容
name[5:1:2]
name[4:1:-1]

案例:字符串反轉
[::-1]

8.字符串常見操作

8.1.find
find 檢測str是否包含在mystr中,如果是返回開始索引值,否則返回-1

8.2.rfind
rfind 類似於find,不過是從右邊開始找。

8.3.count
檢測mystr中出現str的次數

8.4.replace 替換
把mystr中的str1替換成str2,如果count指定,則替換不超過count次

8.5.split
name.split(",") 全部分隔
name.split(“hello”,1) 分隔第一個

t

8.6.startswith
以什麼進行開頭,如果是,返回True,如果不是,返回False。

8.7.endswith

8.8.strip
name=" hello world "

去除左右空格

8.9.isalpha
判斷是否都是字母,如果是,返回True,如果不是,返回False

8.10.isdigit
判斷是否都是數字,如果是,返回True,如果不是,返回False
8.11.isalnum
判斷所有是否都是字母或數字,如果是返回True,如果不是返回False
8.12.len() 非字符串方法
獲取字符串(列表)長度

9.列表 list
存儲一系列名字,存儲一些新聞條目,可以使用列表的格式。

9.1.列表的基本形式
names=[“張三”,“李四”,“王五”,“趙六”]
ages=[1,4,6,9]
s=[1,“哈哈”,“呵呵”,True]

9.2.獲取列表中元素
9.2.1.根據下標(索引)獲取
print(names[0])
print(names[1])
print(names[-1])
9.2.2.切片操作
print(names[0:3])#索引0-2的元素
print(names[0::2])#步長爲2,索引0-2的元素
print(names[::-1])#步長爲1,倒序遍歷
print(names[3:0:-1])#步長爲-1,倒序遍歷,索引3 2 1

9.3.列表的循環遍歷
9.3.1.for循環
#列表
names=[“張三”,“李四”,“王五”,“趙六”]
for name in names:
print(name)

9.4.列表常見的操作
9.4.1. append 增加元素
9.4.2.extend 可以將另外一個集合中的元素逐一添加到列表中
9.4.3.insert 在指定位置插入元素
insert(index,object) 在指定位置處插入元素object
9.4.4.修改元素
修改元素的時候,只需要獲取到對應的下標,就可以重新賦值,就完成了修改
nums[1]=100

9.4.5.查找元素 in not in
python中常見的查找方法爲:
in(存在),如果存在那麼結果爲True,否則爲False
not in (不存在),如果不存在那個結果爲True,否則爲False

姓名查找案例:
#列表
names=[“張三”,“李四”,“王五”]
name=input(“請輸入要查詢的姓名?\n”)
if name in names:
print(“存在”)
else:
print(“不存在”)

9.4.6.index count
index 獲取某元素在列表中的索引值
count 獲取元素在列表中出現的次數

#列表
names=[“張三”,“李四”,“王五”,“李四”,“王五”]
name=“李四”
print(names.index(name))#查找索引
print(names.count(name))#查找個數

9.4.7.刪除元素
del:根據元素下標進行刪除
starNames=[“張三”,“李四”,“王五”,“李四”,“王五”]
#del 根據下標進行刪除
del starNames[2]
print(starNames) #[“張三”,“李四”,“李四”,“王五”]

remove:根據元素的值進行刪除
starNames.remove(“李四”)#[“張三”,“李四”]
print(starNames)

10.元組 tuple
python中元組和列表類似,不同之處在於元組的元素不能更改,元組使用小括號,list使用中括號。

tuple=(“abc”,“bcd”,“efg”)

10.1.根據下標和切片獲取元素
print(tuple[0]) #abc
print(tuple[0:1]) #abc bcd efg

10.2.元組中內置函數count index
tuple=(“abc”,“bcd”,“efg”,“bcd”)
print(tuple.index(“abc”)) #0
print(tuple.count(“bcd”)) #2

11.字典介紹

key value(鍵值對)形式數據對應,比如 name:張三 age:18 sex:男 JSON

info={“name”:“張三”,“age”:18,“sex”:“男”}

11.1.元素獲取
print(info[“name”])如果元素沒有會報錯誤
print(info.get(“name”)) #
#print(info.get(“xx”))

11.2.字典的增刪改操作
11.2.1.修改元素
字典中每個元素都是可修改的,只要通過key找到,既可以修改Demo
info[“name”]=“李四”
11.2.2.添加元素
想要添加元素,只需要指定key 指定 value就可以

info[“address”]=“北京”

11.2.3.刪除元素
對字典進行刪除操作,有以下兩種方式:
del info[] 指定要刪除的元素

del info[“name”]

clear 清空元素
info.clear()

11.3.字典的常見操作
11.3.1.len() 獲取字典的長度

11.3.2.
keys() 獲取字典的所有key 列表

print(info.keys())

11.3.3.values 獲取字典的所有values 列表

print(info.values())

11.3.4.items 返回一個包含所有元組(鍵,值)的列表

print(info.items())

11.4.字典的遍歷

11.4.1.遍歷key
#遍歷key
for key in info.keys():
print(key)

11.4.2.遍歷value
#遍歷value
for value in info.values():
print(value)

11.4.3.遍歷items
#遍歷items
for item in info.items():
print(item)

11.4.4.遍歷key value
#遍歷key value
for key,value in info.items():
print(key,value)

12.函數定義、調用
12.1.定義函數的格式如下
def 函數名():
代碼

13.函數參數
13.1.定義帶有參數的函數:
def printSum(a,b):
print(a+b)

13.2.形式參數和實際參數
定義時小括號中的參數,用來接受參數用的,稱爲“形參”
調用時小括號中的參數,用來傳遞給函數用的,稱爲”實際參數”

13.3.缺省參數
默認有參數值的函數
def printInfo(name,age=23):
print(name,age)
printInfo(“張三”)

13.4.可變參數(一 元組類型)
def getSum(*args):
print(args)
sum=0
for i in args:
sum+=i
return sum
print(getSum(1,2,3,4))

13.5.可變參數(二 字典類型)
def printKeyValue(**kwargs):
print(kwargs)
getSum(m=6,n=10)

14.函數類型
無參數,無返回值
無參數,有返回值
有參數,無返回值
有參數,有返回值

14.1.無參數,無返回值的函數
案例:簡單操作,沒有參數,沒有返回值,簡單打印。

14.2.無參數,有返回值的函數
案例:比如獲取當前溫度。

15.主函數
if name == ‘main’:

16.文件打開與關閉
python中打開文件,可以使用open函數,可以打開一個已經存在的文件,或者創建一個新的文件。
open(文件名,訪問模式)
比如
#Python寫入內容
file=open(“test.txt”,“w”)
file.write(“哈哈哈”)
file.close()
16.1.文件訪問模式

17.文件備份
17.1.案例 將一個文本文件拷貝一份,並命名爲aa.py
import os
#打開源文件
f1=open(“text.txt”,“r+”)
f2=open(“aaa.txt”,“w+”)
for line in f1.readlines():
f2.write(line)
f1.close()
f2.close()

18.定義類
定義一個類,格式如下。
class 類名:
方法列表

18.1.定義一個car類,擁有移動的方法,鳴笛的方法(toot)
class Car:
def move(self):
print(“car在移動”)
def toot(self):
print(“car在鳴笛”)

18.2.定義對象
#創建car對象
bmw=Car()
bmw.color=“黑色”
bmw.wheelNum=4 #輪子數量
bmw.move()
bmw.toot()

print(bmw.color)
print(bmw.wheelNum)
19.__init__方法
19.1.使用方式

def init(self):
pass

19.2.__init__調用
def init(self):
print(“init__方法執行了”)
19.3.在_init__方法中進行屬性初始化
def init(self):
self.color=“黑色”
self.wheelNum=4
19.4.使用__init__方法傳遞參數
def init(self,newcolor,wheelNum):
self.color=newcolor
self.wheelNum=wheelNum

20.封裝
如果有一個對象,當需要對其進行屬性修改的時候,有兩種方法

對象名.屬性名=數據----->直接修改
對象名.方法名()----->間接修改

爲了更好的保存屬性安全,即不能隨意修改,一般的處理方法爲

將屬性定義爲私有屬性
添加一個可以調用的方法,供調用。

20.1.屬性封裝

def setAge(self,age):
if age>150 or age<0:
print(“年齡錯誤”)
else:
self.__age=age
def getAge(self):
return self.__age
20.2.方法私有
def __getHeart(self):
print(“把心臟逃出來看一看”)

20.3.總結:
私有的屬性,不能通過屬性直接調用,但是可以通過方法直接訪問

私有的方法,不能通過對象直接調用,只能內部調用。

21.繼承介紹以及單繼承
21.1.繼承概念
兒子繼承爹的財產

在程序中,繼承描述的是事物之間的所屬關係,例如貓和狗都屬於動物.

21.2.繼承特點

class Dog(object):
def init(self,name,color=“黃色”):
self.name=name
self.color=color
def run(self):
print("%s在跑着"%self.name)

class JinMao(Dog):
def setNewName(self,name):
self.name=name
def eat(self):
print("%s在吃飯,顏色是%s"%(self.name,self.color))

dog1=JinMao(“大黃”)
dog1.run()
dog1.setNewName(“小阿黃”)
dog1.eat()

說明:雖然子類沒有定義__init__方法,但是父類有,所以在子類繼承父類的時候這個方法被繼承了,所以只要創建子類的對象,就默認執行了這個init方法.

21.3.私有屬性的繼承
21.3.1.案例
class Person(object):
def init(self,name,color=“黃色”):
print(“父類的init方法”)
self.__name=name
self.color=color

def run(self):
    print("%s在跑着"%self.__name)

class HungPerson(Person):

def setNewName(self,name):
    self.name=name

def eat(self):
    print("%s在吃飯,膚色是%s"%(self.__name,self.color))

p1=HungPerson(“張三”)
p1.eat()

21.3.2.總結:

私有的屬性和方法,不能被子類繼承,也不能被訪問。
一般情況下,私有的屬性,方法是不對外公佈的,往往用來做內部的事情,起到安全的作用。

22.重寫父類方法及調用父類方法
class Dog(object):
def init(self,name,color=“黃”):
self.name=name
self.color=color
def play(self):
print(“玩尾巴”)

class JingBa(Dog):
def init(self,name):
super().init(name)

def play(self):
    super().play()
    print("%s顏色的%s抓老鼠"%(self.color,self.name))

d=JingBa(“京巴”)
d.play()
23.類屬性和對象屬性
類屬性就是類(類對象)所擁有的屬性。它被類和所有對象所擁有。對於共有類屬性,在類外可以通過類對象和實例對象訪問。

23.1.類屬性
class Dog(object):
name = “Tom”
__age = 10

print(Dog.name)#正確
print(Dog.__age)#錯誤

d=Dog()
print(d.name)#正確
print(d.__age)#錯誤

23.2.對象屬性
def init(self,name):

self.name=name

print(Dog.name)#Tom
d=Dog(“大黃”,19)
print(d.name)#大黃
print(d.getAge())
def getAge(self):
return self.__age
24.類方法方法
24.1.類方法
類方法,是類對象所擁有的方法,需要用修飾器@classmethod來標識其爲類方法

對於類方法,第一個參數通常是類對象本身

24.1.1.使用類方法調用類屬性

class Person(object):
country=“北京”
@classmethod
def getCountry(cls):
return cls.country;

print(Person.getCountry())
p=Person()
print(p.getCountry())

24.1.2.使用類方法修改類屬性
@classmethod
def setCountry(cls,name):
cls.country=name

Person.setCountry(“美國”)

25.異常介紹
當python檢測到一個錯誤時,解釋器就無法繼續執行了,反而出現一些錯誤提示,這就是所謂的“異常”。

算術異常
文件不存在異常
類型轉換異常

26.捕獲異常

try:
print(“test1=====”)
i=1/0
print(“test2=====”)
except ArithmeticError:
pass

程序捕獲異常之後,就看不到任何錯誤。

總結:把可能產生的錯誤放置到try中
把處理異常的代碼,放在except中

27.獲取異常信息描述
try:
print(“test1=====”)
i=1/0
print(“test2=====”)
except ArithmeticError as result:
print(result)

28.except捕獲多個異常
28.1.出現數學異常時捕獲
try:
print(“test1=====”)
i=1/0
print(“test2=====”)
except (ArithmeticError,IndexError) as result:
print(result)

print(“普通的打印”)
28.2.出現角標越界時捕獲
try:
print(“test1=====”)
#i=1/0
print(“test2=====”)
list=[1,2]
print(list[10])
except (ArithmeticError,IndexError) as result:
print(result)

print(“普通的打印”)

28.3.捕獲所有異常
try:
print(“test1=====”)
#i=1/0
print(“test2=====”)
list=[1,2]
print(list[10])
except Exception as result:
print(result)

print(“普通的打印”)
29.else
except Exception as result:
print(result)
else:
print(“沒有捕獲到異常,可開心了”)
29.1.try…finally
#案例:文件操作異常,文件關閉
try:
file=open(“aaa.txt”,“w”)
i=1/0
except Exception as result:
print(result)
finally:

file.close()
print("文件關閉")


30.異常拋出
#自己拋出異常
def testAge(age):
if age>150 or age<0:
raise Exception(“年齡範圍不對”)
testAge(199)
31.Python中模塊基本導入

模塊就好比是工具包,要想使用這個工具包的工具,就需要導入這個模塊。
在Python中用關鍵字import來引入模塊,比如要引入模塊(文件),math,就可以在文件最開始的地方用import math來引入。

31.1.格式:一 import module1,module2…
31.1.1.普通導入
當使用import語句,模塊內容就會被導入。
調用方式
模塊名稱.函數名()
import math
print(math.sqrt(10))
#print(sqrt(20)) 不能這樣寫
31.1.2.導包並改名

import math as HaHa
print(HaHa.ceil(10))

31.2.格式二 from 模塊名 import 函數名2,函數名3

31.2.1.from math import …導入函數
from math import sqrt
print(sqrt(10))

31.2.2.from math import *
from math import *
print(sqrt(10))
print(ceil(12.8))

32.Python數據庫編程前提
熟練使用sql語句的基礎上,開始使用python語言提供的模塊與mysql進行交互
這是我們在工作中大事要做的事
先學會sql是基礎,一定要熟練編寫sql語句

33.安裝引入模塊

安裝mysql模塊
pip install pymysql 3.6版本

在文件中引入模塊
import pymysql

34.Connection對象
用於建立與數據庫的連接
創建對象:調用connect()方法
conn=connect(參數列表)
參數host:連接的mysql主機,如果本機是’localhost’
參數port:連接的mysql主機的端口,默認是3306
參數db:數據庫的名稱
參數user:連接的用戶名
參數password:連接的密碼
參數charset:通信採用的編碼方式,默認是’gb2312’,要求與數據庫創建時指定的編碼一致,否則中文會亂碼

35.對象的方法
close()關閉連接
commit()事務,所以需要提交纔會生效
rollback()事務,放棄之前的操作
cursor()返回Cursor對象,用於執行sql語句並獲得結果
36.Cursor對象
執行sql語句
創建對象:調用Connection對象的cursor()方法
cursor1=conn.cursor()
36.1.對象的方法
close()關閉
execute(operation [, parameters ])執行語句,返回受影響的行數
fetchone()執行查詢語句時,獲取查詢結果集的第一個行數據,返回一個元組
fetchall()執行查詢時,獲取結果集的所有行,一行構成一個元組,再將這些元組裝入一個元組返回

37.增刪改
37.1.向數據庫中添加一條數據

if name == ‘main’:
#參數host:連接的mysql主機,如果本機是’localhost’
# 參數port:連接的mysql主機的端口,默認是3306
# 參數db:數據庫的名稱
# 參數user:連接的用戶名
# 參數password:連接的密碼
# 參數charset:通信採用的編碼方式,默認是’gb2312’,要求與數據庫創建時指定的編碼一致,否則中文會亂碼
connect=pymysql.connect(host=“localhost”, user=“root”, password=“root”, db=“mydb1”, port=3306, charset=“utf8”)
#獲取連接的遊標
cursor=connect.cursor()
#定義sql語句
sql1=“insert into student values(0,‘吼吼’,‘男’)”
cursor.execute(sql1)
#提交
connect.commit()
#關閉遊標
cursor.close()
#關閉連接
connect.close()

37.2.修改
sql1=“update student set sex=‘女’ where name=‘zhangsan’”

37.3.刪除
sql1=“delete from student where name=‘zhangsan’”

38.參數化操作
name=input(“請輸入要添加的姓名:\n”)
sex=input(“請輸入要添加的性別:\n”)
parmas=[name,sex]
#定義sql語句
sql1=“insert into student values(0,%s,%s)”
cursor.execute(sql1,parmas)

39.查詢操作
39.1.查詢一行數據
cursor=connect.cursor()
sql=“select * from student where id=2”
cursor.execute(sql)
#獲取一個
result=cursor.fetchone()
print(result)

39.2.查詢所有數據
cursor=connect.cursor()
sql=“select * from student”
cursor.execute(sql)
#獲取一個
result=cursor.fetchall()
for r in result:
print®

39.3.查詢多行數據
#獲取多個
result=cursor.fetchmany(3)

40.封裝操作數據庫工具類

觀察前面的文件發現,除了sql語句及參數不同,其它語句都是一樣的
創建MysqlHelper.py文件,定義類
增加(Create)、讀取查詢(Retrieve)、更新(Update)和刪除(Delete)

encoding=utf8

import pymysql
import pymysql.cursors
class MysqlHelper():
def init(self, host=“localhost”, port=3306, db="", user=“root”, password=“root”, charset=“utf8”):
self.host = host
self.port = port
self.db = db
self.user = user
self.password = password
self.charset = charset

# 獲取連接並獲取cursor
def connect(self):
    self.conn = pymysql.connect(host=self.host, port=self.port, db=self.db, user=self.user, password=self.password,
                                charset=self.charset)
    self.cursor = self.conn.cursor()

def close(self):
    self.cursor.close()
    self.conn.close()

def cud(self, sql, params=()):
    count = 0
    # try:
    # 先連接一把
    self.connect()
    count = self.cursor.execute(sql, params)
    self.conn.commit()

# except Exception as result:
#     print(result)
    return count


def getOne(self,sql,params=()):
    result = None
    try:
        self.connect()
        self.cursor.execute(sql,params)
        result = self.cursor.fetchone()
        self.conn.commit()
        self.close()
    except Exception as r:
        print(r)
    return result


def getAll(self, sql, param=()):
    result = None
    try:
        self.connect()
        self.cursor.execute(sql, param)
        result = self.cursor.fetchall()
        self.conn.commit()
        self.close()
    except Exception as r:
        print(r)
    return result

40.1.測試
class SQLTest(unittest.TestCase):
def testAdd(self):
mysqlHelper=MysqlHelper(db=“mydb1”)
mysqlHelper.cud(“insert into student (name,sex) values(%s,%s)”,params=(“zhangsan”,“男”))

def testUpdate(self):
    mysqlHelper = MysqlHelper(db="mydb1")
    mysqlHelper.cud("update student set sex =%s where id <%s",params=("男",10))

def testFetchOne(self):
    mysqlHelper = MysqlHelper(db="mydb1")
    result=mysqlHelper.getOne("select * from student where id=%s",params=(4))
    print(result)

def testFetchAll(self):
    mysqlHelper = MysqlHelper(db="mydb1")
    result = mysqlHelper.getAll("select * from student")
    print(result)

if name == ‘main’:
unittest.main()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章