The Python Tutorial 笔记 2-4

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

函数参数








    
    


     
     


     
     


     
     


     
     


     
     


    
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值