python 语言入门

python

基础篇

一. 运算符

1. 算术运算符
  • a+b,a-b,a-b,a*b,a/b
  • a%b,a**b,a//b
2. 比较运算符

假设a=10,b=20

  • (a==b)返回false;(a!=b)返回true
  • (a>b)返回false; (a<b)返回true
  • (a>=b)返回false; (a<=b)返回true
3. 赋值运算符

假设a=10,b=20

  • c=a+b
  • c+=a等于c=c+a
  • c-=a等于c=c-a
  • c*= a,c/= a c%=a ,c**=a,c //=a

    解:a,b=b,a
4. 逻辑运算符
  • and ; or ; not
5. 成员运算符
  • in
  • not in
6. 条件语句
  • if …else
7. 循环
  • while
  • for
8. 大杂烩
  • 变量值颠倒(python特有)
    • a=10 ,b=5 ,不引入第三个变量,交换ab的值
  • python 只传址 不传值(其他传统语言有区分)
    • 重新赋值时,重新开辟一个内存,建立新的指向(旧的指向断开)
  • 迭代器
list1=[1,2,3,4]
it=iter(list1)#创建了一个迭代器it
print(next(it))#输出list第一个值
print(next(it))#输出list第二个值

二. 列表(中括号)

  • 在列表结尾添加元素
list1=[1,2,3,4]
list1.append('a')
print(list1)#输出[1, 2, 3, 4, 'a']
  • 在列表结尾添加另一个列表
list2=['d','c']
list1.extend(list2)
print(list1)#输出[1, 2, 3, 4, 'a', 'd', 'c']
  • 在列表位置i处插入元素X:list.insert(i,x)
list1.insert(2,'e')
print(list1)#输出[1, 2, 'e', 3, 4, 'a', 'd', 'c']
  • 更新或删除列表中元素
list[2]=6666
del list[2]

  • 切片
    • list[start🔚sequence]
    • sequence>0,由左至右,若start>end,则为空
    • sequence<0,由右至左,若start<end,则为空
    • start为空,从开始走
    • end为空,走到最后
    • end不为空,取到end前一位
    • 全部为空,取整个list,顺序由sequence决定
string=['a','b','c','d']
list1=string[-1:-5:-1]
print(list1)#输出['d', 'c', 'b', 'a']
  • 练习
    • 去掉整数列表中重复的数
i=0
j=1
def Alone(list):
    global i
    global j
    if i<=len(list)-2:
        print(i)
        print(j)
        if j<=len(list)-1:
            if list[i]==list[j]:
                print("相等")
                list.pop(j)
                list.pop(i)
                i-=1
                Alone(list)
            else:
                j+=1
                Alone(list)
        else:
            print("  ")
            i+=1
            j=i+1
            Alone(list)

list=[100,2,3,3,4,88,44,66,33,44,99,88,66,99,4,5,6,6,5]
Alone(list)
print("列表是:",list)
print(i)
print(j)
i=0
j=1
def Alone(list):
    global i
    global j
    while i!=len(list)-1:
        while j<=len(list)-1:
            print(i)
            print(j)
            print('')
            if list[i] == list[j]:
                list.pop(j)
            else:
                j += 1
        i+=1
        j=i+1

list=[2,2,100,55,88,99,100,22,33,55,44,2]
print(len(list))
Alone(list)
print("列表是:",list)
list1=[55,34,76,23,56,45,54,54,55,76,88]
list2=[]
for i in range(0,len(list1)-1):
    print(" ")
    print(i)
    for j in range(i+1,len(list1)):
        print(j)
        if list1[i]==list1[j]:
            print(i,j,"相等")
            list2.append(list1[i])

print("list2",list2)

for i in range(len(list2)-1,-1,-1):
    print(i)
    for j in range(len(list1)-1,-1,-1):
        print(j)
        if list2[i]==list1[j]:
            print("删除",i)
            list1.pop(j)
print("list1",list1)

三. 元组

  • 组合元组
tup1=('A','B','C')
tup2=(1,3,122)
tup3=tup1 + tup2
print(tup3) #tup3为: ('A', 'B', 'C', 1, 3, 122)
  • 判断X是否存在元组中,返回真假
print('A' in tup1)#为true
print('F' in tup1)#为false
  • 元组长度
print(len(tup2))#长度为3
print(len(tup3))#长度为6
  • 元组中最大最小值
print(min(tup1))#返回A
print(max(tup2))#返回122
  • 将元组赋值给列表
