Python基础

一、变量及简单的数据类型

1、字符串

name = "aaaaa"
a = "bbb bbbb"
print(a)
name.title()  #以首字母大写的方式显示每个单词
name.upper() #全部大写
name.lower()  #全部小写
c = f"{name}{a}"  #(3.5以前的版本)合并两个字符串
d = "{}{}".format(name,a) #(3.5后的版本)合并两个字符串
print("\tpython")  #\t制表符
a = a.rstrip()  #删除字符串末尾的空白
a.lstrip() #删除字符串开头的空白
a.strip() #删除字符串两边的空白

二、列表

列表:
1、列表中的类型需统一;元素都存在一个[ ]内;无限长度的数据结构

table = ['v','a','o','d']  #索引从0开始,索引为-2时,表示列表倒数第二个元素
table1=[] #创建空列表
table[0]="raaa" #修改列表中的元素
table.append('e') #在列表末尾添加元素
table.insert(2,'insert') #在列表中添加元素
del table[2] #删除列表中指定元素
table = table.pop() #删除列表末尾的元素
str1 = table.pop(1) #删除列表中指定要删除的元素,括号里为该元素的索引
#pop和del的区别:del是从列表中彻底删除一个元素,若后续还想继续使用该元素,则使用pop就可
table.remove(raaa) #删除指定元素,此方法只删除第一个指定的值,若要删除的值在列表中出现多次,需要使用循环来删除
table.sort() #永久性地修改元素的排列顺序,正序
table.sort(reverse=True) #倒序排列
table.sorted() #对列表临时排序
table.reverse() #翻转列表元素的排列顺序
len(table) #获取列表的长度,计算长度时,从1开始加

三、操作列表

1、列表相关操作

table = ['v','a','o','d']
min(table) #列表最小值
max(table) #列表最大值
sum(table) #列表求和

#循环打印
for t in table:
	print(t)
for t in range(1,5):  #只会打印1~4
	print(t)

#从2开始打印,每次加2,一直打到20
for t in range(2,20,2):  
	print(t)

# ** 表示乘方	
a = 5
b = a**5 

table[0:3]  #列表切片,选中列表中的前三个元素

 #打印列表第一个到第三个元素,[2:] 表示从第三个到最后一个元素,[-3:]表示
for t in table[:3]: 
	print(t)

table1 = table[:] #复制列表

2、元组

1、若要定义只包含一个元素的元组,必须在这个元素后面加上逗号:my_t=(3,)
2、不可给元组赋值
3、可以给存储元组的变量赋值,所以如果要修改最后一个元素之前的元素,则需要重新定义整个元组

四、字典及嵌套

1、字典

dic = {'color':'red','points':5}
dic['color']  #获取某一键值对的值
dic['add'] = 100 #自动添加到字典的最后一位,字典中元素的排列与定义时相同
dic1 = {}  #建立空字典
dic['color'] = 'yellow'#修改字典中的值
del dic['points'] #删除键'points'及其值,使用del语句必须指定字典名和要删除的键,删除的键值对会永远消失
value = dic.get('points','no result')#如果字典里有键’points‘,将获得与之相关的值,若没有,则获得指定的默认值

#遍历字典
for key1,value1 in dic():
    print(f"\nkey:{key1}")
    print(f"Value:{value1}")

#按特定顺序遍历字典中的所有键
for key in sorted(dic.keys()):
    print(key.title())

#遍历字典中的所有值
values()# 返回值列表
for value in dic.values():
    print(value)
"""
可以使用set()函数,剔除集合中的重复值,set集合中的每个元素都是独一无二的,
可以这么写:set(dic.values())得到的集合就是独一无二的啦
"""

2、嵌套

for value in dic.values():
	if value = 9
		print("yeyeyeyeyeye!")
	elif value = "red"
		print("I am red wolf")

五、用户输入和while循环

