天天看點

The Python Tutorial 筆記 2-4 2. Using the Python Interpreter 3. An Informal Introduction to Python 4. More Control Flow Tools

Source

2. Using the Python Interpreter

2.1. Invoking the Interpreter

添加path

set path=%path%;C:\python36      

widows 退出解釋器: ^Z or quit()

The interpreter’s line-editing features include interactive editing, history substitution and code completion on systems that support readline.Perhaps the quickest check to see whether command line editing is supported is typing 

Control-P

 to the first Python prompt you get. If it beeps, you have command line editing; see Appendix Interactive Input Editing and History Substitution for an introduction to the keys. If nothing appears to happen, or if 

^P

 is echoed, command line editing isn’t available; you’ll only be able to use backspace to remove characters from the current line.

Control-P會觸發提示窗"Print to defaut printer", 似乎和其他應用有熱鍵沖突。 行編輯功能不能使用。

The interpreter operates somewhat like the Unix shell: when called with standard input connected to a tty device, it reads and executes commands interactively; when called with a file name argument or with a file as standard input, it reads and executes a script from that file.

A second way of starting the interpreter is 

python -c command [arg] ...

, which executes the statement(s) in command, analogous to the shell’s 

-c

 option. Since Python statements often contain spaces or other characters that are special to the shell, it is usually advised to quote command in its entirety with single quotes.

Some Python modules are also useful as scripts. These can be invoked using 

python -m module [arg] ...

, which executes the source file for module as if you had spelled out its full name on the command line.

When a script file is used, it is sometimes useful to be able to run the script and enter interactive mode afterwards. This can be done by passing 

-i

 before the script.

All command line options are described in Command line and environment.

2.1.1. Argument Passing

When known to the interpreter, the script name and additional arguments thereafter are turned into a list of strings and assigned to the 

argv

 variable in the 

sys

 module. You can access this list by executing 

import sys

. The length of the list is at least one; when no script and no arguments are given, 

sys.argv[0]

 is an empty string. When the script name is given as 

'-'

 (meaning standard input), 

sys.argv[0]

 is set to 

'-'

. When 

-c

 command is used, 

sys.argv[0]

 is set to 

'-c'

. When 

-m

 module is used, 

sys.argv[0]

 is set to the full name of the located module. Options found after 

-c

 command or 

-m

 module are not consumed by the Python interpreter’s option processing but left in 

sys.argv

 for the command or module to handle.

2.1.2. Interactive Mode (是什麼?)

the primary prompt usually three greater-than signs (

>>>

); 比如在windows cmd下輸入python,則顯示:

C:\Users\xxxxx>python
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
           

continuation lines it prompts with the  secondary prompt , by default three dots (

...

). Continuation lines are needed when entering a multi-line construct. 一次輸入多行代碼,代碼體内部行用secondary prompt打頭。

2.2. The Interpreter and Its Environment

2.2.1. Source Code Encoding

By default, Python source files are treated as encoded in UTF-8. 編輯器需要識别UTF-8編碼,所用字型也用支援UTF-8

不使用預設編碼要明示,通常在源程式檔案首行。

# -*- coding: encoding -*-
           

3. An Informal Introduction to Python

Note that a secondary prompt on a line by itself in an example means you must type a blank line; this is used to end a multi-line command. 多行指令用空行終止

python的注釋号  #, 字元串中的#不算注釋開頭

3.1. Using Python as a Calculator

>>> 8 / 5  # division always returns a floating point number
1.6
           

差別于C/C++ 整型相除得到整型

int 整型 float 浮點型

floor division 用 //

取餘 %

乘方 **

指派=   指派語句執行後,解釋器不會有相應。

>>> a = 10
>>> a
10
           

未指派的變量不能直接使用

In interactive mode, the last printed expression is assigned to the variable 

_

上一個表達式計算結果存在變量_中,  _當作隻讀用,不要對其指派,否則就相當于定義了新的同名變量,不再有存前結果的功能

取小數位 round( 3.14159, 2)   3.14

其他資料類型Decimal, Fraction, complex number

3.1.2. Strings

字元串單雙引号等效,互動模式下,解釋器會用單引号,用反斜杠escape特殊符号

print()會直接把根據escape符号意義列印,如果不希望這麼做, 使用raw string, 

