python語句--條件陳述式

來源:互聯網
上載者:User

標籤:python語句


一、print語句、import語句、指派陳述式。

1.1、print語句:輸出

>>> print(2,3,4)    //python2.x
(2, 3, 4)
>>>

>>> print(1,2,3)    //python3.x
1 2 3
>>>

備忘:print函數在輸出時會在每個參數之間都插入一個空格符

在python2.x中,print的參數會構成一個元組,但是在python3.x中,print參數會構成一個元組。

如果不想在各參數之間留有空格,用串連字元“+”(加號)。如:

>>> print(1+2+3)    //按整數進行相加操作
6
>>> print(‘1‘+‘2‘+‘3‘)    //字元串連操作。
123
>>>


1.2、import語句:把某件事作為另一件事匯入

從模組匯入函數方法一:import somemodule

從模組匯入函數方法二:from somemodule import somefunction

從模組匯入函數方法三:from somemodule import somefunction,anotherfunction,yetanotherfunction

從模組匯入函數方法四:from somemodule import *

從模組匯入函數方法五:import math as foobar    //增加模組別名,關鍵字as 後為模組的別名

從模組匯入函數方法六:from math import sqrt as foobar    //增加函數別名,關鍵字as後為函數別名

            如:from module1 import open as open1

                    from module2 import open as open2

只有確定自己想要從給定的模組中匯入所有功能時,才應該使用方法四。如果一個函數在兩個模組中都有,如open函數,可以使用方法一匯入,然後像下面這樣使用函數:

module1.open(...)

module2.open(...)


1.3、指派陳述式

a)、序列解包:多個賦值同時進行(兩邊的變數需數量一致)

如:

python3.x中

>>> x,y,z=1,2,3
>>> x
1
>>> y
2
>>> z
3
>>> print(x,y,z)
1 2 3
>>>

  python2.x中

>>> x,y,z=1,2,3
>>> x
1
>>> y
2
>>> z
3
>>> 

>>> print(x,y,z)
(1, 2, 3)


>>> x,y,z=1,2,3    
>>> print(x,y,z)
(1, 2, 3)
>>> x,y,z=z,x,y        //交換變數
>>> print(x,y,z)
(3, 1, 2)
>>>

備忘:序列解包(或叫迭代解包)將多個值的序列解開,然後放到變數的序列中。更形象的表示方法如:

>>> values=1,2,3
>>> values
(1, 2, 3)
>>> x,y,z=values
>>> print(x,z,y)
(1, 3, 2)
>>>


取字典中的鍵-值對:

>>> d={‘name‘:‘zhangsan‘,‘age‘:‘30‘}
>>> d
{‘age‘: ‘30‘, ‘name‘: ‘zhangsan‘}
>>> key,value=d.popitem()    //用popitem方法(隨機取字典中的鍵-值對刪除)賦值給變數(key、value)。
>>> key
‘age‘
>>> value
‘30‘
>>> print(key,value)
(‘age‘, ‘30‘)
>>> d
{‘name‘: ‘zhangsan‘}
>>>

b)、鏈式賦值:

鏈式賦值(chained assigment)是將同一個值賦給多個變數的捷徑。

如:

>>> x=y=1
>>> x
1
>>> y
1
>>>

等同於:

>>> y=1
>>> x=y
>>> x
1
>>>


c)、增量賦值(+=、-=、*=、\=、%=)

x+=1: 即x=x+1,其他增量類似。

注意:對於其他資料類型同樣適用(只要二元運算子本身適用於這些資料類型即可):

如:

>>> a=‘love‘
>>> a+=‘u‘
>>> a
‘loveu‘
>>> a*=3
>>> a
‘loveuloveuloveu‘
>>>

二、語句塊

語句塊是在條件為真(條件陳述式)時執行或者執行多次(迴圈語句)的一組語句。在代碼前放置空格來縮排語句即可建立語句塊。當然tab字元也可以縮排語句塊,一個tab為8個空格,建議用空格縮排

    很多程式設計語言使用特殊單詞或者字元(比如begin或{ )來表示一個語句塊的開始,用另外的單詞(end或者 })來表示語句塊的結束。在python中,冒號(:)用來標識語句塊的開始,塊中的每一個語句都是縮排的(縮排量相同)。當回退到和已經閉合的塊一樣的縮排量時,表示當前語句塊結束。


三、條件和條件陳述式:

  


python語句--條件陳述式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.