要检查是否已在 Windows PC (个人电脑)上安装了 python,请在开始栏中寻找 Python 或在命令行(cmd.exe)上运行以下命令:
python --version
没有安装则官网下载
https://www.python.org/
编辑Python工具vscode
https://code.visualstudio.com/
vscode安装插件:
1,Python
2.Tabnine(代码提示功能)
3.chinese(中文)
4.BracketPaair Colorizer (彩色对括号)
5.Better Comments(更好的注释)
Python与其他语言不同,它没有声明变量的命令,当想要使用他的时候,直接为其赋值就自动创建变量
x=10
y="li"
print(x)
print(y)
变量不需要使用任何数据类型声明,可以在其创建后在修改数据类型
x=10
y="5"
如何修改数据类型:数据类型(x或y)
向多个变量赋值
x=y=z="Orange"
输出变量
print("a"+"b"):字符串 + 输出 是将字符串链接输出
print(5+5):数值型 + 输出 将两个数值相加
global关键字
在函数里面创建全局变量 x
def myfunc():
global x
x="fanta"
myfunc()
print(x)
文本类型:str
数据类型 int(整形),float(浮点型)
布尔类型bool Ture(真),flase(假)
获取数据类型方法
print(type(x))
字符串多行赋值
a="""Python is a widely used general-purpose, high level programming language.
It was initially designed by Guido van Rossum in 1991
and developed by Python Software Foundation"""
print(a)
字符串也是数组
a="Hello,World"
print(a[0]) #获取字符第一个
裁切字符串
a="Hello,World"
print(a[2:5]) #正序第三位裁切到第五位
反裁切字符串
a="Hello,World"
print(a[-5:-2]) #负序末尾开始倒数第五开始到倒数第二
len()函数返回字符串的长度
a="Hello,World"
print(len(a)) #多数用于当作 循环范围
strip()方法删除开头和结尾的空白字符
a=" Hello,World! "
print(a.strip())
lower()返回小写的字符串
a="Hello,World!"
print(a.lower())
upper()方法返回大写的字符串
a="Hello,World!"
print(a.upper())
replace()用另一段字符串来替换字符串
a = "HELLO,World"
print(a.replace("HELLO", "12345"))
split()方法在找到分隔符的实例时将字符串拆分成子字符串可循下标
a = "asd/sadcvs/sd/asd/v/s"
print(a.split("/")[0])
检查文本是否存在该字符串(必须是邻近字符串)(也可使用and 相隔查找)
in(遍历所有该元素 存在返回True) 一对多
a = "sdjioasd"
x = "io" in a
print(x)
检查文本是否不存在该字符串
not 不存在
not in 该集合都不存在
is (一对一判断是否相等)
is not (判断一对一是否不相等)
a = "dsijdal"
x = "k" not in a
print(x)
通过索引获取该字符串的信息
a = "dsijdal"
l = int(input())
for b in a:
if a.index(b) == l:
index = a.index(b)
print(a[a.index(b)])
使用 format()方法将数字插入字符串中
age = 63
txt = "My name is Bill,and I am {}"
print(txt.format(age))
多次插入: 也可根据format 索引不按顺序放置
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {2} pieces of item {1} for {0} dollars."
print(myorder.format(quantity, itemno, price))
字符串方法
Python 有一组可以在字符串上使用的内建方法。
注释:所有字符串方法都返回新值。它们不会更改原始字符串。
方法 描述
capitalize() 把首字符转换为大写。
casefold() 把字符串转换为小写。
center() 返回居中的字符串。
count() 返回指定值在字符串中出现的次数。
encode() 返回字符串的编码版本。
endswith() 如果字符串以指定值结尾,则返回 true。
expandtabs() 设置字符串的 tab 尺寸。
find() 在字符串中搜索指定的值并返回它被找到的位置。
format() 格式化字符串中的指定值。
format_map() 格式化字符串中的指定值。
index() 在字符串中搜索指定的值并返回它被找到的位置。
isalnum() 如果字符串中的所有字符都是字母数字,则返回 True。
isalpha() 如果字符串中的所有字符都在字母表中,则返回 True。
isdecimal() 如果字符串中的所有字符都是小数,则返回 True。
isdigit() 如果字符串中的所有字符都是数字,则返回 True。
isidentifier() 如果字符串是标识符,则返回 True。
islower() 如果字符串中的所有字符都是小写,则返回 True。
isnumeric() 如果字符串中的所有字符都是数,则返回 True。
isprintable() 如果字符串中的所有字符都是可打印的,则返回 True。
isspace() 如果字符串中的所有字符都是空白字符,则返回 True。
istitle() 如果字符串遵循标题规则,则返回 True。
isupper() 如果字符串中的所有字符都是大写,则返回 True。
join() 把可迭代对象的元素连接到字符串的末尾。
ljust() 返回字符串的左对齐版本。
lower() 把字符串转换为小写。
lstrip() 返回字符串的左修剪版本。
maketrans() 返回在转换中使用的转换表。
partition() 返回元组,其中的字符串被分为三部分。
replace() 返回字符串,其中指定的值被替换为指定的值。
rfind() 在字符串中搜索指定的值,并返回它被找到的最后位置。
rindex() 在字符串中搜索指定的值,并返回它被找到的最后位置。
rjust() 返回字符串的右对齐版本。
rpartition() 返回元组,其中字符串分为三部分。
rsplit() 在指定的分隔符处拆分字符串,并返回列表。
rstrip() 返回字符串的右边修剪版本。
split() 在指定的分隔符处拆分字符串,并返回列表。
splitlines() 在换行符处拆分字符串并返回列表。
startswith() 如果以指定值开头的字符串,则返回 true。
strip() 返回字符串的剪裁版本。
swapcase() 切换大小写,小写成为大写,反之亦然。
title() 把每个单词的首字符转换为大写。
translate() 返回被转换的字符串。
upper() 把字符串转换为大写。
zfill() 在字符串的开头填充指定数量的 0 值。
如果有某种内容,则几乎都将True,
(空值,0,空列表,空元组,空字典,空集合)为false
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
查看对象是否是整数 函数 isinstance()
x=200
print()
一种有序和可更改的集合.允许重复的成员
创建列表(Python 不限制数据类型存放)
thislist = ["apple", "red", "cheryy", 15]
print(thislist)
访问项目(通过索引获取单独列表信息)
thislist = ["apple", "red", "cheryy", 15]
print(thislist[0])
负索引(- 从最后一位开始遍历)
thislist = ["apple", "red", "cheryy", 15]
print(thislist[-1])
返回多个列表元素
thislist = ["apple", "red", "cheryy", 15]
print(thislist[0:3])
负索引返回多个列表元素(返回 倒数第二元素和倒数第三)
thislist = ["apple", "red", "cheryy", 15]
print(thislist[-3:-1])
逐个打开列表中的所有项目
thislist = ["apple", "red", "cheryy", 15]
for x in thislist:
print(x)
检查数据类型相同的列表的是否存在该元素
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("存在该元素")
else:
print("不存在")
指定类型查找
thislist = ["apple", "banana", "cherry",15]
for x in thislist:
if type(x) == str and x == "apple":
print(x)
返回列表长度/数量
thislist = ["apple", "banana", "cherry", 15]
print(len(thislist))
添加元素
a = [1, 56, 4321, 5, 43, 15, 65, 32, 15]
a.append(2)
print(a)
插入元素(插入正序二个位置)
a = [1, 56, 4321, 5, 43, 15, 65, 32, 15]
a.insert(1, 15)
print(a)
删除元素
a = [1, 56, 4321, 5, 43, 15, 65, 32, 15]
a.remove(15)
print(a)
删除索引
a = ["apple", "banana", "cherry"]
del a[0]
print(thislist)
复制列表
a = [1, 2, 3, 4, 5, 6, 7, 8, 10, 9]
a1 = a.copy()
print(a1)
合并列表
list1 = ["a", "b", "c", "d"]
list2 = [1, 2, 3, 4]
list3 = list1 + list2
print(list3)
sort() 排序函数
不支持非整形排序
[a = [1, 3, 5, 8, 4, 12, 0, 8, 10, 9]]()
a.sort()
print(a)
sorted():根据字典关键字_列表排序
sorted() 根据字典 整形元素 对列表中的字典排序 True为降序 false为升序
key=lambda:隐函数(固定写法)
keys:keys(临时起的名字_随意写)
[“a”]关键字索引
reverse=False 升序, True_降序
list = [{"a": 1}, {"a": 4}, {"a": 3}, {"a": 2}]
a = sorted(list, key=lambda keys: keys["a"], reverse=False)
print(a)#输出全部列表
print(min(list, key=lambda x: x["a"])) #输出列表最小值
也可对列表直接排序
reverse=False 升序, True_降序
a = [1, 3, 5, 4, 12, 0, 8, 10, 9]
b = sorted(a, reverse=False)
print(b)
count 函数 计数
查找指定元素出先次数
b = "asdsadwd"
print(b.count("a"))
index()函数
返回索引 列表同理
b = "asdsadwd"
print(b.index("s"))
根据输入的关键字返回索引
for 字典 in 列表:
if 字典[关键字]==input()
index=列表.index(字典)
print()输出格式
foramt()
print("x:{},x:{},x:{}".format(dict["x"],dict["x"],dict["x"]))
获取values 转换tuple(元组)
for 字典 in 列表:
va=tuple(字典.values)
print("x:%s,x:%d,x:%.f" % va)
end关键字
将结果输出到同一行
print(x,end=",")
元组是有序且不可改变的集合.在Python中,元组是用圆括号编写的
实例
创建元组
thistuple=("apple","banna","cherry")
print(thistuple)
删除元组
可以删除元组,不可以删除元组的项目
thistuple=("apple","banna","cherry")
del thistuple
返回元组最大元素 max()
tuple1=(1,25,3,4)
max(tuple1)
返回元组最小元素 min()
tuple1=(2,12,13,5)
min(tuple1)
列表转换元组
list1= ['Google', 'Taobao', 'Runoob', 'Baidu']
tuple1=tuple(list1)
tuple1
('Google', 'Taobao', 'Runoob', 'Baidu')
集合是无序和无索引的集合,在Python中,集合用大括号编写.
创建集合
thisset={"apple","banana","cherry"}
print(thisset)
或
set(value)
无法通过索引访问 set 元素 因为set 无序没有索引
但是可以使用for 遍历循环 set 或使用 in 查询集合是否存在该数值
for 遍历循环
thisset={"apple","banana","cherry"}
for x in thisset:
print(x)
in 查找
thisset={"apple","banana","cherry"}
print("banana" in thisset) #返回 True
添加元素,添加多个元素
add()添加单个元素
update()添加多个元素
thisset={"apple","banana","cherry"}
thisset.add("ors")
thisset.update("a","b","c")
print(thisset)
删除元素 remove
thisset={"apple","banana","cherry"}
thisset.remove("apple")
合并集合 union()
合并后 元素是混乱的 排除重复项
set1={"a","b","c"}
set2={1,2,3}
set3=set1.union(set2)
print(set3)
运算集合
集合a 包含而集合b 不含的元素
a = set("asdqwdts")
b = set("esdqwdes")
print(a-b)
集合a或b中包含的所有元素
a = set("asdqwdts")
b = set("esdqwdes")
print(a | b)
集合a和b中都包含了的元素
a = set("asdqwdts")
b = set("esdqwdes")
print(a & b)
不同时包含于a和b的元素
a = set("asdfgt")
b = set("qweryt")
print(a ^ b)
字典是一种无序,可变的和有索引的集合.在Python中,字典用大括号编写,拥有键和值
创建字典
thisdict = {
"a": 1,
"b": 2,
"c": 3
}
print(thisdict)
通过字典键获取值
thisdict = {
"a": 1,
"b": 2,
"c": 3
}
print(thisdict["a"])
查询字典键更改字典值
thisdict = {
"a": 1,
"b": 2,
"c": 3
}
thisdict["a"] = 20
print(thisdict["a"])
update()插入一个键值
thisdict = {"a": 1, "b": 2, "c": 3}
thisdict.update({"d": 4})
print(thisdict)
查询字典中的所有键
thisdict={
"a":1
"b":2
"c":3
}
for i in thisdict:
print(i)
查询字典中所有的值
thisdict={
"a":1
"b":2
"c":3
}
for i in thisdict:
print(thisdict[i])
values ()遍历字典所有值
thisdict={
"a":1
"b":2
"c":3
}
for i in thisdict.values():
print(i)
items() 遍历字典所有键值
thisdict={
"a":1
"b":2
"c":3
}
for x, y in thisdict.items():
print(x, y)
为字典添加新的元素
thisdict={
"a":1
"b":2
"c":3
}
thisdict["d"] = 4
for x, y in thisdict.items():
print(x, y)
嵌套字典
thisdict = {"a": {"a": 1, "b": 2},
"b": {"c": 1, "d": 2},
"c": {"e": 1, "f": 2}}
print(thisdict)
if语句
满足条件会继续执行下去
a = 66
b = 77
if b > a:
print("通过")
elif 语句(分支) 输入的满足那个条件
执行那个if 下面的print
a = int(input("输入:"))
if 80 <= a <= 100:
print("A")
elif 60 <= a <= 79:
print("B")
else 语句
不满足所有if 时 执行
a = int(input("输入:"))
if 80 <= a <= 100:
print("A")
elif 60 <= a <= 79:
print("B")
elif 60 > a:
print("C")
else:
print("输入错误")
or 关键字
满足 if 所有条件中的一个
a = int(input("输入:"))
if a == 1 or a == 2 or a == 3 or a == 8:
print("正确")
else:
print("错误")
and 关键字
满足if所有 条件
a = int(input("输入:"))
b = int(input("输入2:"))
if a == 1 and b == 2:
print("正确")
else:
print("错误")
如果使用break语句 即使 while 条件为真也可以停止循环
找到就不继续往下循环了
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print("找到了")
通过continue语句,我们可以停止循环的当前迭代,并继续下一个:
跳过banana
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
如果while循环条件为真,我们就可以执行继续执行语句为假停止
循环1到6
i = 1
while i < 7:
print(i)
i += 1
也可以在使用input的时候 开始条件为假,为真以后在执行下面的操作
a = int(input())
while a != 7:
a = int(input("重新输入"))
print(a)
如果我们需要指定代码循环一定次数,可以使用range()函数
默认0开始
for x in range(10):
print(x)
默认1开始,10结束(不包括10)
for x in range(1, 10):
print(x)
(起始5 ,结束100,递增 3
for x in range(5, 100, 3):
print(x)
第一个for 0-9
第二for 0-9 循环9次
for x in range(10):
for j in range(10):
print(j, end=" ")
print(" ")
函数是一种仅在调用时运行的代码快
也可以将数据成为参数传递到函数中.
函数可以把数据作为结果返回
创建函数
def my_function():
print("Hello world")
调用函数
my_function()
信息可以作为参数传递给函数
参数在函数名后的括号内指定.可以添加任意数量的参数,用逗号分隔
带参数的函数(必须按照参数顺序,传递参数)
def my_function(a,b):
print(a+b)
my_function(5,6)
不需要按照参数顺序 传递参数
def my_function(a,b):
print(a+b)
my_function(b=6,a=5)
设置默认参数
设置的默认参数必须放在最后
def my_function(b, a=5):
print(a+b)
my_function(6)
以列表(list)作为参数
def my_function(a):
for x in a:
print(x)
fruits = [1, 2, 3, "a"]
my_function(fruits)
当需要一个函数处理比当初声明更多的参数时.这样的参数叫做不定长参数
声明时不会命名 加*的参数会以元组(tuple)的形式导入,存放所有未命名的变量参数
def my_function(b, *a):
print(b)
print(a)
my_function(50, 60, 72)
for 输出参数元组
def my_function(b, *a):
print(b)
print(a)
for i in a:
print(i)
return
my_function(50, 60, 72)
加**的参数会以字典的形式导入.
def dict1(**a):
print(a)
dict1(商品名称="洗衣服", 商品单价=25, 商品类型="家用")
list1 = []
def dict1(**a):
list1.append(a)
list1.append(dict1(商品名称="洗衣服", 商品单价=25, 商品类型="家用"))
print(list1)
asd = list(filter(None, list1))
print(asd)
return语句
def my_function(x,y):
return x*y
print(my_function(5,6))
sum= lambda a,b:a+b
print(sum(5,5))
遍历列表
list = [{"a": 1}, {"a": 4}, {"a": 3}, {"a": 2}]
a=lambda s:s
print(a(list), end='\n')
创建模块
创建一个 mymodule.py 的文件
然后在写一个函数
def greeting(a,b):
print(a+b)
mylist = [1, 2, 34, 5]
调用模块
经过上面的创建 我们就可以在别的py文件调用 这个模块了
import mymodule
mymodule.greeting(5, 6)
调用列表
模块 还可以调用py文件里面的 数组、字典、对象等
import mymodule
a = mymodule.mylist
print(a)
命名模块
可以as 缩写模块名字 方便自己认识
import mymodule as my
my.greeting(5,6)
python 3 中
内建模块: 直接 import 调用 不用创建 是python自带的
下载模块:当python自带功能 满足不了自己的需求时 可以下载模块
pip install 模块名字
导入指定一部分
from mymodule import fib, fib2
fib(100)
print(fib2(100))
from …import * 语句
全部导入
from mymodule import fib, fib2
报错解决方案
not enough values to unpack (expected 2, got 1)
没有足够的值来解包
---删除多余的空格行 如 a,b=1,2