python初學者筆記—入門基礎知識

2020-08-11 17:46:30

一、變數

變數:儲存數據的容器,我們可以通過變數來操作數據
我們在建立變數時會在記憶體中開闢一個空間,可以儲存不同類型的數據。

變數需要被定義: a=100

>>> b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined

每個物件都包含標識,型別和數據(值)這些資訊。
可以通過id()、type()、print()三個函數檢視

二、識別符號命名規則:

  • 1、識別符號由字母、數位、下劃線、中文
  • 2、開頭的字元不能使數位
>>> 1abc=100
  File "<stdin>", line 1
    1abc=100
       ^
SyntaxError: invalid syntax
  • 3、大小寫敏感(區分大小寫)
  • 4、不能以關鍵詞命名
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
  • 5、命名要有含義、儘量不要再開始位置使用下劃線
>>> a="小王"
>>> a
'小王'
>>> name='小王'
>>> name
'小王'
>>> age=25
>>> password=123456

三、運算子

算數運算子:

      • / **(冪次計算) //整除 %取模(求餘數)

比較運算子(返回邏輯判斷結果):
< > <= >= ==(值的比較) !=

賦值運算子:
= += -= *= /= //= **=
a+=1 --> a=a+1
a-=1 --> a=a-1

# 序列解包
>>> a=1;b=2;c=3;d=4
>>> a,b,c,d=1,2,3,4

邏輯運算子:
and or not
and:兩邊的條件都爲True時返回True,否則返回False
or:兩邊的條件有一個爲True時返回True,否則返回False
not:取反

成員運算子(判斷物件是否在序列中):
in ; not in

身份運算子(判斷是否是同一個物件):
is , is not
a is b --> id(a)==id(b)

運算子的優先順序: 括號() > 乘方 > 乘法除法 > 自左向右順序計算

四、特殊字元

1、註釋符(pycharm ctrl+/ 快速註釋和取消註釋)

# print("hello world!1")
# print(123)# print("hello world!2")
# print("hello world!3")
# print("hello world!4")
# print("hello world!5")

2、字串 ''單引號 "「雙引號 「」」 「」"三引號

三引號用於建立多行字串,有時也做註釋
word=""「第一行
第二行
第三行
第四行
「」」

3、跳脫符
將普通字元宣告爲特殊字元\n換行符 \t製表符
將特殊字元宣告爲普通字元’ " \

>>> path="C:\name\time\random.txt"
>>> print(path)
C:
andom.txtme
如何正確表示path路徑
方法1:
path="C:\\name\\time\\random.txt"
方法2:
path=r"C:\name\time\random.txt"
方法3:
path="C:/name/time/random.txt"

4、續行符\

>>> a='12312312312312312333333123123123123\
... ABASDASDASZXCQWEQWEQWEQ'
>>> a
'12312312312312312333333123123123123ABASDASDASZXCQWEQWEQWEQ'

5、分號

>>> a=100
>>> b=100
>>> a=100;b=100
一行中寫多行語句

五、數據型別

基礎數據型別:數值型(整形 浮點數 布爾值 複數) 字串
綜合數據型別:列表 元組 字典 集合

數值型
整形 int(下標、元素的提取)
a=100 b=200 c=-5 d=26

浮點數 float(用於科學計算)
a=3.14 b=9.1 c=.2 d=5.

布爾值 bool(True和False)
True和1等價 False和0等價

複數 complex(1+2j)實部+虛部

字串:不可變的有序序列
string=‘Python’
string=‘Python123中文 # ! ?’

序列(sequence):一種將多個數據組合在一起的結構
有序:支援索引和切片的操作

s='Python';len(s)# 檢視字元長度
s[0]# 獲取第一個元素
s[1]# 獲取第二個元素
s[-1]# 獲取最後一個元素
s[-2]# 獲取最後第二個元素
s[10]

>>> s[10]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

#切片:string[2:4]
#切片:可以獲取序列中的多個元素
string[start:end]# 左閉右開 [ )
>>> string='Python123中文 # ! ?'
>>> string
'Python123中文 # ! ?'
>>> string[0:8]
'Python12'
>>> string[8]
'3'
>>> string[2:10]
'thon123中'

string[2:100]# 超出範圍不會報錯
>>> string[:100]
'Python123中文 # ! ?'
string[2:]# 從指定位置到結尾位置
string[:5]# 從開始位置到指定位置
string[:]# 從開始位置到結尾位置

