python學習筆記(五)——語句


               語句(條件、循環和其他語句)

  之前一直在學習數據結構,單純的結構並不能做什么事,只有組成語句之后才能實現比較復雜的功能,和其他語言一樣,條件、循環是必不可少的。學習基本語句之前,先看一些其它知識。

關於print:

>>> print 1,2,3  #print的參數不能構成一個元組
1 2 3
>>> 1,2,3
(1, 2, 3)
>>> print (1,2,3)
(1, 2, 3)
>>> print 'Age',22  #輸出的每個參數之間插入了一個空格
Age 22
>>> name='jason'
>>> greeting='hello,'
>>> print greeting,name  #同時輸出文本和變量值
hello, jason

如果在結尾處加上逗號,那么接下來的語句會和前一條語句在同一行打印,如:

print 'hello,',
print 'world!'    #輸出的結果為hello,world,注意這里要在腳本中運行

關於模塊導入:

已經知道,導入模塊的時候可以有以下幾個方式:

import module

from module import function

from module import function1,function2,.....

from module import *

可以使用as為整個模塊或者函數提供別名:

>>> import math as m
>>> m.sqrt(4)
2.0
>>> from math import sqrt as S
>>> S(4)
2.0

關於賦值:

(1)、序列解包——將多個值的序列解開,然后放到變量的序列中

>>> x,y,z=1,2,3  #多個賦值操作可以同時進行
>>> print x,y,z
1 2 3
>>> x,y=y,x  #兩個或多個變量交換
>>> print x,y,z
2 1 3
>>> values=1,2,3  #序列解包
>>> values
(1, 2, 3)
>>> a,b,c=values
>>> a
1
#當函數或者方法返回元組時,這個很有用,它允許返回一個以上的值並打包成元組 >>> seq={'name':'jason','phone':'34223'} >>> key,value=seq.popitem() #獲取popitem方法刪除時返回的鍵值對 >>> key 'phone' >>> value '34223'

注意:解包的序列中的元素數量必須和放置在賦值號=左邊的變量數量完全一致

(2)、鏈式賦值

>>> x=y=z=2  #則xyz的值均為2
>>> y=3
>>> x=y
>>> x
3

(3)、增量賦值

>>> x=2
>>> x+=1
>>> x*=2
>>> x
6
>>> str='python'
>>> str*=2
>>> str
'pythonpython'

  在學習語句之前,我想說python中的縮進是個很坑爹的東西,它不僅僅是可讀性那么簡單了,少了或多了一個空格都是語法錯誤,而且很難排查,而且tab鍵也不太建議用,每個縮進是4個空格。因為python中的語句塊不是通過大括號來區分的,所以就由縮進擔當了這個大括號的角色,對它要求嚴格也很正常。

條件和條件語句:

(1)、布爾變量

  python中把空值和0也看作是false,總結下來,python中的假有如下幾個:

False,None,0,"",(),[],{}  即空字符串、空元組、空列表、空字典都為假。其它的一切都被解釋器解釋為真

>>> True
True
>>> False
False
>>> bool(0)
False
>>> bool("")
False
>>> bool(42)
True
>>> 0==0
True

(2)、if、elif、else語句(注意縮進且最好作為腳本運行而不是在交互式環境下)

num=input('enter a number:')
if num>0:
	print 'positive number'
elif num<0:
	print 'negative number'
else :
	print 'zero'
raw_input('press any key to exit!')

(3)、嵌套代碼塊

name=input('please input your name:')
if name.endswith('jzhou'):
    if name.startswith('Mr.'):
        print 'hello,Mr.jzhou'
    elif name.startswith('Mrs.'):
        print 'hello,Mrs.jzhou'
    else:
        print 'hello,jzhou'
else:
    print 'hello,stranger!'    
raw_input('press any key to exit!')

(4)、更復雜的條件

  1)、比較運算符(==,<,<=,>,>=,!=)

>>> 'foo'=='foo'
True
>>> 'foo'=='oof'
False
>>> 'foo'!='oof'
True

  2)、is:同一性運算符(判斷是否屬於同一個對象,而不是值是否相等)

>>> x=y=[1,2,3]
>>> z=[1,2,3]
>>> x==y
True
>>> x==z
True
>>> x is y
True
>>> x is z
False

  再看一個例子,有意讓x和y的值相等,看看它們是否屬於同一對象

>>> x=[1,2,3]
>>> y=[2,4]
>>> x is not y
True
>>> del x[2]  #刪除x中的元素3,即為[1,2]
>>> y[1]=1   #將y的第二個元素改為1,即為[2,1]
>>> y.reverse ()  #將y的元素倒序,即為[1,2]
>>> x==y
True
>>> x is y
False

  3)、in:成員資格運算符

>>> name
'jason'
>>> if 's' in name:
    print 'your name contains the letter "s"'
else :
    print 'your name doesn\'t contains the letter "s"'
    
your name contains the letter "s"

  4)、字符串和序列的比較

>>> "alpha"<"beta"
True
>>> 'Jzhou'.lower()=='JZHOU'.lower()
True
>>> [1,2]<[2,1]
True
>>> [2,[1,5]]>[2,[1,4]]
True

  5)、邏輯運算符(and,or)