list=tup1
print(list) #输出('A', 'B', 'C')
  • 删除元组
    • 元组的数值不可以被二次修改,不可被单个删除
      可以整个元组删除
del tup3
print(tup3) #返回NameError: name 'tup3' is not defined

四.字典

  • 字典基本类型
    • dict ={‘key1’:velue1,‘key1’:velue1}
  • 给字典类型赋值
dict={'name':'hu','Age':18,'class':'first'}
print(dict['name'],dict['Age'],dict['class'])#输出hu 18 first
  • 给字典加一个key和value
dict['school']='家里蹲大学'
print(dict['school'])
  • 输出字典的key
print(dict.keys())#输出:dict_keys(['name', 'class', 'Age'])
  • 输出字典的value
    print(dict.values())#输出:dict_values(['hu', 'first', 18])
  • 用for循环交替输出key和对应的value
for x in dict.keys():
    print(x,dict[x])

五.函数

  • 按照引用传递(要变都变)
def change_me(mylist):
    mylist.append(666)
    print('函数内',mylist)#函数内 [1, 0, 3, 666]

mylist=[1,0,3]
change_me(mylist)
print("函数外",mylist)#函数外 [1, 0, 3, 666]
  • 花式传参
def print_info(name,age=35):
    print(("姓名:%s,年龄:%d")%(name,age))

print_info(name="Ann",age=18)#姓名:Ann,年龄:18
print_info(age=50,name="dave")#姓名:dave,年龄:50
  • 花式返回
def calc(num1,num2):
    result1=num1+num2
   # print("result1=",result1)
    result2=num1-num2
   # print("result2=",result2)
    return result1,result2

r,rr=calc(6,2)
print("r=",r,"rr=",rr)#输出r= 8 rr= 4
m=calc(3,1)
print(m)#输出(4, 2)
  • 局部变量
total=0
def sum(arg1,arg2):
    total=arg1+arg2
    print("函数内是局部变量:",total)#函数内是局部变量: 30
    return total

sum(10,20)
print("函数外:",total)#函数外: 0
  • 全局变量
def sum(arg1,arg2):
    total=arg1+arg2
    print("函数内是局部变量:",total)#函数内是局部变量: 30
    return total

total=sum(10,20)
print("函数外:",total)#函数外: 30
counter=1
def doing():
    global counter
    for i in (1,2,3):
        counter+=1

doing()
print(counter)#输出4
  • range
    1. range(x) (起于0,终于x,公差是1)
       for i in range (5):
        print(i)#输出0,1,2,3,4
    
    1. for index in range(y,x) (起于y,终于x,公差是1)
       for i in range (0,5):
        print(i)#输出0,1,2,3,4
    
    1. for index in range(y,x,z) (起于y,终于x,公差是z)
       for i in range (2,10,3):
        print(i)#输出2,5,8
    
    

六.模块

  • 一个py文件就是模块
import Untitled2.py#引入后可调用模块内的函数
  • 一个模块只会被导入一次
  • 引入函数
from 文件名(py) import 函数名/类名
  • 引入文件
from 文件名 import 文件(py)
  • 将模块中的所有内容导入
from ...import *

七.文件读写

  • 打开一个文件
    file_object =  open(fileName,accessMode,encoding=None)
    #accessMode 打开文件模式,可选
    #encoding 默认为none,可选
    
    • w 写模式,它是不能读的,如果用w模式打开一个已经存在的文件,会清空以前的文件内容,重新写
    • w+ 是读写内容,只要沾上w,肯定会清空原来的文件
    • r 读模式,只能读,不能写,而且文件必须存在
    • r+ 是读写模式,只要沾上r,文件必须存在
    • a 追加模式,也能写,在文件的末尾添加内容
    • rb+、wb+、ab+,这种是二进制模式打开或者读取,一些音乐文件
  • 关闭一个文件
fo=open(r'C:\Users\test\Downloads\任务配置表.xlsx')
fo.close()
print("是否关闭了文件",fo.closed)#返回true
  • 文件的相对路径
fo.open('.\\file')#.在脚本所在的当前目录下
  • 打开文件,可写,并写入
fo=open(r'C:\Users\test\Downloads\任务配置表.xlsx',"w")
fo.write("小陶")#会覆盖掉文件本身的内容
fo.close()
  • 读写文件(读完写完后都关闭)
