Python入门笔记

Python入门笔记

视频学习网址http://blog.fishc.com/category/python

目录


语法:

字符串 ——————单引号 ” 或者 双引号 “”
转义符号—————–\
原始字符串—————r” ,自动添加转义符号
长字符串—————–”’ ”’ 三重引号,可以自动添加换行符
e记法——————–*e(), *10的次方值
随机整数 random.randint(start,end)

数据转换

int()——————–转换成整数,输入为浮点型时,采用去尾法
str()——————–转换成字符串
float()——————转换成浮点数

获取变量类型

type()——————-获取变量类型
isinstance( , object)—-判断是否为object指定的变量类型
dir()获取某个类的所有方法

操作符及优先级:

幂运算—————– **
正负号—————- + -
算数操作符———- * / // + -
比较操作符——– < <= > >= == !=
逻辑运算符——- not and or

if — else

if :
tab键
else :
tab键

for 循环

for each in []
range([start,] stop[, step=1])
—[]中的内容可选
—生成从 start 到 stop 前一个的一个列表,步进为 step

数组:

初始化:

= [ , , ] 数组的元素可以为任意不同的类

方法:
remove(元素名)
pop() -----------------弹出最后的元素
pop(index)------------弹出index位置的元素
[start : end]----------获取从start位置开始到end前一个的数组分片
    ---[:]---------------用于获取列表拷贝
count() ---------------获取某个元素在列表中出现的次数
index() ---------------获取某个元素出现的第一个位置
reverse() -------------翻转数组
sort() ----------------从小到大排序
sort(reverse = true)---从大到小排序
sort(func, key)--------
操作符:
in :判断某个元素是否在数组中
not in:判断某个元素是否不在数组中

元组(tuple):

元组中元素不可更改,其余和数组很像
初始化:( , , )

字符串:

capitalize()————-首字母大写
center()—————–输入为文本居中后的长度,首尾补足空格
count(”)—————-寻找输入字符串出现的个数

字符串格式化输出:

format()
str中含有{0} {1} {2} 等位置参数,用format(”, ”, ”)的输入替换该相应的位置参数
str中含有{a} {b} {c} 等关键字参数,用format(a=”, b=”, c=”)输入替换该相应的位置参数

{f} 表示 浮点数
{m.n}m是显示的最小总宽度,n是小数点后位数

函数:

关键字参数:赋值时直接使用参数形参的名字赋值,可以不用考虑形参的顺序,既 形参 = ”
参数列表:在函数定义时,def func(*params)这种形式可以传入一个元组参数

定义形式:

def func:

全局变量与局部变量

global 关键字
函数内部无法改变全局变量的值,试图使用全局变量时,会自动生成一个同名的局部变量
若需要修改全局变量,则需要在变量前加 global 关键字

内嵌函数:

在函数内部定义的函数,只允许在内部调用

闭包写法:

函数返回值为其内部函数的方式

lambda关键字 :匿名函数 类似define,

字典(dict):

key和value对应,
可以让两个数组一个为key,一个为value,例如a[b.index(元素)]或输出a数组对应的index的元素
另一种赋值方式 {key:value, key:value},访问时使用 [key]

集合(set):

集合是无序的,不可以用index索引访问
赋值方式 = { ,,,}
或者 set([ ]), frozenset()—–不可更改的集合

添加元素:
add()
访问方式:
for方式
用 in 和 not in判断是否存在

由attr和func构成

attr方法:
hasattr(object, name)—————-是否含有某个attr
getattr(object, name[, default])—–获取某个attr
setattr(object, name, value)
delattr(object, name)

x = property(fget, fset, fdel, doc),将某个attr赋值到x中,使得x 通过 = del可以直接操作 某个attr

类的魔法方法:*(self[, …])

继承 class classname(father class)

初始化 init(self, [])
构造 new(class, []), new 方法第一个调用
析构 del(self)

算数运算:

add(self, other),
add +
sub -
mul *
truediv /
flordiv //
mod %
pow **
shift <<
rshift >>
and &
xor ^
or |

yield 与 next()
func内部可以写过个 yield 关键字,当调用next时会依次执行到相应的next

GUI:tkinter

窗口显示:tkinter.Tk().mainloop()
窗口标题:tkinter.Tk().title(‘cui ui’)
按钮:tkinter.Button(Master, text = ‘button’, fg = ‘red’, command = button_behavier)button_behavier为点击调用方法

显示图片 imageLable = Label(Master, image = PhotoImage(file = ‘18.gif’)),PhotoImage只能加载gif图片好像

多选框:Checkbutton(Master, text=”, variable = IntVar())variable选中则为1,未选中则为0

