1.Python安裝
要檢查是否已在 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(更好的注釋)
2.變數
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)
3.資料型別
文本型別: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)
3.1處理字串方法
字串也是陣列
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))
3.2沒有實體的字串方法
字串方法
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 值,
3.3布爾型別
如果有某種內容,則幾乎都將True,
(空值,0,空串列,空元組,空字典,空集合)為false
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
查看物件是否是整數 函式 isinstance()
x=200
print()
4.集合(陣列)
4.1串列(List)
一種有序和可更改的集合.允許重復的成員
創建串列(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=",")
4.2元組(tuple)
元組是有序且不可改變的集合.在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')
4.3集合(set)
集合是無序和無索引的集合,在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)
4.4字典
字典是一種無序,可變的和有索引的集合.在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)
5.if,else的使用
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("錯誤")
6.while 和 for 回圈
break 陳述句
如果使用break陳述句 即使 while 條件為真也可以停止回圈
找到就不繼續往下回圈了
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print("找到了")
continue陳述句
通過continue陳述句,我們可以停止回圈的當前迭代,并繼續下一個:
跳過banana
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
while回圈
如果while回圈條件為真,我們就可以執行繼續執行陳述句為假停止
回圈1到6
i = 1
while i < 7:
print(i)
i += 1
也可以在使用input的時候 開始條件為假,為真以后在執行下面的操作
a = int(input())
while a != 7:
a = int(input("重新輸入"))
print(a)
for 回圈_ range()函式
如果我們需要指定代碼回圈一定次數,可以使用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嵌套
第一個for 0-9
第二for 0-9 回圈9次
for x in range(10):
for j in range(10):
print(j, end=" ")
print(" ")
7.函式
函式是一種僅在呼叫時運行的代碼快
也可以將資料成為引數傳遞到函式中.
函式可以把資料作為結果回傳
創建函式
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, 商品型別="家用")
傳遞的字典存放串列 并且去除None值
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))
lambda 函式
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')
8.模塊
創建模塊
創建一個 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…import 陳述句
匯入指定一部分
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/54065.html
標籤:其他
