一、miniconda的安装及环境配置
1、通过官网下载miniconda
2、创建环境:打开终端输入命令conda create -n test python=3.10创建一个名为test的虚拟环境
3、进入环境:输入conda activate test
4、退出环境:输入conda deactivate
二、VSCode的安装
1、通过官网下载
2、在左侧‘extensions’中搜索chinese语言包并点击install
3、在‘扩展’中搜索并安装python扩展
三、Jupyter Notebook 安装与使用
1、安装 Jupyter Notebook:输入pip install jupyter
2、打开Jupyter Notebook:输入jupyter notebook然后在浏览器打开一个页面
3、在Jupyter Notebook写代码:点击“New”,选择“Python 3”创建一个新的 Python 笔记本,输入 Python 代码, 按Shift + Enter 运行代码
四、Python的基础语法学习
1、条件语句 if语句:
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
try:
user_weight=float(input("请输入你的体重"))
user_height=float(input("请输入您的身高"))
user_BMI=user_weight/(user_height)**2
except ValueError:
print('输入不为合理数字,请重新运行程序,并输入正确数字')
except ZeroDivisionError:
print('身高不能为0,请重新运行程序,并输入正确数字')
except:
print('发生了未知错误,请重新运行程序')
else:
print('您的BMI为'+str(user_BMI))
if user_BMI<=18.5:
print ('此BMI属于偏瘦范围')
elif user_BMI<=25:
print('此BMI属于正常范围')
elif user_BMI<=30:
print("此BMI属于偏胖范围")
else:
print("此BMI属于肥胖范围")
2、循环语句
while循环:
while 判断条件:
执行语句
else:
执行语句
print('一个求所有输入数平均值的程序')
total=0
count=0
user_input=input("请输入数字,全部输完打e结束进程")
while user_input!='e':
num=float(user_input)
total=num+total
#total+=num
count+=1
user_input = input("请输入数字,全部输完打e结束进程")
if count==0:
#比较值时为双等号’变量赋值时为单等号
result=0
else:
result=total/count
print('您输入数字的平均值为'+str(result))
for语句:
配合range()函数使用
total=0
for e in range(1,101):
total=total+e
print(str(total))
遍历可迭代对象
word = 'hello'
for i in word:
print(i)
for...else 语句
for i in range(6):
print(i)
else:
print('Finally finished')
break 语句可以跳出 for 和 while 的循环体。如果你从 for 或 while 循环中终止,任何对应的循环 else 块将不执行。
continue 语句被用来告诉 Python 跳过当前循环块中的剩余语句,然后继续进行下一轮循环。
3、列表
函数&方法:
len(list):列表元素个数
max(list):返回列表元素最大值
min(list):返回列表元素最小值
list(seq):将元组转换为列表
list.append(obj):在列表末尾添加新的对象
list.count(obj):统计某个元素在列表中出现的次数
list.extend(seq):在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
list.index(obj):从列表中找出某个值第一个匹配项的索引位置
list.insert(index, obj):将对象插入列表
list.pop([index=-1]):移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
list.remove(obj):移除列表中某个值的第一个匹配项
list.reverse():反向列表中元素
list.sort( key=None, reverse=False):对原列表进行排序
list.clear():清空列表
list.copy():复制列表
fruit = ["apple",'pear','pineapple','orange','banana']
fruit1=sorted(fruit,key=len)#按字符串长度排序
print(fruit1)
items = [(2,'apple'),(1,'banana'),(3,'cherry'),(2,'date')]
sorted_items = sorted(items,key=lambda x:(x[0],x[1]))
print(sorted_items)#首先按元祖中第一个元素升序排序 然后按第二个元素升序排序
#改成大写
for i in range(len(fruit)):
fruit[i]=fruit[i].upper()
print(fruit)
#简单的方法
fruit = ["apple",'pear','pineapple','orange','banana']
print(fruit)
fruit=[x.upper() for x in fruit]
print(fruit)
fruit = ["apple",'pear','pineapple','orange','banana']
print(fruit)
#挑选出列表里以a开头的水果
filtered_fruit=[]
for f in fruit:
if f.startswith('a'):
filtered_fruit.append(f)
print(filtered_fruit)
#简单方法
fruit = ["apple",'pear','pineapple','orange','banana']
print(fruit)
filtered_2_fruit=[x for x in fruit if x.startswith('a')]
print(filtered_2_fruit)
enumerate函数
for i,x in enumerate(fruit):
print(i,x)#i代表列表元素索引值 x代表列表内容
列表推导式
[变量表达式 for 变量 in 序列(可迭代对象) if 条件]
list1 = [1,2,3,4,5,6,7]
list2 = [i**2 for i in list1]
print(list2)
#一样:
lst2 = [i**2 for i in range(1,8)]
print(lst2)
#相当于:
list3=[]
for i in list1:
list3.append(i**2)
print(list3)
list4 = [i**2 for i in list1 if i%2==1 ]
print(list4)
#两层循环:
list5 = [[i,j] for i in range(1,10) for j in range(1,10)]#也可以在后面写条件
print(list5)
#相当于:
list6 = []
for i in range (1,10):
for j in range(1,10):
list6.append([i,j])
print(list6)
#99乘法表:
list7 = [print('{}*{}={:<2}'.format(j,i,i*j),end = '\n' if i==j else' ') for i in range(1,10) for j in range(1,i+1)]
二维列表切片
import numpy as np
listnew = np.array(li)
print(listnew[0,:])第一行 [:,1]第二列
4、字典
d = {key1 : value1 , key2 : value2 , key3 : value3} 字典函数&方法
len(dict):计算字典元素个数,即键的总数。
str(dict):输出字典,可以打印的字符串表示。
type(variable):返回输入的变量类型,如果变量是字典就返回字典类型。
dict.clear():删除字典内所有元素
dict.copy():返回一个字典的浅复制
dict.fromkeys():创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
dict.get(key, default=None):返回指定键的值,如果键不在字典中返回 default 设置的默认值
key in dict:如果键在字典dict里返回true,否则返回false
dict.items():以列表返回一个视图对象
dict.keys():返回一个视图对象
dict.setdefault(key, default=None):和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
dict.update(dict2):把字典dict2的键/值对更新到dict里
dict.values():返回一个视图对象
pop(key[,default]):删除字典 key(键)所对应的值,返回被删除的值。
popitem():返回并删除字典中的最后一对键和值。
#遍历字典中的键:
for key in character_dictionary.keys():
print('键:',key)
#遍历字典中的值:
for value in character_dictionary.values():
print('值:',value)
#遍历字典中的键值对:
for a,b in character_dictionary.items():
print('键:',a ,'\t值:',b)
字典推导式
#(求1-10(键) 每个数的平方(值)
d1 = {i:i**2 for i in range(1,11)}
print(d1)
#在后面也可以跟上过滤条件 奇数
d2 = {i:i**2 for i in range(1,11) if i %2 == 1}
print(d2)
5、类//函数
class Employee:
def __init__(self,name,id):
self.name=name
self.id=id
def print_info(self):
print(f'员工的名字{self.name},工号{self.id}')
class FullTimeEmployee(Employee):
def __init__(self,name,id,monthly_salary):
super().__init__(name,id)#调用父类的构造函数
self.monthly_salary=monthly_salary
def calculate_monthly_pay(self):
return self.monthly_salary
class PartTimeEmployee(Employee):
def __init__(self,name,id,daily_salary,work_days):
super().__init__(name,id)
self.daily_salary=daily_salary
self.work_days=work_days
def calculate_monthly_pay(self):
return int(self.daily_salary) * int(self.work_days)
zhangsan=FullTimeEmployee('张三','619717',"7000")
lisi=PartTimeEmployee('李四','217217','250','17')
zhangsan.print_info()
lisi.print_info()
print(zhangsan.calculate_monthly_pay())
print(str(lisi.calculate_monthly_pay()))
匿名函数
#lambda x:x*x
#等价于
#def getResult(x):
# return x*x
squire=lambda x:x*x
result=square(9)
print(rsult)
#调用方法之一:
#(lambda str:len(str.split()))('hello world') ->2 把函数括起来后面括参数
#之二作为其他函数返回值 之三作为sorted函数中key参数
split函数
#str.split(separator=" ",number=string.count(str))[n]#为索引 因为返回列表
#separator指定分隔符分割字符串
#number为分割次数 默认所有出现次数分割
#str="hello<[https://github.com/]>byebye"
#print(str.split('[')[1].split(']')[0])
#结果为https://github.com/
#将字符串分割成列表
#a = "my name is eez"
#arr = a.split(' ')根据空格把字符串中每一项分割出来 得到一个列表
#print(arr)打印出来为['my','name','is','eez']
#把一个字符串列表拼成一个字符串
#string = "-".join(arr) 双引号中表示用什么来拼接它
#print(string)打印出来为 my-name-is-eez
#字符串的一堆函数:
#a='hello'.capitalize() 将字符串第一个字母转换成大写
#a='hello world'.title() 将字符串每个单词首字母转换成大写
#a='Hello'.lower() 将字符串中大写转小写
#a='hello'.upper() 将字符串中小写转大写
#b=" hello".lstrip() 删除字符串左侧空白字符
#b = "hello ".rsplit() 删除字符串右侧空白字符
#b=" hello ".strip() 删除字符串两侧空白字符
6、文件
#readline方法 readlines方法 read方法
#返回一行文件内容的字符串 返回全部文件内容组成的列表 返回全部文件内容的字符串
#f=open('./date.tex','r',encoding='utf-8')
#line=f.readline() lines=f.readlines() content=f.read()
#while line!=' ': for line in lines print(content)
#print(line) print(line)
#line=f.readline()
#f.close()关闭文件 with open("./date.tet",'r')as f:
#r读取 w写入 a添加 r+=r+w 缩进 加对文件的操作
#f.write()参数是一个字符串 单行写入
#f.writelines()参数可以是字符串也可以是列表 多行写入
7、异常类型
#1.IndexError索引错误
#2.ZeroDivisionError除零错误
#3.FileNotFoundError找不到文件错误
#4.TypeError类型错误
#Indentation缩进 Import导入模块 Arithmetic计算 Index索引 Attribute属性 Key键 Sytax语法 Value值 Assertion断言
#assert断言 测试 unittest测试库
#抛出 TypeError 异常
#raise TypeError("Both arguments must be integers.")