fo=open(r'C:\Users\test\Downloads\test.txt',"w")
fo.write("rrrrrr")
fo.close()
fo=open(r'C:\Users\test\Downloads\test.txt',"r")
str=fo.read()
print(str)
  • tell函数(告诉你文件内当前位置)
fo=open(r'C:\Users\test\Downloads\test.txt',"w")
fo.write("123456")
position= fo.tell()
print(position)#输出3
fo.close()
  • seek(offset,where)(改变当前位置)(where=0,文件开始;1,当前位置;2文件末尾)
fo=open(r'C:\Users\test\Downloads\test.txt',"rb")#在文本文件中,没有使用b模式选项打开的文件,只允许从文件头开始计算相对位置,从文件尾计算时就会引发异常,所以用rb模式
position=fo.seek(3,2)
print(position)#输出9
fo.close()
  • turncate(size)#从size处开始截断后面的内容
fo=open(r'C:\Users\test\Downloads\test.txt',"w+")
fo.write("123456")
fo.seek(0,0)
str=fo.read()
print(str)
position=fo.tell()
print(position)
position=fo.seek(3,0)
print(position)#输出9
fo.truncate(5)
str=fo.read()
print(str)#输出4,5

八.异常处理

  • try…else
logPath='C:\\Users\\test\\Downloads\\test.txt'
try:
    fh=open(logPath,"r")
    fh.write("我能写入吗")
except IOError as e:
    print("错误,无法读取文件!",str(e))
else:      #没有异常时执行else
    print("success")
    fh.close()
  • try …finally
logPath='C:\\Users\\test\\Downloads\\test.txt'
try:
    fh=open(logPath,"r")
    fh.write("我能写入吗")
except IOError as e:
    print("错误,无法读取文件!",str(e))
finally:      #有没有异常都执行finally
    fh.close()

九.访问excel的模块openpyxl

import openpyxl

table = openpyxl.load_workbook('Book1.xlsx')#打开要读取的excel文件,默认可读写
table.sheetnames # 获取当前所有工作表的名称, 返回一个列表
table.active  # 获取当前活跃的工作表 
sheet1 = table['sheetname']#获取页签名称为sheetname的表
print(sheet1.title)#获取工作表的名称

获取工作表中行和列的最值

print(sheet.max_column)
print(sheet.max_row)
print(sheet.min_column)
print(sheet.min_row)

修改表的名称

sheet.title = 'sheet1'
print(sheet.title)

返回指定行指定列的单元格信息

print(sheet.cell(row,column).value)

cell=testcase_table.cell(row,column)
print(cell.coordinate)#输出单元格的坐标

插入数据,并保存表格

sheet.cell(row,column).value=xx
table.save('Book1.xlsx')#不保存不会生效

十.大杂烩

  • random
import random
print(random.choice("1234567890"))#随机取数字
print(random.choice(["apple","pear","banana"]))#随机取字符串
  • glob 根据指定的通配符去搜索
import glob
print(glob.glob("E:\小强Python全栈\*.pdf"))#输出该路径下的全部pdf文件名
  • os
    • os.getcwd 获取当前目录
    import os
    print(os.getcwd())#输出E:\pythonproject
    
    • 其他函数
      image
      image
    • 【课堂练习】打印指定目录下所有的文件名(带路径)。统一为C:\Program Files
    for i in os.listdir("C:\\Program Files"):#listdir返回指定路径下的文件和文件夹列表
    path = os.path.join("C:\\Program Files",i)#将前后元素组合成路径后返回
    print(path)
    
    • 【课堂练习二】递归显示指定目录名以及子目录下的文件名。统一为C:\Program Files\Internet Explorer
    import os
    def show(path):
    for i in os.listdir(path):
        p=os.path.join(path,i)
        print("p:"+p)
        if os.path.isdir(p):
            print("是目录:"+p)
            show(p)
        else:
            print(p)
    show("C:\Program Files\Internet Explorer")
    

进阶篇

一. 面向对象

1. 类
    • 类的定义:class
    • 类的组成:方法,类变量,成员变量,局部变量
  • 对象
  • 类方法
    • 包含参数self,self必须作为第一个类方法的参数(包含构造方法在内)
  • 类变量
    • 定义在类里,方法外
    • 类名和对象都可调用
  • 成员变量
    • 类的对象来调用,由self.开头来定义,可在类的不同方法中使用
  • 局部变量
    • 方法中的普通变量,仅可以再该方法中使用
