python入门基础语法学习笔记

本文详细介绍了Python的基础语法、类型转换、字符串操作、列表与字典的使用、集合运算、赋值机制、判断与循环、函数、模块、异常处理、文件操作、类与继承,以及时间模块等内容,适合Python初学者和进阶者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基础语法

类型转换

a = 3.3
int(a)
b = 123
str(b)#转换成字符型
round(15.4)#四舍五入

字符串部分操作

str1='1,2,4'
str1.split(',')#以逗号为分隔符号  ['1', '2', '3']
str2=' '
str2.join(str1)#合并
str1=str1.replace('4','3')#将4替换成3
str.upper()#大写
str.lower()#小写
str.isalpha()#逐个检查 是字母返回Ture
str.isdigit()#逐个检查 是空格返回Ture
s2.find(s1)#找到s1在s2中的位置
str.lstrip() #去除空格 右边:str.rstrip()

list列表

a = [1,'2',3.0,4]#创建列表 基本什么类型的元素都可以
a[0]#索引第一个 
a[1:]#第二个到最后一个   
a[-1]#是最后一个
a=[1,2,3,4,5]
a[2:4]#[3,4]
del a[0]#删除第一个
3 in a#判断3是不是a中的值 返回True 和 False
b=[1,2,[3,4]]
b[2][1]#4
b.count(1)#1出现了多少次
a.index(1)#找索引 0
a.append('hello')#a里面添加‘hello’ 一次添加只能一个元素或者一个列表
a.insert(2,'hello')#在第二个后面插入‘hello’ a[2] = 'hello'
a.remove(1)#有多个的时候去除第一个
a.pop(1)#弹出元素1并删除
a.sort()#排序 原顺序变了
c=sorted(a)#排序后成为c a原来顺序不变
a.reverse()#顺序颠倒

字典 没有先后顺序

a={}#空集合
a=dict({1:2,2:3})
b=[12]
c=[34]
d=dict([b,c])#{1: 2, 3: 4}
a['hello']='world'#添加 a = {1: 2, 2: 3, 'hello': 'world'} vaule可以是别的元素也可以是一个字典
a['hello']='1'#更新 a = {1: 2, 2: 3, 'hello': '1'}
a['hello']#'world'
a[1]+=1 #1对应的就是3了
a.pop(1)#删除1:
b={3:4}
a.update(b)#更新,添加
1 in a#判断里面有没有键1
a.keys()#a字典里面的键
a.values()#a字典里面的值
a.items()#a字典

集合

t = [1,1,3,4]
t=set(t)#t={1,3,4} 同样元素只保留一个
t=set([1,2,3,4,4])#t = {1, 2, 3, 4} 自动排序
a={1,2}
b={2,3}
a.union(b) a|b#并集
a.intersection(b) a&b#交集
a.difference(b)  a-b #a中有b中没有的
b.issubset(a)#b是不是a的子集 返回True/False
a.add(4)#添加元素
a.update([4,5,6])#更新添加
a.remobe(2)#删除
a.pop()#弹出 不能填参数 弹出第一个

赋值机制

a=1
b=1#id(a)和id(b)是一样的 共用内存
a=1000
b=1000#id(a)和id(b)是不一样的 不共用内存 小的数公用内存 大的数就不一定

判断

a=1000
if a > 50:
    print('A')
elif 50>a>20:
	print('B')
else:
	print('S')

循环

a=0
while a < 10:
    print(a)
    a += 1
a=set([1,2,3])
for i in a:
    print(i)
a=[1,2,3,4,5,6]
for i in range(6)#0到5
    print(a[i])

函数

def add(a,b):#定义函数名及参数
    print(a+b)
    return (a+b)
a=4
b=6
c=add(a,b)#c=return (a+b)
def add1(a,*args):#表示参数不确定 可以很多个
def add2(a,**kwarge):#只能用键值对 add2(1,x=2,y=3)
return a,i#可返回多个值

模块

%%writefile 1.py #写入文件1.py
a=3
print(a)

%run 1.py#运行

import 1#调用之前保存的一个文件
print(a)

import 1 as 2#别名
from 1 import a#从文件1中调用a

异常

import math
for i in range(10):
    try:
        a=input('number')
        if a == '1':
            break
        result=math.log(float(a))
        print(result)
    except ValueError:#单独对应这种异常处理办法
        print('ValueError')#输入0 输出ValueError 不报错

except exception:#包含所有异常情况
	print('error')


try:
    print('hello')
finally:
    print('finally')#无论异常不异常 都会执行 一般是保存文件 防止异常后没保存
except exception:
	print('error')

文件操作

txt = open('./123.txt')#打开当前位置下的123.txt
txt_read=txt.read()
print(read)#全部读出来
line=txt.readlines()
print(line)#一行一行读 是list类型
txt.close()#关闭

txt = open('./123.txt','w')#写  w从头开始写 覆盖  a 追加
txt.write('123\n')
txt.close()

with open('./123.txt') as f:#用with的方法不用f.close()
    f.read()

class people:#定义一个类
    def __init__(self,name,age):#构造函数 self调用时不用输入参数
        self.name=name
        self.age=age
    def display(self):
        print(self.name)
p1 = people('a',20)
p2 = people('b',30)

p1.display()#调用函数 输出a
p1.name = 'c'#可以更改
hasattr(p1,'name')#p1里面有没有name这个属性 返回True/False
getattr(p1,'name')#'a'
delattr(p1,'name')#删除这个属性

继承

class parent:#定义父类
    def __init__(self):
        print('调用父类构造')
    def parentM(self):
        print('调用父类方法')
    def setAttr(self,attr):
        parent.parentAttr = attr
    def getAttr(self):
        print('属性:',parent.parentAttr)
    def newM(self):
        print('重写夫')

class child(parent):
    def __init__(self):
        print('调用子构造')
    def childM(self):
        print('调用子方法')
    def newM(self):
        print('子重写')
c = child()#调用子构造
c.childM()#调用子方法
c.parentM()#调用父类方法(因为子类中没定义这个函数)
c.setAttr(100)
c.getAttr()#属性: 100
c.newM()#父子函数重名 输出的是子重写 即调用的是子类的函数

时间模块

import time#调用时间库
print(time.time())#1970年1月1号开始到现在
time.localtime(time.time())#现在时间 time.struct_time(tm_year=2021, tm_mon=5, tm_mday=30, tm_hour=17, tm_min=45, tm_sec=22, tm_wday=6, tm_yday=150, tm_isdst=0)

time.asctime(time.localtime(time.time()))#'Sun May 30 17:48:05 2021'
time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))#'2021-05-30 17:48:17'

import calendar#日历
calendar.month(2021,11)#输出这个月的日历
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值