python語句與語法

Python的語句與語法

語句 角色 例子
賦值 創建引用值 a='Apple',b='bike'
調用 執行函數 log.write('mylog')
打印調用 打印對象 print(1,'hello')
if/elif/else 選擇動作 if a in b: print(a)
for/else 序列迭代 for i in list: print(i)
while/else 一般循環 while True: print('True')
pass 空佔位符 for i in list: pass
break 循環/迭代退出 while True:if a==b: break
continue 循環繼續 for i in list: if i<5: continue
def 函數定義 def add(a,b): print(a+b)
return 函數返回 def add(a,b): return a+b
import 模塊訪問 import os
from 屬性訪問 from sys import stdin
class 創建類 class myclass(): def myprint(): print('myprint')
try/except/finally 捕獲異常 try: open('/tmp/file') except: print('no file')
raise 觸發異常 raise <'error type'>
assert 調試檢查 assert a<0,'a is too large'
with/as 環境管理器 with open(file) as f: f.read()
del 刪除引用 del_list[i] del_list[i:j] del obj.attr

Python語句的格式

語句的開頭

在python裏是不使用{}或者別的符號來限制語句的開始和結尾的,一個語句的開始(除了複合語句),就是開頭,換行就是結束。在開頭,不能隨意增加空格:

>>> print (1)
1
>>>  print (1)
  File "<stdin>", line 1
    print (1)
    ^
IndentationError: unexpected indent

語句的對齊

在複合語句裏也是同樣的,當你使用縮進時,必須一致:

>>> def add(str):
...     str=str
...    print(str)
  File "<stdin>", line 3
    print(str)
             ^
IndentationError: unindent does not match any outer indentation

複合語句

複合語句有單行寫法和多行寫法。從冒號後面就是複合語句的開始。
單行:複合語句只有一行時,可使用單行寫法,但是複合語句所包含的語句不是單行時,需要使用對齊的縮進來表示複合語句

#單行語句
>>> if 1>0: print(1)
...
1
#多行語句
>>> if 1>0:
...     int=1
...     print(int)
...
1

語句的結束

一般語句裏,一行的結束就是此語句的結束。
在簡單語句可以使用分號來隔開多個語句。

>>> a=3;b=3;print(a+b)
6

使用列表,元組,字典的時候按照一定的方式可以把一個語句分成多行:

>>> dict={1:'first',
... 2:'second'}

處理錯誤

當我們所寫的語句有bug,會出現一些錯誤,程序會中斷運行。
但我們在這個時候,不想讓程序中斷但還是需要提示報錯的時候可以使用try:

>>> while True:
    _input=input("please input digit:")
    try:
        print("{:d} *10 is {:d}".format(int(_input),int(_input)*10))
        break
    except:
        print("{} is not a number".format(_input))

please input digit:a
a is not a number
please input digit:1
1 *10 is 10

變量賦值

變量命名規則

變量名可以使大小寫字母,數字和下劃線,但只能以大小寫字母和下劃線開頭,不能以數字開頭。變量名是區分大小寫的,保留字符是不能使用的。
python3.0裏的保留字符:
false class finally is
None continue for lambda
True def from nonlocal
and del dlobal not
as elif if or
assert else import pass
break except in raise
特殊變量名:
main等,前後都有兩個下劃線的變量名,有很多是有特殊意義的

打印

print 函數

