Python3學習筆記 | 十一、Python的語句與語法-語句簡介

  • 2019 年 10 月 7 日
  • 筆記

一、Python的語句

二、Python語句的格式

1、語句的開頭

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

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

第二次print前面是多了一個空格,這樣的話,也會報錯。 在Python里,一個語句的開始,是嚴格控制的。不能有多餘的空格。

2、語句的對齊

關於嚴格控制,在複合語句里也是同樣的。當你使用縮進時,必須一致:

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

我們會發現縮進不對齊,也會發生錯誤。

3、複合語句

複合語句,有單行寫法和多行寫法。從冒號後面就是複合語句的開始 單行:複合語句里只有一行時,可使用單行寫法:

>>> if 1 > 0 : print(1)  ...  1

但是,複合語句所包涵的語句不是單行時,需要使用對其的縮進來表示複合語句:

>>> if 1 > 0 :  ...     output = 1  ...     print(output)  ...  1

4、語句的結束

一般語句里,一行的結束就是此語句的結束。在簡單語句(比如賦值,列印等)可以使用分號(;)來隔開多個語句。

>>> a = 'Dora';b = 'Emon';print(a+b)  DoraEmon

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

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

每一個對象,符號之間可以有多個空格或者換行,但是不能把一個對象分成兩行。 複合語句的結束:在腳本里是縮進的結束,在交互模式下,還需要一個空行。

>>> if 1>0:print(1)  ...  1

三、Python的縮進

在Python里,複合語句是使用嚴格的縮進對齊來表示同一層次。 縮進可使用1個以上的空格或者製表符(tab),具體數量沒有嚴格限制,但必須對齊。

>>> if 1 > 0 :  ...  print(1)  ...  1  >>> if 1 > 0 :  ...     print(1)  ...  1

在多層嵌套時,一定要注意縮進。

>>> for i in range(1,7):  ...     if i > 3 :  ...             if i < 5 :  ...                     print(i)  ...     else :  ...             print('NULL')  ...  NULL  NULL  NULL4

四、對用戶輸入數據的判斷

在Python里,有input的方法,可以讀取用戶數據。但是我們不能限制用戶輸入的數據是純文本或者純數字。這個時候我們可以使用判斷語句來進行測試,輸入錯誤就讓用戶重新輸入。

>>> while True:  ...     _input = input("Please input number:")  ...     if _input.isdigit():  ...         print("{:d} * 10 is {:d}".format(int(_input),int(_input)*10))  ...         break  ...     else:  ...         print("{} is not a number".format(_input))  ...  Please input number:11 * 10 is 10

關於input函數的使用可以參考http://www.runoob.com/python/python-func-input.html

五、處理異常

當我們所寫的語句有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:e  e is not a number  Please input digit:33 * 10 is 30

關於Python異常的處理可以參考http://www.runoob.com/python/python-exceptions.html


Tags: