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 后面添加像删除的元素的位置
del fruit[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']
for fruit in fruits: #这个地方有冒号
print(fruit)
print("i love "+" "+ fruit)#如果这一行不缩进,则会认为是循环之外的语句
print("ending")
# 可以创建数字列表,对应的会有一些操作
#可以使用range来生成一系列的数字,用list转换成列表
numbers=list(range(1,9)) #生成1~8
print(numbers)
#切片
print(numbers[2:6])
#循环遍历切片
for number in numbers[6:]:
print(number)
digits=numbers
print(digits)
# while 循环 要先赋值
number=0
while number<10:
number+=1
print(number)
# 使用break 可以跳出循环 continue t
stag=True
numbers=0
while stag==True:
print("hello")
numbers+=1
if numbers==3:
break
# 使用while 来处理列表和字典
fruit=['apple','banana','orange']
while 'apples' in fruit:
fruit.remove('apple')
print(fruit)
responses={}
stag=True
while stag:
name='lihua'
response='yes'
responses[name]=response
if response=='yes':
stag=False
if responses["lihua"]=='yes':
print(responses)
#选择结构
age=19
if age<18:
print("yes")
## 并列使用and 或者使用的是or
if age>18 and age<99:
print("yes")
numbers=list(range(1,9)) #生成1~8
# 使用in 或者 not in 来查看元素是否在列表中
if age in numbers:
print("true")
if age not in numbers:
print("false")
# if-else 条件
if age>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)
for key,value in message:
print(key)
student={"number":123456,"grade":96}
print(student)
print(student["grade"])
print(student.items()) #items 返回键值对的列表
for key,value in student.items(): #循环遍历字典的时候记得转换成列表
print(key)
print(value)
# 字典的嵌套,
# 列表中嵌套字典
apple={"colour":"red","struct":"yuan"}
bannan={"colour":"yello","struct":"chang"}
xigua={"colour":"green","struct":"qiu"}
fruits=[apple,bannan,xigua]
for fruit in fruits:
print("fruit is "+fruit["colour"])
# 字典中嵌套列表
languages={"xiaoming":['c++','python'],
"xiaohong":['c',"c++"],
"lihua":["java","php"]
}
print(languages)
for lag ,ne in languages.items():
print(lag)
for nes in ne:
print(nes[0])
#字典中嵌套字典
users={"lihua":{"first":"2000","last":"2001"},
"xiaoming":{"frist":"2002","last":"2003"}
}
for user,se in users.items():
print(user)
print(se)
for key,value in se.items():
print(key)
print(value)
输入
# 输入input,input输入会被解释为字符串
name = input("please input your name")
print(name)
函数
# 函数 使用def 来定义函数
def inputs():
print("hello world")
inputs()
#传递参数
def inputs(names):
print("you name is "+ names)
inputs("lihua")
# 函数返回值
def isdog(dog):
if dog=="dog":
return True
else:
return False
if isdog('dog'):
print("it is dog")
def get_name(names):
for name in names:
print("hello "+name )
if name=="apple":
names.remove(name)
fruit=['apple','banana','orange']
get_name(fruit)
print(fruit)
# 如果不想修改列表 使用切片创建副本
def get_name(names):
for name in names:
print("hello "+name )
if name=="apple":
names.remove(name)
fruit=['apple','banana','orange']
get_name(fruit[:]) #使用切片来创建副本。不会改变原来列表的元素
print(fruit)
#传递任意数量的实参 * 返回值将封存在元组当中
def make_pizza(*topping):
print(topping)
make_pizza("1","2","3")
#可以将函数封装在模块当中,使用import来调用函数,导入的函数如果重名可以使用as来更改名称
类
#类
class Dog():
def __init__(self,name,age): #初始化方法执行程序时会自动调用
self.name=name
self.age=age
def ShowAge(self):
print("the dog age is "+str(self.age))
def Hello(self):
print("say hello")
dog=Dog("wangwang",3)
dog.ShowAge()
dog.Hello()
print(dog.name)
文件
#文件
with open('digits.txt') as file_object:
contents=file_object.read()
print(contents)
#逐行读取
with open('digits.txt') as file_object:
for line in file_object:
print(line.rstrip())
#创建一个包含文件各行内容的列表
with open('digits.txt') as file_object:
lines=file_object.readlines() #从文件中读取每一行,并存储在列表中
for line in lines:
print(line.rstrip())
#写入文件
with open('love.txt','w') as file_object:
file_object.write("i love you\n")
file_object.write("but you no love\n")
#附加到文件 ,不覆盖原来的内容
with open('love.txt','a') as file_object:
file_object.write("i love you\n")
file_object.write("but you no love\n")
n(‘love.txt’,‘w’) as file_object:
file_object.write(“i love you\n”)
file_object.write(“but you no love\n”)
#附加到文件 ,不覆盖原来的内容
with open(‘love.txt’,‘a’) as file_object:
file_object.write(“i love you\n”)
file_object.write(“but you no love\n”)