2. 构造方法和析构方法
  • 构造方法
    • init():每次生成一个新对象都会自动调用一次该方法
  • 析构方法
    • del():,删除清理操作,可选
class User:
    age=20#类变量
    def __init__(self):  #构造方法
        self.name="xiaotao" #成员变量
        print("name:",self.name)
    def say(self):  #类方法
        address="china"#say方法中的局部变量
        print("address=",address)#若想变量可以在类中的方法中使用,可以self.address
u = User()
print(u.age)
u.say()
  • 静态方法
    • 静态方法参数可为空
     @staticmethod
     def func():#可以没有参数
         print("静态函数")
    
    User.func()#可用类名调用静态方法
    
  • 课堂练习一
    • 定义一个员工类,创建对象时,对员工姓名和工资初始化,类中有两个方法,一个是打印员工的数量,一个打印员工的信息
class employee:
    number=0
    def __init__(self):
        employee.number+=1#不能用self.number
    def detail(self,name,salary):
        self.name=name
        self.salary=salary
        print("该员工的姓名和薪资是",name,salary)
    @staticmethod
    def count():
        print("目前有",employee.number,"个员工")
E=employee()
E.detail("xiaotao",520)
E1=employee()
E1.detail("xiaoLI",521)
employee.count()
  • 课堂练习二
    • 实现一个shape类(圆),用getArea方法计算面积,用getLong方法计算周长
import math
class Shape:
    r=0
    area=0
    long=0
    def __init__(self,r):
        self.r=r
    def getArea(self):
        self.area=math.pi*self.r*self.r
        return self.area
    def getLong(self):
        self.long=2*math.pi*self.r
        return self.long
