基础语法
python中,没有:{},也不用每句话才用分号分开。python只通过缩进来分块的,一行占个句话就可以。
1>.基础数值运算:
18/5 = 3.6
18//5 = 3 //两个除号 结果取整
5*5*5 = 125
5**3 = 125 // 两个乘号 5的三次方
2>.字符串:"" ‘’ 表示字符串
字符串长度: len("hello")
vpn="虚幻世界"
vpn[0] = "虚"
vpn[-1]="界" //双向访问 从末尾 -1 下标访问
vpn[0:2]="虚幻" //区域访问
vpn[2:]="世界"
vpn[0:]="虚幻世界"
3>.列表:一堆数字 字符串的结合
plsyers=[3,5,11,23,24]
plsyers[2] //输出11
plsyers[2] = 1 //输出[3,5,1,23,24]
plsyers + [90, 91] //输出[3,5,11,23,24,90,91]
plsyers.append(90)//输出[3,5,11,23,24,90]
plsyers[:2] = [0,0] //输出[0,0,11,23,24,90]
plsyers[:2] = [] //输出[11,23,24,90]
plsyers[:] =[]//清空列表
4>.if elif else 语句后要加“:”
age = 27
if age < 18:
print("oxox")
name = ‘bang’
if name is ‘bang’:
print("bangbang")
elif name is 'lucy':
print("hello lucy")
elif name is 'linMing':
print("hello linMing")
else:
print("hello people")
5>.for
words = ['a', 'ab', 'abc', "abcd", "abcde"]
for w in words: //遍历words并输出
print(w)
print(len(w))
for w in words[:2]: //遍历words 下标到2 并输出
print(w)
6>.Range() while()循环
for x in range(10): //一个参数 默认从0开始到10 步长默认为 1
print(x)
for x in range(5, 12): //两个参数 从第一个参数 到第二个参数
print(x)
for x in range(5, 12, 2): //三个参数 从第一个参数 到第二个参数 步长为第三个参数
print(x)
count = 5
while count < 10:
print(count)
count += 1
7>.注释 break语句 continue语句单行注释: #这是注释~~~~
多行注释: ‘''这是注释~~~''' “”“ 这是注释~~~"“”
字符串和数字相加:
n = 19
str(n) + "is magic number" //输出 19 is magic number
break:打断循环continue:终止本次循环
8>.函数
定义函数
def fun():
print('work')
fun()//调用函数
def predict_gf_age(my_age = 29): //默认参数 29
gf_age = my_age/2 + 8
return gf_age
age1 = predict_gf_age(50) //
print(age1)//
高阶函数变量:用来保存数据 (python中可以使用变量来表示操作数据的动作)
通过函数名引用函数
像对待普通变量那样对待函数名
函数名可以当做变量进行赋值
当做参数传递给别的函数
可以从函数中返回另一个函数
高阶函数的意义
抽象层次更高:数据抽象=》操作抽象
9>.变量作用范围
a = 1111 //在函数外定义 下面的函数都能用这个变量
//在函数内部定义的变量 只能在函数内部使用
def oxox()
print(a)
def work()
print(a)
oxox()
work()
10>.关键字参数11>.可变参数
def add_numbers(*args):
total = 0
for a in args:
total += a
print(total)
add_numbers(3) //输出 3
add_numbers(3, 33) //输出 36
add_numbers(3, 33, 333) //输出 369
12>.参数解包
def health_cacl(age, apple_ate, cigs_smoked):
value = (100 + age) +(apple_ate*3.5) -(cigs_smoked*2)
print(value)
bangge =[29, 20, 0]
health_cacl(bangge[0], bangge[1], bangge[2])
health_cacl(*bangge) //函数参数解包
13>. zip
first =['a', 'b', 'c']
last =['x', 'y', 'z']
letter = zip(first, last) //first和last组合成元组 [('a', 'y'), ('b', 'y'), ('c', 'z')]
print(letter)
for i, j in letter:
print(i, j)
14>. lambda函数
answer = lambda x:x*7 // 定义个lambda函数 参数为x 函数实现 x*7 函数赋值给answer
print(answer(5))
def oxox(answer = lambda x:x*7):
print(answer(5))
oxox()
oxox(lambda x: x*5)
15>. 数据结构 集合相当C++中的set 无序 不重复的结合
tutorial = {"C++", "Python", "Github", "windows", "chrome", "Python"}
print(tutorial) //{"C++", "Python", "Github", "windows", "chrome"}
if "Python" in tutorial:
print("Python Online")
else
print("Python Offline")
16>. 数据结构 字典
key - value
classmates = {"xupeng":"niaorenxu", "liuzipei":"Piziliu" , "YeGenngYong":"FengRenGang" }
print(classmates)
print(classmates["xupeng"])
遍历字典
for k, v in classmates.items():
print(k+v)
17>. 模块 (多文件):
Tool.py
def Google():
print("Don`t be evil!")
first.py
import Tool //引入 Tool.py
Tool.Google() //模块名.函数名
18>. 解包列表:
ourUrl = ["www","oxox","work"]
sec, first, top = ["www","oxox","work"]
print(sec) //"www"
print(first) //"oxox"
print(top) //"work"
sec, *first, top = ["www","ox", "ox","work"] //first指代没有声明变量的值集合
print(sec) //"www"
print(first) //["ox", "ox"]
print(top) //"work"
19>.字典的操作
url = {
'Google': 'Google.com',
'Youtube': 'Youtube.com',
'Facebook': 'Facebook.com',
'Github': 'Github.com',
}
print(min(zip(url.keys(), url.values()))) // 'Facebook': 'Facebook.com'
print(max(zip(url.keys(), url.values()))) // 'Youtube': 'Youtube.com'
print(sorted(zip(url.keys(), url.values())))
20>. 类和对象
//定义个敌人类
class Enemy:
life = 3
def attack(self):
print("掉一滴血")
self.life -= 1
def checkLife(self):
if self.life <= 0:
print("i`die")
else:
print("我还活着,来打我呀")
//通过类创建对象 然后调用类的函数
enemy1 = Enemy()
enemy1.attack()
enemy1.checkLife()
21>.类的 init函数相当于C++中的构造函数,会在每次构建对象时自动调用
class work:
def __init__(self):
print("init函数被调用")
def oxox(self):
print("oxox函数被调用")
www = work() //输出 init函数被调用
www.oxox() //输出 oxox函数被调用
class Enemy:
life = 3
def __init__(self, x):
self.life = x
def get_lift(self):
print(self.lift)
oxox = Enemy(5)
boss = Enemy(20)
oxox.get_lift()
boss.get_lift()
21>.继承继承中也可重载父类函数
class parent():
def print_last_name(self):
print("huang")
class child(parent): //继承parent
def print_first_name(self):
print("bangge")
oxox = child()
oxox.print_last_name()
oxox.print_first_name()
22>.多重继承
class Mario():
def move(self):
print("我在移动")
class BigMario():
def eat_mushroom(self):
print("我变大了")
class ShootMario(Mario, BigMario): //多重继承
def Shoot(self):
print("我在射击")
oxox = ShootMario();
oxox.move()
oxox.eat_mushroom()
oxox.Shoot()
23>. struct模块
import Module //引入模块
from Module import Other //引入模块中的类,函数或者变量
from Module import * //引入模块中的所有 '公开' 成员
from struct import *
packed_data = pack('iif', 6, 19, 4.73) //普通数据转换字节数据
print(packed_data)
orgin_data = unpack('iif', packed_data) //字节数据转换普通数据
print(orgin_data)
print(calcsize('i'))// 打印int字节长度
24>. Map函数 使用函数作用一组数据
income = [10, 20, 30]
def double_money(RMB):
return RMB*2
list = map(double_money, income) //针对income列表中每个元素都用double_money操作一遍 操作的数据返回
//原有income列表数据不变
print(list)
25>. 读写文件//创建 并写入内容
fw = open("sample.txt", 'w')
fw.write('writting some stuff in my text file \n')
fw.write('i develop game')
fw.close()
//读取内容
fr = open('sample.txt', 'r')
text = fr.read()
print(text)
fr.close()
26>. 异常
while True:
try:
numb = int(input("你喜欢的数字?"))
print(18/numb)
break
except ValueError: //捕获异常
print("请确保输入的是数字")
except ZeroDivisionError: //捕获异常
print("除数不能为0")
except: //捕获全部异常
break
finally: //不管有没有触发异常 都会指向finally中语句
print("本次循环结束")
27>. 线程
import threading
class wxMessager(threading.Thread): //wxMessager继承threading包中Thread类
def run(self): //每次启动线程对象时被调用
for x in range(10):
print(threading.current_thread().getName())
x = wxMessager(name = "发送消息")
y = wxMessager(name = "接收消息")
x.start() //启动线程 启动后 会调用run函数
y.start()
28>. 常量29>. 列表 元组:
在python 中没有数组的概念,Python中跟数组最接近的概念就是列表和元组
列表(list) 可变
元祖(tuple) 不可变列表
列表:就是用来存储一连串元素的容器,列表用[]来表示
student = ["ming", "hua", "li", "juan", "yun" ]
print(student)
元组:元组里面的元素也是进行索引计算, 但是列表和元组有什么区别尼?一是列表里面的元素的值可以修改,二元组里的元素的值不能修改,只能读取,二是列表的符号是[] 而元组的符号是()
student = ("小明", "小军","小强","小龙")
print(student)
30>. OS模块:目录操作就是通过Python来实现目录的创建,修改,遍历等功能。
import os
//目录操作需要调用OS模块
//比如:
os.mkdir('/root/csvt')
mkdir(path)