python基础语法一

一、基础语法


        数据类型:int long float str  复数 1+2j  //整除
        运算符:算术,逻辑,
        循环结构  while (实数循环) for   break  contain (相互转换)
        分支结构  if   elif
        list:
            是地址的集合


1、注释


单行注释:#

多行注释:'''内容'''


2、关键字


# 关键字
import keyword
print(keyword.kwlist)


3、变量


# python可以修改变量类型【地址赋值类型】
# 变量命名
num = 10
print(num)
print(type(num))#查看数据类型
print(id(num))#查看数据id

num='把啦啦啦小魔仙'
print(num)
print(type(num))
print(id(num))

特殊标识符:None

num = None #NULL标识符
print(type(num))



<class 'NoneType'>


4、字符


ch1 = "A"
ch2 = "B"
print(ord(ch1),ord(ch2))

print("\u6211")
print("a","\n")
print("a\n")


5、运算符


// 为整除
% 求余数
** 开方 ** 0.5 平方根   ** 2  平方   **3 三次方
数据类型转换 - 强制类型转换即可
调用数学方法 round() 四舍五入
连续输入多个数 x,y = eval(input("描述"))

格式化

#没有<右对齐 f:浮点数  d:整形数  s:字符串
print(format(10.654654654,".8f"))
print(format(10.65464,".8f"))
print(format(10.654665464654654,"<.8f"))

print('\n')

print(format(101233,"<8d"))
print(format(1065464,"<8d"))
print(format(10654665464654654,"<8d"))


6、条件循环语句


判断条件语句:if语句 bool表达式
    随机数  and运算符  or或者运算符  not 取反运算符
    is 身份运算符(判断)
    elif  配合好,注意隐含条件

    pass空语句
    turtle.dot(10,"red")  #绘制点:点宽,颜色

    文本与语音的转换:

    循环语句:while   for
    while else : 过界之后临界值处理
    浮点数存在误差

if语句

num = 1
if num == 2:
    print("true")
else:
    print("false")
score = 70

if score < 60:
    print("不及格")
elif score < 70:
    print("及格")
elif score < 80:
    print("好")
elif score < 90:
    print("良")
else:
    print("优")

判断语句

import random
num1 = random.randint(0, 100)
print(num1)
num2 = random.randint(0, 100)
print(num2)
print("%d + %d" % (num1, num2))

if num1 is not num2:
    print("不是同一个地址")
else:
    print("是同一个地址")
#特殊用法
print("hello" if num > 3 else "world")

while循环语句

import time
num = 2.0
# while num != 0:
index = 0
while num - 0 > 0.00000001:
    num -= 0.1
    print(num)
    index += 1
    print(index)
    time.sleep(0.5)
else:
    print(index)

for循环语句

for i in range(1,100):    #for循环 1<=i<100
for i in range(1,100,10): #步长为10
for i in range(100):  0-99
            range(min,max,step)
            range(max,min,-step)  倒序
    break:结束循环
    contain:结束当前循环【筛选】

读写文件,找出符合条件的内容并写入指定文件

import codecs
import os

file = codecs.open("H:\\data\\source.txt", "rb", "gbk", "ignore")
fileResult = codecs.open("H:\\data\\result.txt", "w", "gbk", "ignore")

while True:
    linestr = file.readline()
    if linestr.find("无冬城") != -1:
        print(linestr)
        fileResult.write(linestr)

    if linestr == None:
        break

二、函数


    def 方法名(参数列表):函数体
    返回值,参数列表
        默认参数标识
        位置参数,名称参数
        不会改变参数本身(值传递)
        多返回值(对应接收)
        全局变量  global:引用全局变量    nonlocal:引用外层变量(函数间嵌套)
        函数可以嵌套


1、定义【不定长参数】


def newadd(*num):
    lastNum = 0
    for data in num:
        lastNum += data

    print(lastNum)


newadd(1, 2, 3)


2、名称参数与位置参数