circle=Shape(5)
circle.getArea()
print("面积是:",circle.area//1)#//是取整符号
circle.getLong()
print("周长是:",circle.long//1)
3. 类的继承
  • 类的继承格式
    • class Student(User):
  • 子类可以继承或者重写父类的方法
  • 子类可以自定义新的方法或成员变量
私有变量和方法
  • 私有变量
    • 不能在类的外部被使用或者直接访问
    • 声明方式:两个下划线开头
      • __private_attrs
    • 在类内部的方法中使用
      • self.__private_attrs
    class Info():
    def __init__(self):
        self.__name="xiaotao"
    def say(self):
        print(self.__name)
    a=Info()
    a.say()
    print(a.__name)#错误,不能在外部直接使用
    
  • 私有方法
    • 不能在类的外部调用
    • 声明方式:两个下划线开头
      • __private_method
    • 在类内部的方法中使用
      • self.__private_methods
    class Info():
    def __privateMethod(self):
        print("我是私有方法")
    def publicMethod(self):
        print("我是非私有方法")
        self.__privateMethod()
    a=Info()
    a.publicMethod()
    a.__privateMethod#不可以调用
    
    • 在python中没有真正的私有
    a._Info__privateMethod()#可以动用私有方法
    

二. python操作数据库

1. mysql以及sql语句基础
  • 连接数据库
import mysql.connector
try:
    con=mysql.connector.connect(
        host='10.0.0.53',
        user="ikukouser",
        password="111111",
        port=3306,
        database='ikukodev',
        charset="utf8",#标准编码格式
        buffered="True"#提交执行时立即生效。防止mysql读写提交数据缓冲的延时
    )
    print("数据库链接成功")
    cursor=con.cursor()#获取游标
except mysql.connector.Error as e:
    print("数据库链接失败",str(e))
  • 数据库(补充)
    • 登录
@>mysql -u root -p
  • 创建一个新用户
mysql@>CREATE USER username IDENTIFIED BY 'password';
  • 为这个用户分配所有权限
    • 授权格式:grant 权限 on 数据库.* to 用户名@登录主机 identified by ‘密码’;
mysql@>grant all privileges on test.* to root@172.16.12.122 identified by '123456';
  • 部分授权
grant select,update on test.* to root@...;
  • 调整权限后,通常需要执行以下语句刷新权限
mysql>flush privileges;
  • 删除刚才创建的用户
mysql>Delete FROM user Where User='root' and Host='localhost';

三. 多线程

实战篇

在当前类的函数里调用函数范围外,类里面的变量,要加self
Class Demo():
  a=1
  def fun():
    self.a
在当前类调用其他类,要先引进和实例化
import B 
Class Demo():
  a=1
  def fun():
    b=B()
    self.a
    b...
用python正则表达式提取字符串
import re
str = "a123b"
print re.findall(r'a(.+?)b',str)#
#输出['123'],返回了一个list类型
将list转化为整数或者str
  • “”.join
a=[‘a’,‘b’,‘c’]
b="".join(a)
print(b) #输出结果为 abc
  • map( )
map(“f”,“list”)
#map的用法是调用f的函数分别对list的元素不断地使用
  • 将list转化为整数或者str
a=['1111']
b=int("".join(map(str,a)))
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python 是一种简单而强大的编程语言,适合初学者入门。下面是18个高中学考中经典的Python程序示例。 1. 打印"Hello World":使用print函数输出文本。 print("Hello World") 2. 计算两个数字的和:使用加法操作符。 num1 = 10 num2 = 20 sum = num1 + num2 print("两个数字的和为:", sum) 3. 判断一个数是奇数还是偶数:使用取模操作符。 num = 15 if num % 2 == 0: print(num, "是偶数") else: print(num, "是奇数") 4. 计算一个数的阶乘:使用循环结构。 num = 5 factorial = 1 for i in range(1, num+1): factorial *= i print(num, "的阶乘为:", factorial) 5. 判断一个数是否是素数:使用循环和条件判断。 num = 7 is_prime = True for i in range(2, num): if num % i == 0: is_prime = False break if is_prime: print(num, "是素数") else: print(num, "不是素数") 6. 计算斐波那契数列:使用循环和递归。 def fibonacci(n): if n <= 0: return [] elif n == 1: return [0] elif n == 2: return [0, 1] else: fib_list = [0, 1] for i in range(2, n): fib_list.append(fib_list[i-1] + fib_list[i-2]) return fib_list n = 10 print("斐波那契数列前", n, "项为:", fibonacci(n)) 7. 计算圆的面积和周长:使用圆周率和半径的公式。 import math radius = 5 area = math.pi * radius ** 2 circumference = 2 * math.pi * radius print("圆的面积为:", area) print("圆的周长为:", circumference) 8. 判断一个年份是否是闰年:使用条件判断。 year = 2020 if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: print(year, "是闰年") else: print(year, "不是闰年") 9. 计算三角形的面积:使用海伦公式。 a = 5 b = 4 c = 3 s = (a + b + c) / 2 area = (s * (s - a) * (s - b) * (s - c)) ** 0.5 print("三角形的面积为:", area) 10. 判断一个字符串是否是回文:使用切片操作。 def is_palindrome(s): s = s.lower() return s == s[::-1] word = "level" if is_palindrome(word): print(word, "是回文") else: print(word, "不是回文") 11. 排序列表:使用sort方法或sorted函数。 nums = [5, 2, 8, 1, 3] nums.sort() print("升序排列:", nums) print("降序排列:", sorted(nums, reverse=True)) 12. 统计字符串中某个字符的个数:使用count方法。 s = "hello world" char = 'o' count = s.count(char) print(char, "在字符串中出现的次数为:", count) 13. 判断一个字符串是否是数字:使用isdigit方法。 s = "12345" if s.isdigit(): print(s, "是一个数字") else: print(s, "不是一个数字") 14. 计算列表中数字的平均值:使用sum和len函数。 nums = [1, 2, 3, 4, 5] average = sum(nums) / len(nums) print("列表中数字的平均值为:", average) 15. 反转字符串:使用切片操作。 s = "hello world" reversed_str = s[::-1] print("反转后的字符串为:", reversed_str) 16. 判断一个数是否是质数:使用函数封装循环和条件判断。 def is_prime(num): if num <= 1: return False for i in range(2, int(num ** 0.5) + 1): if num % i == 0: return False return True num = 13 if is_prime(num): print(num, "是质数") else: print(num, "不是质数") 17. 判断一个数是否是完全平方数:使用循环和条件判断。 def is_perfect_square(num): if num < 0: return False if num == 0 or num == 1: return True for i in range(2, int(num ** 0.5) + 1): if i * i == num: return True return False num = 16 if is_perfect_square(num): print(num, "是完全平方数") else: print(num, "不是完全平方数") 18. 判断一个年份是否是闰年:使用函数封装条件判断。 def is_leap_year(year): if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: return True else: return False year = 2020 if is_leap_year(year): print(year, "是闰年") else: print(year, "不是闰年") 这些程序示例可以作为Python入门经典必背,涵盖了常见的问题和算法,在高中学考中具有一定的考查可能。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值