单选框:Radiobuttob(Master, text=”,variable = IntVar(), value = 同一个master中的value不能相同),

输入框:Entry(Master)

大量选择框: Listbox(Master) ,用insert依次添加新的数据, delete()删除。可以设置单选,多选

输入框:Text()

排列方式:
pack(),定义位置
grid(row = , colum = ),按照网格定义位置

pygame

Surface对象,用来表示图像

事件:获取事件 ,pygame.event.get(). 退出按钮 ptgame.QUIT,
方向键:event.type == KEYDOWN, event.key == K_LEFT/K_RIGHT/K_UP/K_DOWN

贪吃蛇小游戏

import pygame
import sys
import random
import tkinter

class MaySnake:    

    snakeColor = (0,0,0)
    eatColor = (255, 255, 0)



    #速率
    interval = 20;


    def init(self, interval):
        #存储贪吃蛇位置
        self.Location = []
        #食物位置
        self.moduleLocation = (0, 0)
        #前进方向
        self.moveDirection = (0, 0)
        self.flash = 0;

        #第一个贪食蛇位置        
        self.Location.append((random.randint(0,screenSize[0]), random.randint(0,screenSize[1])))
        self.creatModule()
        #print(self.moduleLocation)
        self.interval = interval

    #生成吃食的位置
    def creatModule(self):
        while True:
            self.moduleLocation = (random.randint(0,screenSize[0]), random.randint(0,screenSize[1]))
            if self.moduleLocation not in  self.Location:
                return self.moduleLocation

    def draw(self, surface, size):
        for each in self.Location:
            pygame.draw.rect(surface, self.snakeColor, (each[0]*size, each[1]*size, size, size), 0)

    def drawEat(self, surface, size):
        pygame.draw.rect(surface, self.eatColor, (self.moduleLocation[0]*size, self.moduleLocation[1]*size, size, size), 0)

    def move(self, direction):
        #print("move direction", direction, "location -1:", self.Location[-1])
        self.flash = self.flash + 1
        if self.flash < self.interval:
            return
        self.flash = 0
        self.moveDirection = direction
        if (self.moduleLocation[0] - self.Location[-1][0], self.moduleLocation[1] - self.Location[-1][1]) == direction:
            self.Location.append(self.moduleLocation)
            self.creatModule()
        else:
            #print("new location:", (self.Location[-1][0] + direction[0], self.Location[-1][1] + direction[1]))
            self.Location.append((self.Location[-1][0] + direction[0], self.Location[-1][1] + direction[1]))
            self.Location.pop(0)

    def checkOk(self):
        if self.Location[-1][0]<0 or self.Location[-1][0]>screenSize[0] or self.Location[-1][1]<0 or self.Location[-1][1] > screenSize[1]:
            return False
        for index in range(0, len(self.Location)-2):
            if self.Location[-1] == self.Location[index]:
                return False
        return True

direction = (0,1)
#屏幕模块数目
screenSize = (30, 30)
screenColor = (255, 255, 255)
#贪吃蛇大小
moduleSize = (10, 10)
moduleColor = (0,0,0)



def main():
    direction = (0,1)
    #屏幕模块数目
    screenSize = (30, 30)
    screenColor = (255, 255, 255)
    #贪吃蛇大小
    moduleSize = (10, 10)
    moduleColor = (0,0,0)
    pygame.init()
    screen = pygame.display.set_mode((screenSize[0]*moduleSize[0], screenSize[1]*moduleSize[1]))
    pygame.display.set_caption("贪吃蛇")

    maySnake = MaySnake()
    maySnake.init(10)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT and maySnake.moveDirection != (1, 0):
                        direction = (-1, 0)                    
                if event.key == pygame.K_RIGHT and maySnake.moveDirection != (-1, 0):
                         direction = (1, 0)
                if event.key == pygame.K_UP and maySnake.moveDirection != (0, 1):
                         direction = (0, -1)
                if event.key == pygame.K_DOWN and maySnake.moveDirection != (0, -1):
                         direction = (0, 1)
        #print ("direction:", direction)
        screen.fill(screenColor)

        if maySnake.checkOk() == False:
            #if tkinter.messagebox.askokcancel("game over", "restar?"):
                #print('restar')
                #main()
            print('game over')
            sys.exit()

        #pygame.draw.rect(screen, moduleColor, (150, 220, 10, 10), 1)
        #print(S.moduleLocation)
        maySnake.drawEat(screen, moduleSize[0])
        maySnake.draw(screen, moduleSize[0])
        maySnake.move(direction)

        pygame.display.flip()
        pygame.time.delay(40)

main()

这里写图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值