input() #让程序暂停运行一会儿,等待用户输入一些文本,用户输入的内容自动解读为字符串
message = input()  #用户自己手动输入
print(message)
message = input("111aaaaaakrioeqgjoegouebguob......")  #直接赋值
print(message)

int() #获取数值输入
num = int(message)     #把字符串转换成数值

while citynum < 100:
    citynum = int()

    if citynum == 1:
        break   #跳出循环
    elif citynum == 2:
        continue   #忽略后续的代码,开始下一次循环

#陷入死循环时,点击一下输出框,可按ctrl+c

#删除为特定值的所有列表元素
pets = ["cat","dog","dog","rabbit","cat"]
while 'cat' in pets:
    pets.remove('cat')
print(pets)

#使用用户输入来填充字典
respones = {}
respone = input()
name = input()
respones[name]=respone
for name,respone1 in respones.items():

"""
items函数可以历遍出dict内的key和value,并以一对为元组的形式,组成一个list,具体例子如下
注意点:输出的结果,是以key对应value包含在一个元组,以元组为元素的一个list
"""

六、函数

后续再补

七、类

class Dog:
    def __init__(self,name,age):
        self.name = name
        self.age = age
        self.long = 1
"""
(1)方法_init_()
- 每次使用Dog类创建新实例时,会自动运行这个方法
- 该方法中包含任意个参数,self参数必须置于首位
- 参数中包含self的原因:每个与实例相关联的方法调用都自动传参self,它是一个指向实例本身的应用
- 每次创建实例时,只需给除self的参数提供值即可
"""
    def sit(self):
        print(f"{self.name} is now sitting.")
    
    def roll_over(self):
        print(f"{self.name} rolled over!")   

	def read length(self):
		printf(f"dog body's length is {self.long}")
	
	1、通过直接修改属性值来修改参数的默认值
	Dog.long = 2
	2、通过方法修改参数的默认值
	def update_long(self,long):
		self.long = long

#子类
class dog:
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def sit(self):
        print(f"{self.name} is now sitting.")

    def roll_over(self):
        print(f"{self.name} rolled over!")

    def increment_long(self,length):
        self.long +=length

#继承dog类
class super_dog(dog):
    def __init__(self,name,age):
        super().__init__(name,age)

    def descirbe_dog_detail(self):
        print(f"This dog'name is {self.name}.He is {self.age} years old")

    #重写父类的方法,一旦重写,将不会进行子类中方法的内容
    def sit(self):
        print("no")
superDog = super_dog("hello",2)
superDog.descirbe_dog_detail()
superDog.sit()
"""
导入类
(1)导入单个类:from car import car
(2)在一个模块中存储多个类
electric_car.py
class car:
class ElectricCar:
class battery:
(3)从一个模块中导入多个类:from car import car,ElectricCar
(4)使用别名:from car import car as Car
"""

八、文件和异常

#1、从文件中读取数据
#读取整个文件
with open('a.txt') as file_object:
    contents = file_object.read()
print(contents)
print(contents.rstrip())
"""
(1)open()参数接受一个参数:要打开文件的名称
(2)整行代码的解释:open('a.txt')返回一个标识文件a.txt的对象,python将该对象赋给file_project供以后使用
(3)关键字with在不需要访问文件后将其关闭;
    也可使用open()和close()打开和关闭文件,但是若代码出现bug,则文件将不会关闭,未妥善的关闭文件可能会导致文件内容丢失或受损;
    若过早的调用close(),可能会产生在想使用时发现文件已关闭(无法访问)的情况,会导致更多的问题
(4)read()到达文件末尾时返回一个空字符串,这个空字符串就是结果中的最后一行空行,想删除,可在函数调用print()中使用rstrip()
"""

#文件路径
file_path1 = '/pythonProject/a.txt'#相对文件路径
file_path2 = 'C:\Users\Wheat\PycharmProjects\pythonProject\a.txt' #绝对文件路径
with open(file_path1) as file_object:
with open(file_path2) as file_object:

#逐行读取
filename = 'a.txt'
with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip())