def show(num1, num2, num3):
    print(num1, num2, num3)


show(num3=50, num1=20, num2=10)  # 名称参数可以乱序

show(1, 2, 3)  # 位置参数


3、接口实现


实现原理主要是可以传递函数名作为参数。

def add(num1, num2):
    return num1 + num2


def subtract(num1, num2):
    return num1 - num2


def multiply(num1, num2):
    return num1 * num2


'''
    除数不能为0,存在异常
'''
def divide(num1, num2):
    return num1 / num2


# 接口【方法名可以作为传参】
def function(func, num1, num2):
    return func(num1, num2)


print(function(add, 10, 30))
print(function(subtract, 10, 30))


4、匿名函数


num = (lambda a, b, c: a + b + c)(10, 20, 30)
print(num)


5、字符串


  ord:只能处理单个字符
    '':处理字符
    "":处理字符串
    三个:多行字符串
    bytes:字节【编码方式一致】
        decode() 解码:二进制转换成为字符串
        encode() 编码:字符串转换成为二进制

    mystr[x:y] #可省,表示截取
    mystr[x] #获取单个字符
    换行是一个字符,负索引
    字符串单个元素不能够赋值
    转义字符
    字符串加法:连接;乘法:乘以常数,表示重复
    字符串间是否包含:in   /   not in   contain()


    编码问题:中文包含使用UTF-8,空间占用较大
    路径前添加r 和处理转义字符效果一致,不能处理"
    center():居中
    find("str",start,end):查找  rfind():找到最后一个,位置关系一致
    count():出现次数("str",start,end)从start开始到end终止,出现str次数
    index():是否存在,不存在异常    rindex():

    endswith():判断后缀
    expandtabs():将tab符转换成为空格,默认8个

    字符串相关函数:
        汉字没有大小写 isLower()...  upper() lower()
        min()  max() :取出字符串中的最小最大字符


    join():链接字符串,每个字符间添加间隔
    rjust():左边填充【链接在右边】
    ljust():右边填充【链接在左边】
    replace(old,new,max):新替换旧不超过max次
    strip() rstrip() lstrip():去掉空格,左右/右/左
    split("str",count):按照str切割count次,返回list
    splitlines():按照行数切割
    startwith():以什么开始
    swapcase():大小写切换
    zfill(count):填充占位,到count长
    translate(instr,outstr):将字符串中instr字符串中字符替换成为outstr中对应的字符
print(format("1", "10s"), "1")
print(format("12", "10s"), "12")
print(format("123", "10s"), "123")
print(format("12345", "10s"), "12345")

# d 整数   f:浮点数  s:字符串  c:字符     %e:指数
# %.2f:两位小数
# %-010.4f :表示最大宽度为10,左对齐
# 小数点保留4位的浮点数,左边默认填充空格,添0占位
# %% 表述输出一个%


year = 2017
num = 10
mystr = "倒计时%d天过%d的春节" % (num, year)
print(mystr)

print(dir(""))

mylist = dir("")
print(mylist[0])

for i in mylist:
    print(i)
    print(help("\"\"." + i))
    print(help("str." + i))

模板

from string import Template

print(type(Template))

mystr = Template("hi,$name 你是 $baby")
print(mystr.substitute(name="彭于晏", baby="超级巨星"))


6、其它数据类型


    list
    有点类似字符串

    list可以容纳变量
    tuple 不可以修改内部的值

    集合set:集合的运算  交并差
        交:共有的
        并:组合全部,重复留一份
        差:被有被减没有的
    字典dict  map  key-value  key唯一

    eval():转换字符串为数字,包括表达式
    exec():
mylist = [1, 2, 3, 4]
print(mylist)
print(type(mylist))

tupletemp = (1, 2, 3, 4)
print(tupletemp)
print(type(tupletemp))

set1 = {1, 2, 3, 5}
set2 = {3, 6, 8, 9}

print(set1 - set2)

mydict = {"1234": "jzhnkj", "jabcjah": "nbvkjak", "132": 6366}
print(mydict)

