python基础语法笔记

Python 学习


列表--增删改查


#列表

fruit=['apple','banana','orange']

print(fruit)

#访问单个元素,类似数组的访问

print(fruit[2])

# 可以有负数,比如-1就是倒数第一个元素,-2就是倒数第二个元素

print(fruit[-2])

#插入,删除,修改操作

#插入,append在最后位置插入元素

fruit.append("pear")

print(fruit)

#insert 在指定位置插入元素

fruit.insert(0,"watermelon")

print(fruit)

#删除 del 后面添加像删除的元素的位置

delfruit[1]

print(fruit)

#使用pop 来删除元素,pop可以拿到这个元素并删除,pop可以添加索引,默认是最后一个元素

fruit_love=fruit.pop()

print(fruit)

print(fruit_love)

#根据元素名称来删除元素 remove

fruit.remove("watermelon")

print(fruit)

操作列表,选择循环结构


# 循环结构,注意缩进 python的缩进会影响程序的执行

fruits=['apple','banana','orange']

forfruitinfruits: #这个地方有冒号

print(fruit)

print("i love "+" "+fruit)#如果这一行不缩进,则会认为是循环之外的语句

print("ending")

# 可以创建数字列表,对应的会有一些操作

#可以使用range来生成一系列的数字,用list转换成列表

numbers=list(range(1,9)) #生成1~8

print(numbers)

#切片

print(numbers[2:6])

#循环遍历切片

fornumberinnumbers[6:]:

print(number)

digits=numbers

print(digits)

# while 循环 要先赋值

number=0

whilenumber<10:

number+=1

print(number)

# 使用break 可以跳出循环 continue t

stag=True

numbers=0

whilestag==True:

print("hello")

numbers+=1

ifnumbers==3:

break

# 使用while 来处理列表和字典

fruit=['apple','banana','orange']

while'apples'infruit:

fruit.remove('apple')

print(fruit)

responses={}

stag=True

whilestag:

name='lihua'

response='yes'

responses[name]=response

ifresponse=='yes':

stag=False

ifresponses["lihua"]=='yes':

print(responses)

#选择结构

age=19

ifage<18:

print("yes")

## 并列使用and 或者使用的是or

ifage>18andage<99:

print("yes")

numbers=list(range(1,9)) #生成1~8

# 使用in 或者 not in 来查看元素是否在列表中

ifageinnumbers:

print("true")

ifagenotinnumbers:

print("false")

# if-else 条件

ifage>18:

print("you can take part in voting")

else:

print("you too young")

# if-elif-else 条件 用法和上面类似

元组

#元组 不可变的元素 使用()

length=(100)

print(length)

#这里会报错,不允许修改

# length[0]=99

# print(length)

不同括号的作用


字典


#字典 {}

message=[("lihua",19),("liming",20)]

print(message)

forkey,valueinmessage:

print(key)

student={"number":123456,"grade":96}

print(student)

print(student["grade"])

print(student.items()) #items 返回键值对的列表

forkey,valueinstudent.items(): #循环遍历字典的时候记得转换成列表

print(key)

print(value)

# 字典的嵌套,

# 列表中嵌套字典

apple={"colour":"red","struct":"yuan"}

bannan={"colour":"yello","struct":"chang"}

xigua={"colour":"green","struct":"qiu"}

fruits=[apple,bannan,xigua]

forfruit infruits:

print("fruit is "+fruit["colour"])

# 字典中嵌套列表

languages={"xiaoming":['c++','python'],

"xiaohong":['c',"c++"],

"lihua":["java","php"]

}

print(languages)

forlag ,neinlanguages.items():

print(lag)

fornesinne:

print(nes[0])

#字典中嵌套字典

users={"lihua":{"first":"2000","last":"2001"},

"xiaoming":{"frist":"2002","last":"2003"}

}

foruser,seinusers.items():

print(user)

print(se)

forkey,valueinse.items():

print(key)

print(value)

输入


# 输入input,input输入会被解释为字符串

name = input("please input your name")

print(name)

函数


# 函数 使用def 来定义函数

definputs():

print("hello world")

inputs()

#传递参数

definputs(names):

print("you name is "+names)

inputs("lihua")

# 函数返回值

defisdog(dog):

ifdog=="dog":

returnTrue

else:

returnFalse

ifisdog('dog'):

print("it is dog")

defget_name(names):

fornameinnames:

print("hello "+name )

ifname=="apple":

names.remove(name)

fruit=['apple','banana','orange']

get_name(fruit)

print(fruit)

# 如果不想修改列表 使用切片创建副本

defget_name(names):

fornameinnames:

print("hello "+name )

ifname=="apple":

names.remove(name)

fruit=['apple','banana','orange']

get_name(fruit[:]) #使用切片来创建副本。不会改变原来列表的元素

print(fruit)

#传递任意数量的实参 * 返回值将封存在元组当中

defmake_pizza(*topping):

print(topping)

make_pizza("1","2","3")

#可以将函数封装在模块当中,使用import来调用函数,导入的函数如果重名可以使用as来更改名称


#类

classDog():

def__init__(self,name,age): #初始化方法执行程序时会自动调用

self.name=name

self.age=age

defShowAge(self):

print("the dog age is "+str(self.age))

defHello(self):

print("say hello")

dog=Dog("wangwang",3)

dog.ShowAge()

dog.Hello()

print(dog.name)

文件


#文件

withopen('digits.txt') asfile_object:

contents=file_object.read()

print(contents)

#逐行读取

withopen('digits.txt') asfile_object:

forlineinfile_object:

print(line.rstrip())

#创建一个包含文件各行内容的列表

withopen('digits.txt') asfile_object:

lines=file_object.readlines() #从文件中读取每一行,并存储在列表中

forlineinlines:

print(line.rstrip())

#写入文件

withopen('love.txt','w') asfile_object:

file_object.write("i love you\n")

file_object.write("but you no love\n")

#附加到文件 ,不覆盖原来的内容

withopen('love.txt','a') asfile_object:

file_object.write("i love you\n")

file_object.write("but you no love\n")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值