>>> number=input('enter a number between 1 and 10:')
enter a number between 1 and 10:4
>>> if number <=10 and number >=1:
    print 'Great!'
else:
    print 'wrong!'

    
Great!

斷言——當輸入不符合條件時,可以用斷言來解釋,即在程序中置入檢查點

>>> age=-1
>>> assert 0<age<100,'The age must be realistic' #如果age輸入在[0,100]之外,則提示出錯

Traceback (most recent call last):
  File "<pyshell#79>", line 1, in <module>
    assert 0<age<100,'The age must be realistic'
AssertionError: The age must be realistic

循環

(1)、while

>>> x=1
>>> while x<=100:
    print x
    x+=1

(2)、for

>>> words=['this','is','an','egg']
>>> for word in words:
    print word
   
this
is
an
egg
>>> numbers=[1,2,3,4,5,6,7,8,9]
>>> for num in numbers:
    print num

有個內建的迭代函數range,它類似於分片,包含下界,不包含上界

>>> range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for num in range(1,5):
    print num

(3)、循環遍歷字典元素

>>> d={'x':1,'y':2,'z':3}
>>> for key in d:
    print key,'corresponds to',d[key]
    
y corresponds to 2
x corresponds to 1
z corresponds to 3
>>> for key,value in d.items ():  #這種用法很重要
    print key,'corresponds to',value
    
y corresponds to 2
x corresponds to 1
z corresponds to 3

常見迭代工具

(1)、並行迭代

>>> names=['jzhou','jason','james']
>>> ages=[22,42,45]
>>> for i in range(len(names)):  #i是循環索引
    print names[1],'is',ages[i],'years old'
    
jason is 22 years old
jason is 42 years old
jason is 45 years old

內建的zip函數可以進行並行迭代,並可以把兩個序列“壓縮”在一起,然后返回一個元素的列表

>>> for name,age in zip(names,ages):  #在循環中解包元組
    print name,'is',age,'years old'
   
jzhou is 22 years old
jason is 42 years old
james is 45 years old
# zip函數可以作用於任意多的序列,並且可以應付不等長的序列,最短的序列“用完”則停止
>>> zip(range(5),xrange(10000)) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
#注意:這里最好不要用range,因為range函數一次創建整個序列,而xrange一次只創建一個數。當需要迭代一個巨大的序列時,無疑xrange更高效。即此例中,使用xrange,序列只創建前5個數,而使用range則創建10000個,而我們只需要5個

(2)、翻轉和排序迭代

>>> sorted([4,3,6,8,3])
[3, 3, 4, 6, 8]
>>> sorted('hello,python!')
['!', ',', 'e', 'h', 'h', 'l', 'l', 'n', 'o', 'o', 'p', 't', 'y']
>>> list(reversed ('hello,world!'))
['!', 'd', 'l', 'r', 'o', 'w', ',', 'o', 'l', 'l', 'e', 'h']
>>> ''.join(reversed('Hello,world!'))
'!dlrow,olleH'

reversed和sorted函數和列表的reverse和sort函數類似

跳出循環

(1)、break——退出循環

>>> from math import sqrt
>>> for n in range(99,0,-1):
    root=sqrt(n)
    if root==int(root):
        print n
        break
    
81

設置range的步長(第三個參數)也可以進行迭代

>>> range(0,10,2)
[0, 2, 4, 6, 8]

(2)、continue——跳出本次循環,繼續下輪循環(不常用)

列表推導式——輕量級循環(列表推導式是利用其它列表創建新列表

>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

也可以在循環中加判斷條件,如計算能被3整除的數的平方

>>> [x*x for x in range(10) if x%3==0]
[0, 9, 36, 81]

也可以使用雙重循環,太強大了

>>> [(x,y) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

如果我們用普通方式實現上述的雙重循環,則代碼顯得有點冗余

>>> result=[]
>>> for x in range(3):
    for y in range(3):
        result .append((x,y))
        
>>> result
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

其它語句——pass,del,exec

(1)、pass

  由於python中空代碼塊是非法的,所以在什么事都不用做到情況下,可以使用pass作為占位符。(注釋和pass語句聯合的代替方案是插入字符串,后面筆記會介紹文檔字符串)

(2)、del

>>> x=1
>>> del x  #del會移除一個對象的引用,也會移除名字本身
>>> x   #x被刪除后,則不存在

Traceback (most recent call last): File "<pyshell#2>", line 1, in <module>
    x
NameError: name 'x' is not defined
>>> x=['hello','world']
>>> y=x  #x和y指向同一個列表
>>> y[1]='python'
>>> x
['hello', 'python']
>>> del x  #刪除x后,y依然存在,因為刪除的只是名稱,而不是列表本身的值
>>> y
['hello', 'python']

(3)、exec

  用來執行儲存在字符串或文件中的Python語句

>>> exec 'a=100'
>>> a
100
>>> exec 'print "hello,world!"'
hello,world!
>>> h=['hello']
>>> w='world'
>>> exec ('h.append(%s)' % 'w')
>>> h
['hello', 'world']

>>> str = "for i in range(0,5): print i"
>>> c = compile(str,'','exec')
>>> exec c
0
1
2
3
4

(4)eval

  用來計算存儲在字符串中的有效Python表達式。

>>> eval('2*3')
6

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM