Python基礎文法

來源:互聯網
上載者:User

標籤:python行 縮排 字典

一、行和縮排

   Python與其他語言最大的區別就是,Python的代碼塊不適用大括弧{}來控制類,數以及其他邏輯判斷。python 最具特色的就是用縮排來寫模組。

   縮排的空白數量是可變的,但是所有代碼塊語言必選包含相同的縮排空白數量,這個必須嚴格執行。

   如下所示:

           

 if True:    print "true" else:    print "false"

 以下代碼將會執行錯誤:

   

#!/usr/bin/python# -*- coding: UTF-8 -*-#  if True:    print "Answer"    print "True" else:    print "Answer"    # 沒有嚴格縮排,在執行時會報錯  print "False"

    執行後的代碼,會出現如下錯誤:

 

$ python test.py    File "test.py", line 5    if True:    ^IndentationError: unexpected indent

 二、print輸出

      

#!/usr/bin/python# -*- coding: UTF-8 -*-x="a"y="b"print (x)print (y)

三、if語句

四、字典
    字典是另一種可變容器模型,且可儲存任意類型對象。

     字典的每個索引值(key=>value)對用冒號(:)分割,每個對之前用逗號(,)分割,整個字典包括在括弧({})中。

    格式如下所示:

     d = {key1 : value1, key2 : value2 }

    鍵必須是唯一的,但值則不必。

    值可以取任何資料類型,但鍵必須是不可變得,如字串,數字或元組。

    一個簡單的字典執行個體:

      dict = {‘luwenjuan’: ‘123‘, ‘ningji‘ : ‘18‘}

  也可以如下字典:

      dict1 = {‘abc’:4456 };

      dict2 = {‘abc’: 123,456,45: 12};

#!/usr/bin/python dict = {‘Name‘: ‘Zara‘, ‘Age‘: 7, ‘Class‘: ‘First‘}; print "dict[‘Alice‘]: ", dict[‘Alice‘];

以上執行個體輸出結果:

dict[‘Alice‘]: Traceback (most recent call last):  File "test.py", line 5, in <module>    print "dict[‘Alice‘]: ", dict[‘Alice‘];KeyError: ‘Alice‘
五、修改字典   向字典添加新內容的方法是增加新的鍵/值對,修改或刪除已有鍵/值對如下執行個體:   #!/usr/bin/python   dict = { ‘name‘: ‘luwenjuan‘, ‘Age‘:18 ‘Class‘: ‘First‘};   dict [ ‘Age‘ ] = 19;   doct [ ‘School‘ ] = " DPS School";   print "dict [‘Age‘]: ", dict [‘Age‘];   print "dict [‘School‘] : ", dict [‘School‘];  以上執行個體輸出結果:      dict[‘Age‘]:  19     dict[‘School‘]:  DPS School
   


  

本文出自 “hcwj” 部落格,請務必保留此出處http://luwenjuan.blog.51cto.com/10967115/1922431

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.