title: python語法入門
author: Sun-Wind
date: August 25, 2021
python語法入門
博主最近參加一項比賽,因為需要用到python,所以在這里記錄自己學習python的一些語法知識,希望能夠幫助初學者
注意:該學習過程要求有c或者C++基礎
python與C++的區別
- python用新行來完成命令,而C++使用分號
- python 用空格來定義范圍而c++使用花括號
- python是一種面向對象的解釋性語言,C++是一種面向對象的編譯性語言
- python中的幾乎所有東西都是對象,擁有屬性和方法
輸出和輸入
#This is a comment
print("Hello, World!")
x = 10
y = "Bill"
print(x)
print(y)
可以看到其語法十分直觀
print("Python is " + x)print語句可以和變量組合。(除字符串也是變量)
裁切語法:指定開始索引和結束索引,用冒號分隔,返回對應變量的一部分如print(b[2:5])
存在負的索引,可以用負索引從字符串末尾開始切片
利用input進行輸入
print("Enter your name:")
x = input()
print("Hello ", x)
語句
與C++的語法十分類似,下面僅介紹不同點
elif 相當於else if
a = 66
b = 66
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
如果只有一條語句要執行,可以放到同一行,
如果ifelse都只有一個語句要執行可以放到同一行
if語句內容不能為空如果一定要為空,可以用pass代替
a = 66
b = 200
if b > a:
pass
while 有break和continue,else可以和while語句配合
i = 1
while i < 7:
print(i)
if i == 3:
break
i += 1
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
for 循環和in關鍵字配合,相當於創建了一個迭代器對象,並且為每個循環執行next()方法
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
變量
python用類來定義數據類型python不用申明變量,在首次賦值時,才會創建變量並且變量沒有特定申明類型,隨時可以發生變化並且python允許在一行中給多個變量賦值如:
<x, y, z = "Orange", "Banana",>'
"Cherry"·變量的數據類型可以type(x)獲取
print(type(x))
print(type(y))
print(type(z))
- 文本類型: str
- 數值類型: int, float, complex
- 序列類型: list, tuple, range映射類型: dict
- 集合類型: set, frozenset
- 布爾類型: bool
- 二進制類型: bytes, bytearray, memoryviewcomplex是復數類型如x=1j,j作為虛部的書寫字符串類型
例如
x = 10 # int
y = 6.3 # float
z = 2j # complex
可以用函數int(),float(),complex()。
x = int(1) # x 將是 1
y = int(2.5) # y 將是 2
z = int("3") # z 將是 3
str()——從一種類型轉換為其他類型,但是復數類型不能轉換
x = str("S2") # x 將是 'S2'
y = str(3) # y 將是 '3'
z = str(4.0) # z 將是 '4.0'
int 類型長度不限
list是列表類型
print "list1[0]: ", list1[0]print "list2[1:5]: ", list2[1:5]t = (0,1,2,3,4,5,6,7,8,9)
thislist = ["apple", "banana", "cherry"]
print(thislist)
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
tuple用小括號建立而且tuple中的元素不能修改列表(List)是一種有序和可更改的集合。允許重復的成員。
元組(Tuple)是一種有序且不可更改的集合。允許重復的成員。
集合(Set)是一個無序和無索引的集合。沒有重復的成員。
詞典(Dictionary)是一個無序,可變和有索引的集合。沒有重復的成員。並且也有負索引等適用於字符串得操作
append()可以追加元素
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
insert()可以在指定得索引處增加項目
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
remove()可以刪除指定得項目
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
pop()刪除指定得索引,如果沒有指定,就刪除最后一項
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
del 關鍵字也可以刪除指定的索引,並且可以刪除列表
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
clear()方法可以清空列表
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
注意:
內置的=只是對變量的引用,
列表的合並可以直接用+法
進行copy()和list()都可以復制列表,同時list()還可以構建列表
元組值是不可改變的,但是可以先將元組變成列表在變回去,元組構建函數是tuple()
元組不能刪除元素,但是可以直接刪除元組
字符串語法
可以用len()函數獲取字符串的長度
a = "Hello, World!"
print(len(a))
strip()可以刪除字符串開頭和結尾的空白字符
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
lower()返回小寫的字符串
upper()返回大寫的字符串
replace()用另一段字符串來替換字符串
a = "Hello, World!"
print(a.replace("World", "Kitty"))
split()在找到分隔符時將字符串拆分為子字符串
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
可以用in not in 關鍵字查找文本中是否出現短語字符串
txt = "China is a great country"
x = "ina" in txt
print(x)
可以用+和” “ 拼接format()可以使得字符串和任意變量拼接,
a = "Hello"
b = "World"
c = a + b
print(c)
原字符串需要有大括號,format方法不限參數
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
集合和字典
set是無序的,構建set要用花括號
thisset = {"apple", "banana", "cherry"}
print(thisset)
add()方法添加一個項目,
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
update()可以添加多個項目
thisset = {"apple", "banana", "cherry"}
thisset.update(["orange", "mango", "grapes"])
print(thisset)
有remove,del,clear操作
union方法可以合並后兩個集合
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
set也有自己的構造函數
thisset = set(("apple", "banana", "cherry")) # 請留意這個雙括號
print(thisset)
字典是無序,可變和有索引的集合,用花括號編寫,有鍵和值,且都是字符串可以對新的項目賦值,這樣的話新的元素會被自動創建
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
print(thisdict)
字典中字典可以嵌套
函數
利用def來定義函數,函數也有return 語句
可以傳送任意個參數,只需要在參數名稱前面加個*
def my_function():
print("Hello from a function")
def myfunction:
pass
模塊
py中的模塊相當於c++中頭文件,用import引入datetime模塊
可以用datetime類創建日期對象,年月日
import datetime
x = datetime.datetime.now()
print(x)
re模塊專門用於匹配,
findall()返回包含所有匹配項的列表
split()返回一個列表,字符串在每次匹配時被拆分,還可以指定第三個參數判定時第幾次出現進行拆分
import re
str = "China is a great country"
x = re.findall("a", str)
print(x)
import re
txt = "China is a great country"
x = re.search("^China.*country$", txt)
import re
str = "China is a great country"
x = re.split("\s", str)
print(x)
import re
str = "China is a great country"
x = re.sub("\s", "9", str)
print(x)
其中使用了正則表達式匹配
- [] 一組字符 "[a-m]"
- \ 示意特殊序列(也可用於轉義特殊字符) "\d"
- . 任何字符(換行符除外) "he..o"
- ^ 起始於 "^hello"
- {} 確切地指定的出現次數 "al{2}"
- | 兩者任一 "falls|stays"
- () 捕獲和分組
sub()可以把匹配替換為所選擇的文本,還可以指定第4個參數來控制替換的次數search()返回一個match對象,
import re
str = "China is a great country"
x = re.search("\s", str)
print("The first white-space character is located in position:", x.start())
span()返回的元組包含了匹配的開始和結束位置·
group()返回匹配的字符串部分如果沒找到,則返回值
Nonebottle模塊是一個快速小巧。輕量級的微型web框架,
@route()建立url映射,route是路由,括號里是url的路徑,
def login() return 的內容將顯示在頁面上最后,
run() 函數啟動服務器,並且我們設置它在 本機 的 8080 端口上運行
可以在命令行中運行python文件前提是已經安裝了pythonpython
注釋以#開頭
多行注釋可以采用“”“即未分配給變量的字符串文字
- 就先寫到這里吧,這一節沒有寫類和對象的語法
- 以后想到什么再回來補充一下 阿巴阿巴o( ̄▽ ̄)ブ