for key in mydict:
    print(key, mydict[key])

mylist = [1, 2, 3, 4, 5, 6]

print(1 in mylist)  # 存在 不存在的判断
print(10 not in mylist)

mylist = [x * x for x in range(1, 10)]
print(mylist)

mylist = [x * 2 for x in range(1, 10)]  # 偶数集合
print(mylist)

print(list((1, 2, 3, 4)))  # (1,2,3,4)  元祖  数据转换
print(repr(1 + 2 * 3 + 4))  # repr计算一个表达式
print(1 + 2 * 3 + 4)

print("16", 10)
print(int("16", 10))  # 按照进制转换
print(int("16", 8))

# frozenset
import os

exec('print("hello world")')

mystr = 'os.system("notepad")'
exec(mystr)


三、python操作数据库


前提是安装了MySQL,并创建了要使用的数据库。

# -*- coding: utf-8 -*-
import pymysql

conn = pymysql.connect('localhost', 'root', '123qwe', 'pythondb', charset="utf8")

'''
数据库的增删改查
'''
# 使用cursor()方法获取操作游标
cursor = conn.cursor()
# 使用execute方法执行SQL语句 【 数据库的版本 】
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取一条数据
data = cursor.fetchone()
print("Database version : %s " % data)


'''
创建表格
'''
# 如果数据表已经存在使用 execute() 方法删除表。
cursor.execute("DROP TABLE IF EXISTS user")

# 创建数据表SQL语句
sql = """CREATE TABLE user (
         name  CHAR(20) NOT NULL,
         home  CHAR(20),
         age INT,  
         sex CHAR(1),
         income FLOAT )"""

cursor.execute(sql)

# SQL 插入语句【将bean数据拆分插入】
sql = """INSERT INTO user(name,
         home, age, sex, income)
         VALUES ('vision', 'moon', 20, 'M', 2000)"""
# 执行sql语句
cursor.execute(sql)


# SQL查询语句【查询结果拆解组装】
sql = """SELECT * FROM user"""
cursor.execute(sql)
rows = cursor.fetchall()
for i in rows:
    print(i)


四、GUI模块


当前python使用的是3.6.0版本,其他版本导入方式使用:(对应注释去除)

try:
    from tkinter import *
    '''
    except ImportError:  #Python 2.x
    PythonVersion = 2
    from Tkinter import *
    from tkFont import Font
    from ttk import *
    from tkMessageBox import *
    import tkFileDialog
    '''
except ImportError:

  #Python 3.x
    PythonVersion = 3
    from tkinter.font import Font
    from tkinter.ttk import *
    from tkinter.messagebox import *


1、绘制正方体


import turtle

#绘制两个底面之一
turtle.goto(200,0)
turtle.goto(200,200)
turtle.goto(0,200)
turtle.goto(0,0)

turtle.penup()
turtle.goto(100,100)
turtle.pendown()

#绘制两个底面之二
turtle.goto(100,-100)
turtle.goto(-100,-100)
turtle.goto(-100,100)
turtle.goto(100,100)


#绘制底面之间连接线
#第一条线
turtle.goto(200,200)

#第二条线
turtle.penup()
turtle.goto(0,200)
turtle.pendown()
turtle.goto(-100,100)

#第三条线
turtle.penup()
turtle.goto(-100,-100)
turtle.pendown()
turtle.goto(0,0)


#第四条线
turtle.penup()
turtle.goto(200,0)
turtle.pendown()
turtle.goto(100,-100)

turtle.done()


2、绘制五角星


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)
turtle.right(144)

turtle.done()

python基础总结mind图


曾经的不舍和纠结,
好像一个个形态各异的标点,
是是非非,起起落落,
其实就是一种标注,一个符号而已。
相信人生不会亏待你,
你吃的苦,你受的累,你掉进的坑,你走错的路,
都会练就独一无二成熟坚强感恩的你。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

壹叁零壹

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值