Python入门大全
学习之前需要了解几个内容:
1.python目前的地位
目前看python的主要方向是取代php以及java在web服务器端的部分份额。
(php以前做的工作,例子:豆瓣,知乎)
(服务器端比java轻量级,开发迅速,例子,youtube,dropbox,openstack)
2.python可以做什么
3D游戏开发
数据分析
人工智能
3.python与java的区别
开始学习
一.python基础
python分为python2,python3
Python3入门笔记(1) —— windows安装与运行 - weven - 博客园
第一个py实例
import turtle 海龟画图
新建一个1.py
编写
import turtle
turtle.forward(100)
turtle.right(144)
turtle.forward(100)
turtle.right(144)
turtle.forward(100)
turtle.right(144)
turtle.forward(100)
turtle.right(144)
turtle.forward(100)
run...
----------命令行模式----------
cmd
cd Python 进入根目录
python 查看版本
exit() ---退出
---------基本操作-----------
id(a)查看内存地址
type(a)查看a的类型
2**3 2的3次方
7//2 =3整数除法
input()输入 返回的是一个字符串“123”
int(a) string转化为int 但是a指向“123”
x=int(a);拿到a的值
a=1;
if a<5 : print("ok") ---需要缩进 4个空格
》》》if a<5:
... print(a);
例子:
hp=100
print("welcome")
name = input("please input your name")
if not name:
name="p1"
user = [name,hp]
print(user)
direct=input("请输入要走的位置a/b");
if direct == "a":
print("向左走")
if direct == "b":
print("向右走")
画图:
pip install numpy数学函数
pip install matplotlib画图工具
import numpy as a
import matplotlib.pyplot as b
x = a.arange(0,2*a.pi,0.01)
y = a.sin(x)
b.plot(x,y)
b.show()
字符串还能做乘法
a='1'*5
字符串
s1="hello"
s2="hello"
s1 in s2
true
s1[0] --------h
s1[-1] --------o
s1[6:] -------world(左闭右开)
s1[::2] --------hlowrd全部取跳两个取
say = "hehe %a haha %b"
say % (123,'heihie')
hehe 123 haha heihie
d1 = (123.'sss')
say % d1
输出一样
a=3+4j
b=5+3j
a+b
(8+7j)
---------------------------str方法---------------------------
help(str)帮助文档
capitalize()大写
ip="11.11.22.22"
ip.split('.')[-1]
22
qq =ip.split('.')
>>> print(qq)
['11', '11', '22', '22']
>>> ('.').join(qq)
'11.11.22.22'
>>> ww=('.').join(qq)
>>> print(ww)
11.11.22.22
----------------循环-----------
for i in 'hello':
... print(i)
h
e
l
l
o
>>> for i in range(1,10,1):
... print("aa")
...
aa
aa
aa
aa
aa
aa
aa
aa
aa
>>>
>>> a='x'
>>> while a!='qq':
... a=input()
...
ww
ee
---------break------
while 1:
x=input("输入")
print(x)
if x=="no":
break
else:
print("退出输出no")
-----------数组------------------------
aa=['bb',100,120]
type(aa)
for i in aa:
print(i)
bb
100
120
>>>
----------方法--------------
extends()
aa=['bb',100,120]
box=['a','b','c']
aa.extend(box)
print(aa)
['bb', 100, 120, 'a', 'b', 'c']
>>>
x=aa.pop(-2);
print(x)
b
list.append()
insert()
extend()
pop()
remove()
sort()
print(aa.sort())
not supported between instances of 'int' and 'str'
d=[1,3,5,2,4]
d.sort()
print(d)
[1, 2, 3, 4, 5]
---------------元组---------------
t=('a','b','c');
a,b,c=t
print(a)
print(b)
print(c)
a
b
c
>>>
t[0]
'a'
num = []
for i in range(1,100):
if i%3 == 0 and i%5 == 0:
num.append(i)
print(i)
print(sum(num))
>>> [i*10 for i in range(10)]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
>>>
>>> [i for i in range(1,16) if i%3==0 and i%5==0]
[15]
>>>
----------------生成器---------------
>>> g=(i for i in range(1,16) if i%3==0 and i%5==0)
>>> print(g)
at 0x000002C20803F780>
>>> for i in g:
print(i)
15
>>>
-------------------集合-----------
map((0,1),(0,2),(0,3))
-----------字典---------
d={1:'a',2:'b',3:'c'}
d[6]='c'
In [10]: d
Out[10]: {1: 'a', 2: 'b', 3: 'c', 6: 'c'}
In [12]: for k in d:
...: print(k)
...:
1
2
3
6
In [13]: for k in d:
...: print(d[k])
...:
a
b
c
c
x= int(input())
o=input()
y=int(input())
operator = {
'+':x+y,
'-':x-y,
'*':x*y,
'/':x/y
}
result = operator[o]
print(result)
3
+
3
6
>>>
---------文件输入(锁)----------------
a='haha'
open('login.txt','w').write(a)
f=open('d:/Python/code/login.txt','r')
f.read()
f.close()
f.readline()一行行读
f.read(6)每6个读取数字
f.write()
f.flush()
f.seek(偏移量,选项)
0,1,2 头,当前,尾
read读取的时候类似于指针
参数:
r
w
a在后面追及欸
b打开二进制文件 +r,w,a --- rb
u支持换行 \r\n
import os
os.path.isfile('login.txt')
------------函数----
def
In [28]: a=10
In [29]: def aa(a):
...: a=a+10
...: return a
----------------随机数---
import random
random.randint(1,3) 1-3之间
user{'hp':hp}
eventlist[apple,bom]
user['hp']=random.choice(eventlist)(user['hp'])
In [45]: def aa(x,y):
...: print('s制作一个 %d 元的 %s 冰激凌'%(x,y))
...:
In [46]: aa(5,5)
s制作一个 5 元的 5 冰激凌
aa(3,5,4,6)
TypeError: aa() takes 2 positional arguments but 4 were given
-----------内置函数-----------
len()
divmod()
pow()
round()
abs()
min()
range()
callable()
isinstance()
类型转化:
str()
tupe()
hex()
oct()
ord()生成四位验证码
str方法
str.replace()
split()
join()
strip()
---------------引用方法---
lambda
In [48]: y=lambda x,y:x+y
In [49]: y
Out[49]: >
In [50]: y(3,4)
Out[50]: 7
reduce(lambda x,y:x+y , [1,2,3,4,5])
逐次做运算结果为15
序列处理函数:
reduce()
zip()
filter()
map()
例如:reduce(lambda x,y:x+y , [1,2,3,4,5])
------------生成器函数---------
yield
---------------模块化开发----
java中同包下的类调用
from newnew import show
show()
----------------------路径问题
import os
os.getcwd()
f=os.getcwd()+'\\pack'
import sys
sys.path.append(f)
In [3]: sys.path
Out[3]:
['',
'D:\\Python\\Scripts\\ipython.exe',
'd:\\python\\python36.zip',
'd:\\python\\DLLs',
'd:\\python\\lib',
'd:\\python',
'd:\\python\\lib\\site-packages',
'd:\\python\\lib\\site-packages\\IPython\\extensions',
'C:\\Users\\15456\\.ipython',
'D:\\Python\\code\\pack']
--------------装饰器----------
时间:
import time
def timefu():
start = time.time()
print('开始')
time.sleep(5)
print('结束')
end=time.time()
mm=(start-end)*1000
print(mm)
timefu();
可以返回函数
return timefu()
----------闭包------------------
def helloa(a):
def hellob(b):
print(a,b)
return hellob
q=helloa('呵呵')
q('嘿嘿')
print(q.__name__)
呵呵嘿嘿
hellob
二.python类
---------类---------------
class Car:
color = ''
def run(self):
print('gogogo')
b = Car()
b.color = 'red'
print(b.color)
b.run()
a()普通方法
--a()--构造方法
--aa()私有方法
--aa--()魔术方法
class.__doc__内置属性
---------继承多态-------------
class t:
def __init__(self,w,h):
self.w=w
self.h=h
def getaa(self):
aa=self.w *self.h /2
return aa
s=t(5,5)
print(s.getaa())
12.5
>>>
----------------继承-----------
class father:
money=100
def driver(self):
print('father')
class mother:
money = 200
class son(father,mother):
pass
def pay(self):
print(self.money)
tom = father()
print(father.money)
je=son()
je.driver()
je.pay()
---------重载----------
class Mylist:
mylist =[]
def __init__(self,*args):
self.mylist=[]
for arg in args:
self.mylist.append(arg)
l=Mylist(1,2,3,4,5)
print(l.mylist)
------------内置装饰器-------------
pass代码桩 没想好的功能
staticmethod
classmethod类方法 接受的第一个参数不是self而是类的类型
property系那个类中的方法变成一个只读的属性
@property
def aa(self)
f1.aa -------不需要()
------------游戏-----------
class Hero:
def __init__(self,name='p1',hp=100):
self.name = name
self.hp =hp
print('英雄 %s 诞生!!' % self.name)
anqila = Hero('妲己')
======================= RESTART: D:/Python/code/2/4.py =======================
英雄妲己诞生!!
>>>
----------异常------------------
try:
s='hello'
print(s[100])
except IndexError:
print('error')
else:
print('no error')
======================= RESTART: D:/Python/code/2/4.py =======================
error
>>>
异常的名字
IOError
KeyError ............
with open('d:/Python/code/1/login.txt','r') as f:
f.read()
抛出异常
raise
assert
三.pythonGUI
--------------GUI-------------
import tkinter
import turtle
root = tkinter.Tk() #生成主窗体
lable = tkinter.Label(root,text='你好')
lable.pack() #将label添加到主窗体
button1 = tkinter.Button(root,text='按钮')
button1.pack()
menu = tkinter.Menu(root) #添加菜单
sub = tkinter.Menu(menu,tearoff=0) #生成下菜单
sub.add_command(label='open') #添加菜单选项
sub.add_command(label='save')
menu.add_cascade(label='File',menu=sub) #下拉菜单添加到菜单
root.config(menu=menu)
def aa(event): #响应事件
for i in range(5):
turtle.forward(100)
turtle.right(144)
button1.bind('',aa)
root.mainloop() #进入消息列队
--------应用程序开发----------------
框架开发
安装wxpython
pipi install wxPython
推荐书:wxPython in Action
-------------向面板添加组件-------
--------聊天窗口--------------
import wx
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self,None,-1,'聊天',size=(520,450))
panel = wx.Panel(self)
lableAll = wx.StaticText(panel,-1,'所有内容')
#self.textAll = wx.TextCtrl(panel,-1,size(480,200),pos=(10,25),
# style=wx.TE_MULTILINE)
app = wx.App()
frame = MyFrame()
frame.Show()
app.MainLoop()