string[start,end,step]
>>> num[::1]
'1234567890'
>>> num[::2]
'13579'
>>> num
'1234567890'
>>> num[::3]
'1470'
>>> num[::-1]# 逆向排序
'0987654321'

#字串不可變,不支援元素的修改
string[0]
>>> string[0]='p'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

#字串的常見操作
# 字串的拼接
a='上海';b='浦東'
a+b --> '上海浦東'
a*3 --> '上海上海上海'
a='上海';b='浦東';c='世紀大道'
'上海-浦東-世紀大道'
>>> a+'-'+b+'-'+c
'上海-浦東-世紀大道'

# 檢視元素個數
len(string)
>>> string
'Python123中文 # ! ?'
>>> len(string)
17

# 基礎數據型別之間的轉換
age='25'
>>> age+1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not int

int() float() str() bool() 
int('25')-->25 int(3.14)--> 3
>>> int('abc')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'

float('3.14') float(3) 

str(123) str(3.14)

# 需要數位具有字串的特性時:
a="我的年齡是:"
b=25
>>> a+b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not int
>>> a+str(b)
'我的年齡是:25'

# 輸入和輸出
# 輸出print()
# 輸入和輸出
string="人生苦短,我用Python。"
print(string+' Oh yeah!')
print(string+' Oh yeah!')
print(string+' Oh yeah!')
print(string+' Oh yeah!')
print(string+' Oh yeah!')

# 每次print會進行和換行
string="人生苦短,我用Python。"
# end輸出結束後列印的字元,預設換行符
# print(string+' Oh yeah!',end='---------')
# print(string+' Oh yeah!',end='\n')

string1="人生苦短"
string2="我用Python"
# sep列印多個物件時字元之間的分隔符,預設空格
print(string1,string2,1,2,sep='++')

# 輸入(接受資訊都爲字串型別)
# name=input("請輸入你的姓名:")
# age=input("請輸入你的年齡:")
# print(type(name),type(age))
# print("你的名字是:",name)
# print("你的年齡是:",age)

# 請輸入你的名字和年齡,並且列印出你的名字和明年的年齡
# 要求:一條print語句完成
# name=input("請輸入你的姓名:")
# age=input("請輸入你的年齡:")
# print("你的名字是"+name+"你的年齡是"+str(int(age)+1)+"歲")
# print("你的名字是"+name+"你的年齡是",int(age)+1,"歲",sep="")

# 字串格式化
# 建立字串模板,常用與建立自定義的字串
# print('今天學習的課程是%s'%'python程式設計基礎')
# print('今天學習的課程是%s'%'python基礎')
# print('我的名字是%s,今年%d歲,體重是%.1f公斤'%('程時',18,72.5))
# name=input("請輸入你的名字:")
# age=input("請輸入你的年齡:")
# weight=input("請輸入你的體重:")
# print('我的名字是%s,今年%s歲,體重是%s公斤'%(name,age,weight))

# 1、輸入一串字元,並返回它的長度。(結合input用法)
# string=input("請輸入一段字元資訊:")
# print("輸入的字元資訊長度是%s"%len(string))

# 2、輸入你的名字和年齡,輸出你明年是多少歲(結合input和字串格式化)
# name=input("請輸入你的名字:")
# age=input("請輸入你的年齡:")
# print("你的名字是%s,你的年齡是%d歲,你明年%d歲"%(name,int(age),int(age)+1))
# print("你的名字是%s,你的年齡是%s歲,你明年%s歲"%(name,age,int(age)+1))


# 綜合數據型別
列表list 元組tuple 字典dict 集合set

列表:可變的有序序列,可以儲存任意型別的數據
string=''
tlist=[]
>>> tlist=[1,3.14,True,1+2j,'python','r語言',[100,200,300]]
>>> type(tlist)
<class 'list'>
有序序列:支援索引和切片
# 索引(下標)
tlist[0] tlist[4]
tlist[-1] tlist[-2]
# 切片(返回列表)
tlist[2:5] # 左閉右開
tlist[2:-1]
tlist[2:] tlist[:5]
tlist[:] 
# 步長
>>> tlist[::2]
[1, True, 'python', [100, 200, 300]]
>>> tlist[::3]
[1, (1+2j), [100, 200, 300]]
>>> tlist[::-1]# 翻轉列表
[[100, 200, 300], 'r語言', 'python', (1+2j), True, 3.14, 1]
>>> tlist[2:5]
[True, (1+2j), 'python']
>>> tlist[2:5:2]
[True, 'python']

