一、基础语法
- 缩进: 缩进指的是代码行开头的空格。在其他编程语言中,代码缩进仅出于可读性的考虑,而 Python 中的缩进非常重要。Python 使用缩进来指示代码块。空格数取决于程序员,但至少需要一个。必须在同一代码块中使用相同数量的空格,否则 Python 会出错;
- 变量:Python 没有声明变量的命令。变量是在为其赋值时创建的;
- 注释:Python 实际上没有多行注释的语法。要添加多行注释,可以为每行插入一个 #;由于 Python 将忽略未分配给变量的字符串文字,因此可以在代码中添加多行字符串(三引号),并在其中添加注释;
二、Python基础
1. 变量:
#变量在赋值时创建
x = 1 ;
y = 2 ;
print(x);
print(y);
#变量不需要类型的声明,可以在设置后进行修改
x = 1 ;
x = "string" ;
print(x);
**#命名规则:
#变量名必须以字母或下划线字符开头
#变量名称不能以数字开头
#变量名只能包含字母数字字符和下划线(A-z、0-9 和 _)
#变量名称区分大小写(age、Age 和 AGE 是三个不同的变量)**
#一行为多个变量赋值
x , y , z = "red","black","pick"
x , y , z = "green"
#输出变量【数字+字符串会报错】
x = "world"
print("hello" + x)
#全局变量
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
#在函数内部创建一个与全局变量同名的变量
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
#global 关键字【将函数内创建全局变量】
def mytest():
global x
x = "lalala"
mytest()
print(x)
#在函数内部更改全局变量的值,用global
2 . 数据类型
类型 | 值 |
---|---|
文本类型 | str |
数值类型 | int , float , complex |
序列类型 | list , tuple , range |
映射类型 | dict |
集合类型 | set , frozenset |
布尔类型 | bool |
二进制类型 | bytes , bytearray , memoryview |
#获取数据类型
x = 1
print(type(x))
x = ["aa"] #list
x = ("aa") #tuple
x = {"aa"} #set
3. 数字
x = 10
y = 1.2
z = 1j
a = float(x)
b = int(y)
c = complex(z)
#无法将复数转换为其他数字类型。
#随机数
#没有random()函数来创建随机数,但是又内置模块,可用于生成随机数
import random
print(random.randrange(1,10)
- 字符串
a = "hello world"
print (a)
a =""" 多行数据"""
print(a)
a = "aaaaaa"
print(a[1])
print(a[1:2])
print(a[-4:-1])
print(len(a))
a=" aaa,sss"
print(a.strip()) #将会返回字符串,去掉空格
print(a.lower()) #返回小写字符
print(a.upper())#返回大写字符
a = "aaaaa"
print(a.replace("sss,ss"))
print(a.split(" , ")) #返回['sss','ss']
b= "d" in a
print (b) #检查是否存在d
age = 11
txt = "My name is aa,and i am {}"
print(txt.format(age)) #format 可任意接受不限数量的参数
- bool类型
1.当对数字使用bool函数时,0返回假(False),任何其他值都返回真。
bool(0)
False
bool(1)
True
bool(-1)
True
bool(21334)
True
2.当对字符串使用bool函数时,对于没有值的字符串(也就是None或者空字符串)返回False,否则返回True。
>>> bool('')
False
>>> bool(None)
False
>>> bool('asd')
True
>>> bool('hello')
True
3.bool函数对于空的列表,字典和元祖返回False,否则返回True。
>>> a = []
>>> bool(a)
False
>>> a.append(1)
>>> bool(a)
True
4.用bool函数来判断一个值是否已经被设置。
>>> x = raw_input('Please enter a number :')
Please enter a number :
>>> bool(x.strip())
False
>>> x = raw_input('Please enter a number :')
Please enter a number :4
>>> bool(x.strip())
True
- 列表(用方括号进行编写)
list = ["aaa","sss","ddd"]
print(list[0])
print(list[-1]) #输出ddd
print(list[2:4])
list.append("fff")
print(list)#添加项目
list.insert(1,"ggg")
print(list) #在指定位置添加
list.clear()
print(list)
list1 = ["a","s","d"]
list2 = ["q","w","e"]
list3 = list1 + list2
print(list3)
for x in list2:
list1.append(x)
print(list1)
- 元组(用圆括号进行编写)
【注:元组创建后无法添加或删除项目,不可改变;元组中仅有一个项目时,在该项目后也要添加逗号;元组的删除用del】 - 集合(用花括号进行编写;集合时无序的,无法用索引显示;集合创建后无法更改项目,可以添加(add添加单个项目,update添加多个项目)
#删除
a = {"aa","ss","dd"}
a.remove("aa") #若不存在将报错
print(a)
a.discard("ss")#若不存在将报错
s =a.pop()
print(s)#会删除最后一个
print(a)
- 字典
#字典的创建
thisdic = {
"name" : "aa",
"age" :11 ,
"year" :111
}
print(thisdic)
#索引输出
a = thisdic["age"]
b = thisdic.get("name")
print(a)
print(b)
#修改数据
thisdic["age"] = 199
print(thisdic)
#遍历
for x in thisdic:
print(x)
#输出values 值
for x in thisdic.values():
print(x)
#添加
thisdic["sex"] = "man"
print(thisdic)
#删除最后的数据(pop也行)
thisdic.popitem()
print(thisdic)
#复制
s = thisdic.copy()
print(s)
d = dict(thisdic)
print(d)
- 函数
#函数定义
def mytest():
print("加油!")
mytest()
#传参数
def my(name ,age ="1"):
print("i am "+ name +" and i am " +age+ " ord")
my( "a","2")
def my1(*kids):
print(kids)
my1("a","s","d")
#递归
def my2(k):
if(k>0):
result = k+my2(k-1)
print(result)
else:
result = 0
return result
my2(6)
#lambda函数
#lambda是一种小的匿名函数,可以接受任意数量的参数,但是只有一个表达式
x = lambda a : a +10
print(x(1))
- 类与对象
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("Bill", 63)
p1.myfunc()
//////////////////////////////
/////////////////////////////
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("Bill", 63)
p1.myfunc()
#修改数据
p.name = "s"
#删除
del p.age
- 继承
class person :
def __init__(self,name,age):
self.name = name
self.age = age
def a (self):
print("姓名: " + self.name +" 年龄: " +self.age)
p = person("pp","12")
p.a()
class son(person):
def __init__(self ,name, age , birthday ):
person.__init__(self , name ,age )
#suoer().__init__(name ,age )
self.birthday = birthday
def a(self):
print(self.name +" " +self.age+" "+self.birthday)
x = son("aa" , "12" ,"1234")
x.a()
- 迭代器
my = ("aa", "ss" ,"dd")
a = iter(my)
print(next(a))
for x in my:
print(x)
class number:
def __iter__(self ):
self.a = 1
return self
def __next__(self):
x= self.a
self.a +=1
return x
myclass = number()
m = iter(myclass)
print(next(m))
print(next(m))
print(next(m))
print(next(m))
- 模块(与导入包、库类似)
#创建模块
#在my.py文件中
def getname(name):
print( "my name is " + name)
#在1.py文件中
import lianxi
lianxi.getname("aa")
#创建别名
import lianxi as lx
- JSON
#导入JSON包
import json
#json 与 python 转换
x = '{ "name ":"aa" ,"age" : 33 , "city" :"bj"}'
y = json.loads(x) #解析字符串
print(y["age"])
#indent = 参数 定义缩进
#sort_keys 进行排序
- regex
用于检测字符串是否包含指定的搜素模式
regex或正则表达式是形成搜索模式的字符串序列
#regex 模块
import re #可使用正则表达式
txt = "my name is aa"
x =re.search("^my.*aa$",txt)
if(x):
print("1")
else :
print("22")
#findall()函数 返回包含所有匹配项的列表,若未找到则返回空列表
y = re.findall("a",txt)
print(y)
#search()函数 ,搜索字符串中的匹配项,存在返回Match对象,若有多个匹配,返回首个匹配项位置,没有返回none
z = re.search("\s",txt)
t = re.search("a",txt)
print(t)
print( z.start())
#split()函数 返回一个列表,其中的字符串在每次匹配时拆分
q = re.split("\s" ,txt)
print(q)
w = re.split("\s",txt,2) #传入参数,进行分割
print(w)
#sub()函数
e = re.sub("\s" ,"2" ,txt)
print(e)
r = re.sub("\s","2",txt ,2)
print(r)
#match对象
#Match 对象提供了用于取回有关搜索及结果信息的属性和方法:
#span() 返回的元组包含了匹配的开始和结束位置
#.string 返回传入函数的字符串
#group() 返回匹配的字符串部分
- 文件处理
#open()函数
#"r" - 读取 - 默认值。打开文件进行读取,如果文件不存在则报错。
#"a" - 追加 - 打开供追加的文件,如果不存在则创建该文件。
#"w" - 写入 - 打开文件进行写入,如果文件不存在则创建该文件。
#"x" - 创建 - 创建指定的文件,如果文件存在则返回错误。
#"t" - 文本 - 默认值。文本模式。
#"b" - 二进制 - 二进制模式(例如图像)。
f = open("1.txt" , "rt")
- 文件打开
f = open("1.txt")
print(f.read()) #读取文件
print(f.read(5)) #返回要读取的字符数
print(f.readline())#读取一行
- 文件写入
f = open("1.txt","a")
f.write("asdasda")
f.close()
f = open("1.txt","rt")
print(f.read())
f.close()
f = open("2.txt","w") #写入数据,若文件没有,则创建文件
- 文件删除
import os #导入os块才可以运行os.remove()函数
os.remove("2.txt")
os.path.exists("2.txt")#判断文件是否存在
os.rmdir()#删除文件夹 只能删除空文件夹
三、python yu mysql
1、用管理员运行cmd
2、进入pip所在的目录
3、安装mysql-connector
python -m pip install mysql-connector
4、创建数据库
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
password = "root"
)
print(mydb)
my = mydb.cursor()
my.execute("show databases")
for x in my:
print(x)
5、创建表
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
password = "root",
)
print(mydb)
my = mydb.cursor() #h获得操作数据库的句柄
my.execute("show databases")
for x in my:
print(x)
my.execute("use sis2017")
my.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")
- 增加数据
sql = "INSERT INTO customers (name,address) VALUES(%s,%s)"
val = ("aa","ss")
my.execute(sql,val)
mydb.commit() #数据表更新必须用此函数
- 删除数据
sql = "DELETE FROM customers WHERE address = 'Mountain 21'"
my.execte(sql)
my.commit()
- 修改数据
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'"
my。execute(sql)
mydb.commit()
- 查找数据
my.execute("select * from customers")
result = my.fetchall()
print(result) #获取所有返回的信息
#result = my.fecthone()
#print(result) 返回结果的第一行