#使用文件的内容
filename = 'a.txt'
with open(filename) as file_object:
    for line in file_object:
        lines = file_object.readline()
pi_string = ''
for line in lines:
    pi_string += line.rstrip()/line.strip()

print(pi_string)
print(len(pi_string))

#包含一百万位的大型文件
filename = 'million_a.txt'

with open(filename) as file_object:
    lines = file_object.readline()
pi_string = ''
for line in lines:
    pi_string += line.strip()
print(f"{pi_string[:52]}.....")#创建的字符串确实包含精确到小数点后1000000位的圆周率值
print(len(pi_string))

#字符串中是否包含某字符串
numb = '12345'
if numb in pi_string:
    print("yes")
else:
    print("no")
2、写入文件
调用open()时提供了两个实参。:
第一个实参是打开的文件的名字;
第二个实参用来指定模式,r 读取模式    w 写入模式    a 附加模式   r+读写模式
"""

#写入空文件
filename = 'programming.txt'

with open(filename,'w') as file_object:
    file_object.write("heiheihei.")
3、异常处理
#try-except代码块:使用异常避免崩溃
while True:
    first_nub = input()
    second_nub = input()
    try:
        answer =  int(first_nub)/int(second_nub)
    except ZeroDivisionError:
        print("nonononono")
    else:
        print(answer)

#处理FileNotFoundError异常
filename = 'aaaaa.txt'
try:
    with open(filename,encoding='utf-8') as f:
        contents = f.read()
except FileNotFoundError:
    print(f"Sorry,the file {filename} does not exist.")

#分析文本
filename = 'alice.txt'

try:
    with open(filename,encoding='utf-8') as f:
        contents = f.read()
except FileNotFoundError:
    print(f"sorry,not exist")
else:
    words = contents.split()
    num_words = len(words)
    print(f"the file has {num_words} words")

#使用多个文件
def count_words(filename):
    try:
        with open(filename,encoding='utf-8') as f:
            contents = f.read()
    except FileNotFoundError:
        print(f"sorry,not exist")
    else:
        words = contents.split()
        num_words = len(words)
        print(f"the file has {num_words} words")
filename = ['alice.txt','siddhartha.txt','moby_dick.txt']
for filename in filenames:
    count_words(filename)

#静默失败
def count_words(filename):
    try:
        with open(filename,encoding='utf-8') as f:
            contents = f.read()
    except FileNotFoundError:
        pass #充当了占位符,提醒你再程序的某个地方什么都没有做,并且以后也许要在这里做些什么;若代码出错也不会有任何的报错
    else:
        words = contents.split()
        num_words = len(words)
        print(f"the file has {num_words} words")
filename = ['alice.txt','siddhartha.txt','moby_dick.txt']
for filename in filenames:
    count_words(filename)
#3、存储数据
#json.dump()和json.load()
import json
numb = [2,3,4,5,6,7]
"""
json.dump()的两个参数含义:存储的数据、用于存储数据的文件对象;
用写入模式打开这个文件,让json把数据写入文件中,使用函数将数字列表存储到文件numbers.json中
"""
filename = 'numbers.json'
with open(filename,'w') as f:
    json.dump(numb,f)
"""
json.load():加载存储在numbers.json中的信息,并将其赋给变量numbers
"""
with open(filename)as f:
    numb = json.load(f)

#保存和读取用户生成的数据
import json
username = input()
with open(filename,'w') as f:
    json.dump(username,f)
    print(username)
with open(filename) as f:
    username = json.load(f)
    print(username)
    
#重构上方代码,使其更优
import  json

def get_stored_username():
    filename = 'username1.json'
    try:
        with open(filename) as f:
            username = json.load(f)
    except FileNotFoundError:
        return  None
    else:
        return username


def get_new_username():
    username = input('please input your name')
    with open(filename,'w') as f:
        json.dump(username,f)
    return username

def great_user():
    username = get_stored_username()
    if username:
        print(username)
    else:
        username = get_new_username()
        print(username)
        
great_user()

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值