# 可變的有序序列
string='Python'
string[0]='p'
tlist[0]='p'
>>> tlist[0]='100'
>>> tlist
['100', 3.14, True, (1+2j), 'python', 'r語言', [100, 200, 300]]

# 增刪改查
# 查詢數據(索引、切片)
# 增加數據
# 不同的物件具有不同的方法
>>> string.append(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'append'

物件.方法名(參數)
list.append(object)# 將一個物件追加到列表的末尾
>>> tlist=[1,2,3]
>>> tlist.append('java')
>>> tlist.append('C++')
>>> tlist.append(['Excel','Mysql','Spss'])
>>> tlist
[1, 2, 3, 'java', 'C++', ['Excel', 'Mysql', 'Spss']]
>>>

list.extend(seqence)# 將一個序列中的元素依次追加到列表的末尾

list.insert(index,obj)# 將一個物件插入到列表的指定索引位置

修改數據(修改序列元素)
tlist[-1]='C#'

刪除數據
del是通用方法,用於從記憶體空間中刪除物件
del 物件  del list ; del list[index]
list.clear()# 將一個列表中的元素清空
# 通過索引刪除
list.pop(index=-1)# 刪除列表中的指定索引元素(預設索引爲-1),會返回刪除的物件
>>> tlist=['a','b','c']
>>> tlist
['a', 'b', 'c']
>>> tlist.pop()
'c'
>>> tlist
['a', 'b']
>>> tlist=['a','b','c']
>>> tlist.pop(0)
'a'
>>> tlist
['b', 'c']

# 通過目標刪除
num=['Python','Excel','Mysql','Spss','Ps']
num.remove(obj)# 將列表中的指定物件刪除
num.remove("Ps")
>>> num=['Python','Excel','Mysql','Spss','Ps']
>>> num.remove("Ps")
>>> num
['Python', 'Excel', 'Mysql', 'Spss']
Tip:remove方法只刪除找到的第一個目標

# 其他常用操作
list.reverse()# 將列表元素進行翻轉
list.sort()# 對列表元素進行排序
num=[1, 2, 5, 7, 10, 13, 23]
>>> num.sort()# 預設升序
>>> num
[1, 2, 5, 7, 10, 13, 23]
>>> num.sort(reverse=True)# 降序
>>> num
[23, 13, 10, 7, 5, 2, 1]
sorted(num)# 不修改原物件的情況下進行排序
>>> sorted(num)
[1, 2, 5, 7, 10, 13, 23]
>>> sorted(num,reverse=True)
[23, 13, 10, 7, 5, 2, 1]

list.conut(obj)# 對元素進行計數
>>> n=[1,2,1,2,1,2,3,4,5,2]
>>> n.count(2)
4
list.index(obj)# 第一個查詢到元素所在位置
>>> n
[1, 2, 1, 2, 1, 2, 3, 4, 5, 2]
>>> n.index(2)
1
>>> n.index(1)
0
>>> n.index(3)
6

拼接操作:
list1+list2
>>> list1=[1,2,3]
>>> list2=['a','b','c']
>>> list1+list2
[1, 2, 3, 'a', 'b', 'c']
>>> list1+[4]
[1, 2, 3, 4]
>>> list1+[list2]
[1, 2, 3, ['a', 'b', 'c']]
>>> list1*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

# len(list) 檢視元素數量  max(list) min(list) sum(list)



元組(tuple):與列表相似,但是元素不支援修改,也是一種有序序列
s='123'
l=[1,2,3]
t=(1,2,3) t=1,2,3 t=('Python',) t='Python',
>>> type(t)
<class 'tuple'>

# 有序序列:支援索引、切片
# 不可變:增刪改
# len(list) 檢視元素數量  max(list) min(list) sum(list)

list更加靈活  tuple更加安全
列表和元組的相互轉化
list ---> tuple
tuple(list)
tuple ---> list
list(tuple)
str ---> tuple
tuple(str)
str ---> list
list(str)
str.join(seq)
>>> num=list('123456789')
>>> num
['1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> ''.join(num)
'123456789'
>>> '+'.join(num)
'1+2+3+4+5+6+7+8+9'
>>> '--'.join(num)
'1--2--3--4--5--6--7--8--9'


字典:一種由鍵值對作爲元素組成的無序可變序列
dict1={key1:value1,key2:value2,key3:value3,...}
# 特性:
1、字典中鍵物件不能重複
2、字典的鍵物件必須是不可變型別(值物件沒有要求)
# 不可變型別:字串 數值 元組
# 可變型別:列表 字典

# 增刪改查
# 查詢數據
dict1={'key1':'value1','key2':'value2','key3':'value3','key4':'value4'}
dict1[key]-->value
>>> dict1['key5']# 不存在此鍵值對會報錯
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'key5'

# 修改數據
dict1['key1']='new_value1'

# 新增數據
dict1['new_key']='add_value'

# 新增多個鍵值對
d1={'a':1,'b':2}
d2={'c':3,'d':4}
>>> d1.update(d2)
>>> d1
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

# 刪除數據
del dict1;del dict1[key]
dict.clear()# 清空字典中的元素
dict.pop(key)# 刪除指定的鍵值對

# 其他常用操作
len(dict1)# 檢視元素數量
key in dict# 成員判斷(判斷是否在字典鍵物件中)
dict.fromkeys(seq,value)# 以序列中的元素爲鍵物件快速建立字典
dict([(key1,valu1),(key2,value2)])
dict(key1=value1,key2=value2)
user=['小明','小李','小張']
password=[123,456,789]
zip(user,password)
dict(zip(user,password))
>>> dict(zip(user,password))
{'小明': 123, '小李': 456, '小張': 789}


集合(set):與字典類似,它是一組字典鍵物件的集合,但是不儲存value的值
>>> s={1,2,3,4,5}
>>> s
{1, 2, 3, 4, 5}
>>> type(s)
<class 'set'>
集合保留字典的特性,元素不能重複且不爲可變序列,常用於去重
set([1,2,1,2,1,2])
set(['001','002','003','002'])
list(set([1,2,3,3]))


# 增刪查
# 查詢數據(list for回圈遍歷)
# 增加數據
set.add(obj)# 向集閤中新增物件
set.update(seq)# 將一個序列中的元素新增到集閤中
# 刪除數據
set.claer()# 清空元素
set.remove(obj)# 刪除集閤中指定元素

# 其他常用操作
1 in {1,2,3}# 成員判斷
len()# 檢視元素數量

s1={1,2,3};s2={2,3,4}
>>> s1&s2# 交集
{2, 3}
>>> s1|s2# 並集
{1, 2, 3, 4}
>>> s1-s2# 差集
{1}



# python中有哪些內建數據型別
整型 浮點型 布爾型 複數 字串 列表 元組 字典 集合
# 什麼是序列,英文拼寫是?
序列:可以將多個元素組織在一起的一種數據結構
sequence

info=[["小明",22,"程式設計師",10000,"北京"],
	  ["老王",40,"工程師",15000,"上海"],
	  ["老張",42,"醫生",20000,"深圳"]]
# 通過格式化字串用以下格式列印輸出小明、老王、老張的資訊:
# xxx的職業是xxx,目前xxx歲,在xxx工作每個月能拿xxxx元。
# 例如結果是print('小明的職業是程式設計師,目前22歲,在北京工作每個月能拿10000')
print('%s的職業是%s,目前%s歲,在%s工作每個月能拿%s'%("小明","程式設計師",22,"北京",10000))
print('%s的職業是%s,目前%s歲,在%s工作每個月能拿%s'%(info[0][0],info[0][2],info[0][1],info[0][4],info[0][3]))
print('%s的職業是%s,目前%s歲,在%s工作每個月能拿%s'%(info[1][0],info[1][2],info[1][1],info[1][4],info[1][3]))
print('%s的職業是%s,目前%s歲,在%s工作每個月能拿%s'%(info[2][0],info[2][2],info[2][1],info[2][4],info[2][3]))

# 將列表中的數位都做平方處理
num=[1,2,3,'a','b','c']
num[0]=num[0]**2
num[1]=num[1]**2
num[2]=num[2]**2
num

# 獲取到列表中所有的奇數
num=[0,1,2,3,4,5,6,7,8,9,10]
>>> num[1::2]
[1, 3, 5, 7, 9]