從python3.0開始print變成了函數,但返回值爲None,print函數的格式如下:
print([object,...][,sep=''][,end='\'][file=sys.stdout])
在這裏,object是要打印的內容。object可以是任意對象。默認是沒有。
sep是兩個object之間隔開的字符。默認是一個空格。
end是結尾,默認爲換行。
file爲輸出目標,默認爲標準輸出流。

>> print(1,2,3,sep=';')
1;2;3
>>> print(1,2,3,sep=':')
1:2:3
>>> print(1,2,3,end='')
1 2 3
>>> print(1,2,3,end='');print (4,5,6,end='')
1 2 34 5 6
>>> print(1,2,3,end='\n');print (4,5,6,end='')
1 2 3
4 5 6
>>> print(1,2,3,file=open(r'D:\ruanjian\1.txt','wt'))
>>> file=open(r'D:\ruanjian\1.txt')

>>> file.read()

'1 2 3\n'

判斷語句

真值測試

在if語句裏的<'test'>位置裏的就是判斷語句,結果爲True,就能進入子語句,判斷語句包含:

  • 比較運算符:==,!=,>,<,>=,<=
  • 邏輯運算符:and,or,not
  • 成員運算符:in,not in
  • 身份運算符:is,is not
  • 其他:對象爲空,0,None等的時候是False,其他爲True
    >>> 1<2
    True
    >>> True and True
    True
    >>> 1 and True
    True
    >>> True or False
    True
    >>> not True
    False
    >>> not False
    True
    >>> 1 in [1,2]
    True
    >>> 1 in (1,2)
    True
    >>> 1 in {'1':1}
    False

邏輯運算符

當我們使用and和or的時候,返回結果不一定是True或False:
and:當其中一個或多個測試值爲false的時候,取第一個false的值

False
>>> 1 and [] and {}
[]

and:當全部值得測試值爲True的時候,取最後一個值

>>> 1 and 2 and True
True
>>> 1 and 2 and True
True
>>> 1 and 2 and True and 3
3

or:當其中一個或多個值爲True的時候,取第一個True的值

>>> 0 or [1] or {1:'1'}
[1]
>>> 1 or 0 or 2
1

or:當全部值爲false的時候,去左後一個false值

>>> 0 or [] or {}
{}
>>> False or 0 or {}
{}

三元表達式

三元表達式的格式如下:
<'value1'>if <''test'> else <'value2'>
當測試值爲真的時候取<'value1'>,假的時候取<'value2'>

>>> 1 if True else 2
1
>>> 1 if False else 2
2
>>> 'True' if 1>2 else 'False'
'False'
>>> 'True' if 1<2 else 'False'
'True'

這個還可以如下運用:
[<'value2'>,<'value1'>][<'test'>]

>>> [2,1][True]
1
>>> [2,1][False]
2
>>> ['False','True'][1>2]
'False'
>>> ['False','True'][1<2]
'True'

while語句

whil語句一般格式:

while <'test1'>:
    <'statement1'>
else:
    <'statement2'>

只要測試語句爲真,會一直循環<'statement1'>。當test1爲假的時候會運行else語句裏的內容。從這裏,退出循環的方法有:
1.在<'statement1'>裏的語句更改<'test1'>的結果爲False
2.在<'statement1'>裏的語句裏增加break語句來跳出循環
3.在<'statement1'>裏的語句裏增加exit()來退出python循環,不過這裏會退出整個的python程序

例子

>>> a=0;b=10
>>> while a<b:
    print(a,end='')
    a+=1

0123456789

break,continue語句

break語句用來退出最近所在的for語句或while語句。
continue語句是用來跳到最近所在的for語句或者while語句的結尾。

>>> a=0;b=10
>>> while a<b:
    a+=1
    if a==3: continue
    if a ==7: break
    print (a,end='')

12456

pass語句

pass語句是佔位的空語句,在有些複合語句裏,可能沒有具體的語句,但需要正常運行,這就需要設置空語句(pass)來代替
例子

>>> if True:
    print('true')
else: pass

true

else語句

else語句,只有在for語句和while語句正常結束後,會運行:

>>> a=0;b=10
>>> while a<b:
    print(a,end='')
    a+=1
else:
    print('end')

0123456789end

for語句

for語句在python裏是一個通用的序列迭代器:可以遍歷任何有序的序列對象內的元素。可用於字符串、列表、元組、其他內置可迭代對象以及之後我們能通過類所創建的新對象。
一般格式:

for <target> in <object>:
    <statements>
else:
    <statements>

在這裏object需是可迭代的對象。每次從object裏提取一個元素付給target,之後循環statements裏的語句。
例子

>>> for i in a:
    print (i,end='')

12345

用法

使用for循環時,其他開發語言會使用一個變量,定義起始,結束,遞增值。但python裏只能做迭代。這個時候可以使用range函數來代替。
range函數格式:
range([起始值,]結束值,[遞增值])
在這裏,起始值默認是0,遞增值默認爲1。

>>> a=range(10)
>>> for i in a:
    print(i,end='')

0123456789

當迭代後的元素爲固定長度的元組。列表的時候:

>>> for a,b,c in [(1,2,3),(4,5,6),(7,8,9)]:
    print (a,b,c)

1 2 3
4 5 6
7 8 9

嵌套循環(不一定是固定長度):

>>> for l in [(1,2,3),(4,5,6),(7,8,9)]:
    for i in l:
        print(i,end='')
    print()

123
456
789

迭代器和解析

文件迭代器

文件訪問方式如下:

  • <'file'>.read():一次性讀取全部內容。
  • <'file'>.readline():一次讀取一行。
  • <'file'>.readlines():生成列表,每一行是每個元素。
  • <'file'>.next():跟readline()差不多,但讀取完之後報錯。

__next__()報錯爲stoplteration。在python中任何這類對象都認爲是可迭代的。在python裏迭代工具(比如for)會調用__next__()來獲取數據,並以stoplteration來確認何時離開。

儘量不要使用readlines()函數,因爲這個會一次性得把所有內容讀取到內存裏(轉換爲列表),運行速度會比較慢。

手動迭代

爲了支持手動迭代代碼,python支持next()函數,它會自動讀取__next__()函數。
next(X)等同於X.__next__()

>>> file=open(r'D:\ruanjian\1.txt')
>>> file.__next__()
'hello,world'
>>> file.seek(0)
0
>>> next(file)
'hello,world'
>>> next(file)
Traceback (most recent call last):
  File "<pyshell#135>", line 1, in <module>
    next(file)
StopIteration

這個會從第一行開始讀取內容,但是這個文本文件就一行,所以讀完之後再讀會報錯。
迭代協議裏,當時用for函數進行迭代時,會傳遞給iter()內置函數,以便可迭代對象中獲取迭代器。返回的對象中有next()方法

>>> li=[1,2,3]
>>> i=iter(li)
>>> next(i)
1
>>> next(i)
2
>>> next(i)
3
>>> next(i)
Traceback (most recent call last):
  File "<pyshell#141>", line 1, in <module>
    next(i)
StopIteration

對於文件來說,不需要轉換成iter類型的這一步,
因爲文件對象就是自己的迭代器。

>>> file=open(r'D:\ruanjian\1.txt')
>>> file is iter(file)
True

但列表,元組,字符串就不是了。

>>> s='123';l=[1,2,3];t=(1,2,3)
>>> s is iter(s)
False
>>> l is iter(l)
False
>>> t is iter(t)
False

如果要使用next方法就需要先將字符串,列表,元組轉換成迭代器

其他內置類型迭代器

除了文件以及像列表這樣的實際的序列外,其他類型也有其適用的迭代器。例如,遍歷字典鍵的經典方法是明確的獲取其鍵的列表。

>>> dic={'a':1,'b':2,'c':3}
>>> for key in dic.keys():
    print(key,dic[key])

a 1
b 2
c 3

這個迭代器也可以直接對字典進行迭代:

>>> iter1=iter(dic)
>>> iter1.__next__()
'a'
>>> next(iter1)
'b'
>>> next(iter1)
'c'

列表解析

遍歷列表時,使用for循環來修飾它:

>>> li=[1,2,3,4,5]
>>> for i in range(len(li)):
    li[i]+=10

>>> li
[11, 12, 13, 14, 15]

但這樣看來並不簡便,我們可以使用產生所需列表的一個單個表達式來完成上面的循環

>>> li=[1,2,3,4,5]
>>> li=[i+10 for i in li ]
>>> li
[11, 12, 13, 14, 15]

這個先是運算[i+10 for i in li]之後,再把此值賦給li,具體的運算是先是對li進行迭代,每次把單個值賦給i,在進行i+10,成爲新列表的單個元素。

擴展用法

我們可以使用如下方法,將列表的某一項排除

>>> li=[1,2,3,4,5]
>>> li=[i+10 for i in li if i != 3]
>>> li
[11, 12, 14, 15]

也可以在列表中進行循環嵌套,可以看到y的循環嵌套在了x循環裏

>>> [x+y for x in [1,2,3] for y in [10,20,30]]
[11, 21, 31, 12, 22, 32, 13, 23, 33]

其他迭代環境

map也可用在迭代

>>> list(map(str.upper,open(r'D:\ruanjian\1.txt')))
['HELLO,WORLD']

map函數是把後面的可迭代的每個值當做前面的參數傳入。
上面的語句可以如下解釋:

>>> tmp=[]
>>> for line in open(r'D:\ruanjian\1.txt'):
    tmp.append(str.upper(line))

>>> tmp
['HELLO,WORLD']

相應的也有sorted會對迭代對象進行排序後生成列表

>>> sorted(open(r'D:\ruanjian\1.txt'))
['hello,world']

numerate也會對迭代對象進行運算後生成可迭代列表。enumerate就是在原有的順序中添加序列號。

>>> list(enumerate(open(r'D:\ruanjian\1.txt')))
[(0, 'hello,world')]

sum、any、all、max、min也可使用迭代器。

>>> max([3,5,1,6,4]),min([3,6,8,2,4])
(6, 2)
>>> any([1,[],'True']),all([1,[],'True'])
(True, False)

python3中新的可迭代對象

在python3中函數生成的是可迭代的特定對象:

>>> range(5)
range(0, 5)
>>> list(range(5))
[0, 1, 2, 3, 4]

python3的這種方式會延遲計算,在提取內容的時候計算結果,這樣會節省內存空間,不需要提前計算後放進內存,迭代對象迭代完成後不能再次讀取

>>> def printlist(list1):
    for i in list1:
        print('function print:{}'.format(i))
        yield 'Result: {}'.format(i)

>>> li=[1,2,3,4,5]
>>> s=printlist(li)
>>> s.__next__()
function print:1
'Result: 1'
>>> s.__next__()
function print:2
'Result: 2'
>>> s.__next__()
function print:3
'Result: 3'

歡迎各位關注本人微信公衆號“沒有故事的陳師傅”

python語句與語法

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章