>>> print('C:\some\name')  # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name')  # note the r before the quote
C:\some\name
           

字元串可以占多行 """ """ ''' ''' 

+連接配接字元串    * 重複

字元串常量挨着會自動合并, 用于代碼中字元串拆多行,用括号括起來就可以

>>> text = ('Put several strings within parentheses '
...         'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
           

字元串索引,可正可負,從左數從0開始加,從右數從-1開始減

如何取子串, str[a,b] str[:a] str[b:]  含左不含右

字元串不能改變,給字元串字元指派會引起報錯

拓展

Text Sequence Type — str

Strings are examples of  sequence types, and support the common operations supported by such types.

String Methods

Strings support a large number of methods for basic transformations and searching.

Formatted string literals

String literals that have embedded expressions.

Format String Syntax

Information about string formatting with 

str.format()

.

printf-style String Formatting

The old formatting operations invoked when strings are the left operand of the 

%

 operator are described in more detail here.

3.1.3. Lists

和字元串一樣可以去子清單。子清單操作會傳回一個新的對象。

清單可以合并

>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
           

清單可以修改

append()在清單尾部添加

直接修改子清單

用空清單修改,相當于删除

清單可以嵌套

>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'
           

3.2. First Steps Towards Programming

01 >>> # Fibonacci series:(動态規劃版)
02 ... # the sum of two elements defines the next
03 ... a, b = 0, 1
04 >>> while b < 10:
05 ...     print(b)
06 ...     a, b = b, a+b
07 ...
           
03,  a multiple assignment, the variables 

a

 and 

b

 simultaneously get the new values 0 and 1.

06, again, the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.  右邊兩部分表達式先估值再同時分别付給左邊兩個變量,=右側兩個表達式從左到右估值

In Python, like in C, any non-zero integer value is true; zero is false.  非零true 零false 非空串true 空串false

比較運算符同C

python靠縮進來組織代碼塊,同一塊中的語句縮進量需要相等,用空行來結束代碼塊。

print()

 可以嚴格控制輸出格式。用end=' x',可以避免換行。
>>> a, b = 0, 1
>>> while b < 1000:
...     print(b, end=',')
...     a, b = b, a+b
...
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
           

4. More Control Flow Tools

4.1. if Statements

>>> if x < 0:

...     x = 0

...     print('Negative changed to zero')

... elif x == 0:

...     print('Zero')

... elif x == 1:

...     print('Single')

... else:

...     print('More')

...

沒有secondary prompt

4.2. for Statements

Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. 

for ... in...:

statements

4.3. The range() Function

>>> for i in range(5):

...     print(i)

...

range(開頭,結尾),不含結尾

range(開頭,結尾,步長)

To iterate over the indices of a sequence, you can combine range() and len()

It is an object which returns the successive items of the desired sequence when you iterate over it, but it doesn’t really make the list, thus saving space.

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

>>> for i, v in enumerate(['tic', 'tac', 'toe']):

...     print(i, v)

...

0 tic

1 tac

2 toe

4.4. break and continue Statements, and else Clauses on Loops

The break statement, like in C, breaks out of the smallest enclosing for or while loop.

從最内層的for和while循環中跳出

loop... else語句

正常結束執行else, break跳出不執行else,不需要像類C語言立flag。和try...else..語句相近,沒有exception就執行,有,不執行

The continue statement, continues with the next iteration of the loop:

4.5. pass Statements

空語句,類似C中的 ;

4.6. Defining Functions

def 函數名( 參數清單 ) :

""" 函數說明 """

函數語句

函數内定義的變量的作用域在函數體内。函數體内可以引用全局變量,但不能給全局變量指派,除非在全局語句中可以指派。

The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called;

thus, arguments are passed using call by value (where the value is always an object reference, not the value of the object). [1] 

When a function calls another function, a new local symbol table is created for that call.

renaming mechanism 重命名機制

函數名賦給了别的變量,這個變量也成了一個函數。

沒有顯式返值的函數實際上有返值--None (it’s a built-in name) 用print()可以列印出來。 類似于void函數

return語句同類C

Falling off the end of a function also returns None.

方法隸屬于對象,是由對象類型定義的。

4.7. More on Defining Functions

函數參數