2017/02/02 23:17

# Pythod初学之简单语法

[TOC]

## 3.计算

### 3.1加减乘除求余

+-*/和大多数编程语言类似。不同的是，除法(/)的结果是float。如果想要只保留整数则用//

>>> 1+1
2
>>> 2*5
10
>>> 6-4
2
>>> 5/3
1.6666666666666667
>>> 5//3
1
>>> 5%3
2


### 3.2平方

>>> 5**2
25
>>> 2**10
1024


### 3.3赋值

>>> width=20
>>> height=5*9
>>> width*height
900


>>> n  # try to access an undefined variable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined


### 3.4浮点型

>>> 1+2
3
>>> 1+2.0
3.0


### 3.5最后一次计算值

>>> 1+2
3
>>> _
3


### 3.6四舍五入

>>> round(12.556,2)
12.56


## 4.字符串

>>> span
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'span' is not defined
>>> span='spam eggs'
>>> span
'spam eggs'
>>> span='doesn\'t'
>>> span
"doesn't"
>>> span='"Yes,"he said'
>>> span
'"Yes,"he said'
>>> span='"Isn\'t, she said."'
>>> span
'"Isn\'t, she said."'



>>> span = '"Isn\'t," she said'
>>> span
'"Isn\'t," she said'
>>> print(span)
"Isn't," she said
>>> span = 'First line.\nSecond line.'
>>> span
'First line.\nSecond line.'
>>> print(span)
First line.
Second line.


### 4.1转义

>>> span=r'C:\some\name'
>>> span
'C:\\some\\name'
>>> print(span)
C:\some\name


### 4.2多行

String的字面值可以跨越多行。一种方式是使用三引号（triple-quotes）"""..."""或者'''...'''. 行结束符会自动的包含在string中，但可以在行尾添加\来阻止这种。

>>> span = '''
... 此前会换行'''
>>> print(span)

>>> span = '''\
... 此前不会换行'''
>>> print(span)



### 4.3拼接

strings可以使用操作符+串起来（concatenated, glued together），使用*来表示重复：

>>> 3*'um'+'ium'
'umumumium'


>>> 'a''b''c'
'abc'


>>> prefix="Py"
>>> prefix 'thon'
File "<stdin>", line 1
prefix 'thon'
^
SyntaxError: invalid syntax



>>> prefix
'Py'
>>> prefix+'thon'
'Python'


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


### 4.4截取

>>> word='Python'
>>> word[0]
'P'
>>> word[2]
't'


>>> word='Python'
>>> word[0]
'P'
>>> word[2]
't'
>>> word[-1]
'n'
>>> word[-5]
'y'


>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5]  # characters from position 2 (included) to 5 (excluded)
'tho'


>>> word[:2]
'Py'
>>> word[2:]
'thon'
>>> word[:2]+word[2:]
'Python'


>>> word
'Python'
>>> word[-2]
'o'
>>> word[-2:]
'on'
>>> word[:]
'Python'


 +---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

>>> word[0:1]
'P'
>>> word[5:6]
'n'


>>> word[42]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range


>>> word[:]
'Python'
>>> word[0:1]
'P'
>>> word[0:42]
'Python'
>>> word[42:45]
''
>>> word[2:2]
''
>>> word[3,1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
>>> word[3:1]
''


python中的字符串不能被改变，string是不可变的。因此给string中索引位置初赋值会得到一个错误：

>>> word[0]='j'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment


>>> 'j'+word[1:]
'jython'
>>> word[:2]+'py'
'Pypy'


### 4.5长度

>>> len(word)
6


## 5. Lists

>>> squares = [1, 4, 9 ,16, 25]
>>> squares
[1, 4, 9, 16, 25]
>>> squares[0]
1
>>> squares[2]
9
>>> squares[-1]
25
>>> squares[-3:]
[9, 16, 25]
>>> squares[:]
[1, 4, 9, 16, 25]
>>> squares[3:1]
[]
>>> squares[23:45]
[]


### 5.1拼接

lists也支持聚合操作：

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


>>> cubes = [1, 8, 27, 65, 125]  # something's wrong here
>>> 4 ** 3  # the cube of 4 is 64, not 65!
64
>>> cubes[3] = 64  # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]


>>> cubes.append(216)  # add the cube of 6
>>> cubes.append(7 ** 3)  # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]


### 5.2赋值

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]


### 5.3长度

>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4


### 5.4多维数组

lists也可以嵌套lists（创建一个lists包含其他lists）

>>> 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'


## 6程序设计第一步

>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
...     print(b)
...     a, b = b, a+b
...
1
1
2
3
5
8


• 第一行包含多重赋值。变量ab同时获得新value 0 和 1. 最后一行再次使用，展示了右边的表达式（expression)先执行，在任何赋值发生之前。右边的表达式执行顺序是从左到右。
• 只要条件(condition),此处（b<10）结果仍然是true, while循环就执行。在Python，就像C语言，任何非零整数为true。条件也可以是string或者list value，事实上任何序列（sequence），任何非零长度的序列为true，空序列是false。测试中用到的是一个简单的比较。标准的比较操作同C语言相同：<（less than）,>（greater than),==(equal to),<=(less than or equal to),>=(greater than or equal to) and !=(not equal to).
• 循环体是缩进的：缩进是Python的声明分组的方法。在交互式情景中，你必须为每个缩进行输入一个制表符（tab)或者空格（spaces)。实际上，你会使用文本编辑器准备更复杂的输入； 所有的正规的编辑器都带有自动缩进的功能。当交互式的输入一个复杂语句，你必须随后输入一个空白行来表示完成（因为解析器不能猜测你什么时候输入最后一行）。注意一个基本模块的每一行都必须缩进相同的数量。
• print()方法打印传进来的参数。不同于仅仅是打印，你想要写的表达式（像我们之前在计算示例中使用的）处理多种参数，浮点型float数量，string. string打印的时候不带括号，每个条目之间会插入一个空格，因此你可以格式化string更美观：
>>> i = 256*256
>>> print('The value of i is', i)
The value of i is 65536


>>> 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,


### 注脚

[1] 因为 **-有更高的优先级， -3**2将会被解释为-(3**2),即-9。为了避免这种情况并得到9，你可以使用(-3)**2.
[2] 不像其他语言，特殊字符，比如\n...有相同的意义。唯一的不同是单引号不必转义"(但要转义\')，反之亦然。

0
1 收藏

0 评论
1 收藏
0