第十一章 Assignments, Expressions, and Prints

1.Assignment Statements

  • Assignments create object references.
  • Names are created when first assigned.
  • Names must be assigned before being referenced.
  • Some operations perform assignments implicitly.



1.1 Sequence Assignments

>>> nudge = 1 # Basic assignment
>>> wink = 2
>>> A, B = nudge, wink # Tuple assignment
>>> A, B # Like A = nudge; B = wink
(1, 2)
>>> [C, D] = [nudge, wink] # List assignment
>>> C, D
(1, 2)

交换两个变量

>>> nudge = 1
>>> wink = 2
>>> nudge, wink = wink, nudge # Tuples: swaps values
>>> nudge, wink # Like T = nudge; nudge = wink; wink = T
(2, 1)
tuple and list assignment accept any type of sequence (really, iterable) on the right as long as it is of the same length as the sequence on the left.
>>> [a, b, c] = (1, 2, 3) # Assign tuple of values to list of names
>>> a, c
(1, 3)
>>> (a, b, c) = "ABC" # Assign string of characters to tuple
>>> a, c
('A', 'C')

>>> string = 'SPAM'
>>> a, b, c, d = string # Same number on both sides
>>> a, d
('S', 'M')
>>> a, b, c = string # Error if not
...error text omitted...
ValueError: too many values to unpack (expected 3)


>>> a, b, c = string[0], string[1], string[2:] # Index and slice
>>> a, b, c
('S', 'P', 'AM')
>>> a, b, c = list(string[:2]) + [string[2:]] # Slice and concatenate
>>> a, b, c
('S', 'P', 'AM')
>>> a, b = string[:2] # Same, but simpler
>>> c = string[2:]
>>> a, b, c
('S', 'P', 'AM')
>>> (a, b), c = string[:2], string[2:] # Nested sequences
>>> a, b, c
('S', 'P', 'AM')

>>> ((a, b), c) = ('SP', 'AM') # Paired by shape and position
>>> a, b, c
('S', 'P', 'AM')

for (a, b, c) in [(1, 2, 3), (4, 5, 6)]: ... # Simple tuple assignment
for ((a, b), c) in [((1, 2), 3), ((4, 5), 6)]: ... # Nested tuple assignment

>>> red, green, blue = range(3)   #range(3) 0,1,2
>>> red, blue
(0, 2)

>>> type(range(3))
<class 'range'>
>>> list(range(3))
[0, 1, 2]
>>> 


>>> L = [1, 2, 3, 4]
>>> while L:
...  front, L = L[0], L[1:] # See next section for 3.X * alternative
...  print(front, L)
...
1 [2, 3, 4]
2 [3, 4]
3 [4]
4 []

等价
... front = L[0]
... L = L[1:]

1.2 Extended Sequence Unpacking in Python 3.X

works for any sequence types (really, again, any iterable)

>>> seq = [1, 2, 3, 4]
>>> a, b, c, d = seq
>>> print(a, b, c, d)
1 2 3 4
>>> a, b = seq
ValueError: too many values to unpack (expected 2)

>>> a, *b = seq
>>> a
1
>>> b
[2, 3, 4]

>>> *a, b = seq
>>> a
[1, 2, 3]
>>> b
4

>>> a, *b, c = seq
>>> a
1
>>> b
[2, 3]
>>> c
4

>>> a, *b, c = 'spam'
>>> a, b, c
('s', ['p', 'a'], 'm')

>>> a, *b, c = range(4)
>>> a, b, c
(0, [1, 2], 3)

>>> L = [1, 2, 3, 4]
>>> while L:
... front, *L = L # Get first, rest without slicing
... print(front, L)
...
1 [2, 3, 4]
2 [3, 4]
3 [4]
4 []

注意:

  • the starred name is always assigned a list
  • Second, if there is nothing left to match the starred name, it is assigned an empty list
  • errors can still be triggered if there is more than one starred name


>>> seq = [1, 2, 3, 4]
>>> a, b, c, *d = seq
>>> print(a, b, c, d)
1 2 3 [4]

>>> a, b, *e, c, d = seq
>>> print(a, b, c, d, e)
1 2 3 4 []
>>> a, *b, c, *d = seq
SyntaxError: two starred expressions in assignment


>>> *a = seq
SyntaxError: starred assignment target must be in a list or tuple
>>> *a, = seq
>>> a
[1, 2, 3, 4]


Multiple-target assignment and shared references

>>> a = b = 0  #immutable types
>>> b = b + 1
>>> a, b
(0, 1)

>>> a = b = []   #mutable object
>>> b.append(42)
>>> a, b
([42], [42])


Augmented Assignments


>>> L = []
>>> L += 'spam' # += and extend allow any sequence, but + does not!
>>> L
['s', 'p', 'a', 'm']
>>> L = L + 'spam'
TypeError: can only concatenate list (not "str") to list

Augmented assignment and shared references

>>> L = [1, 2]
>>> M = L # L and M reference the same object
>>> L = L + [3, 4] # Concatenation makes a new object
>>> L, M # Changes L but not M
([1, 2, 3, 4], [1, 2])

>>> L = [1, 2]
>>> M = L
>>> L += [3, 4] # But += really means extend
>>> L, M # M sees the in-place change too!
([1, 2, 3, 4], [1, 2, 3, 4])


Variable Name Rules

  • Syntax: (underscore or letter) + (any number of letters, digits, or underscores)
  • Case matters: SPAM is not the same as spam
  • Reserved words are off-limits


Naming conventions

  • Names that begin with a single underscore (_X) are not imported by a from module import * statement
  • Names that have two leading and trailing underscores (__X__) are system-defined names that have special meaning to the interpreter.
  • Names that begin with two underscores and do not end with two more (__X) are localized (“mangled”) to enclosing classes
  • The name that is just a single underscore (_) retains the result of the last expression when you are working interactively.

2.Expression Statements



>>> x = print('spam') # print is a function call expression in 3.X
spam
>>> print(x) # But it is coded as an expression statement
None

>>> L = L.append(4) # But append returns None, not L
>>> print(L) # So we lose our list!
None

3.Print Operations


The Python 3.X print Function

Call format:print([object, ...][, sep=' '][, end='\n'][, file=sys.stdout][, flush=False])

>>> x = 'spam'
>>> y = 99
>>> z = ['eggs']
>>>
>>> print(x, y, z) # Print three objects per defaults
spam 99 ['eggs']

>>> print(x, y, z, sep='') # Suppress separator
spam99['eggs']
>>>
>>> print(x, y, z, sep=', ') # Custom separator
spam, 99, ['eggs']


>>> print(x, y, z, end='') # Suppress line break
spam 99 ['eggs']>>>

>>> print(x, y, z, sep='...', end='!\n') # Multiple keywords
spam...99...['eggs']!
>>> print(x, y, z, end='!\n', sep='...') # Order doesn't matter
spam...99...['eggs']!

The Python 2.X print Statement



Print Stream Redirection

>>> print('hello world') # Print a string object in 3.X
hello world
>>> print 'hello world' # Print a string object in 2.X
hello world


>>> 'hello world' # Interactive echoes
'hello world'


operations this way:
>>> import sys # Printing the hard way
>>> sys.stdout.write('hello world\n')
hello world

print(X, Y) # Or, in 2.X: print X, Y

等价
import sys
sys.stdout.write(str(X) + ' ' + str(Y) + '\n')


重定向
import sys
sys.stdout = open('log.txt', 'a') # Redirects prints to a file
...
print(x, y, x) # Shows up in log.txt

Automatic stream redirection


C:\code> c:\python33\python
>>> import sys
>>> temp = sys.stdout # Save for restoring later
>>> sys.stdout = open('log.txt', 'a') # Redirect prints to a file
>>> print('spam') # Prints go to file, not here
>>> print(1, 2, 3)
>>> sys.stdout.close() # Flush output to disk
>>> sys.stdout = temp # Restore original stream
>>> print('back here') # Prints show up here again
back here
>>> print(open('log.txt').read()) # Result of earlier prints
spam
1 2 3

C:\code> c:\python33\python
>>> log = open('log.txt', 'w')
>>> print(1, 2, 3, file=log) # For 2.X: print >> log, 1, 2, 3
>>> print(4, 5, 6, file=log)
>>> log.close()
>>> print(7, 8, 9) # For 2.X: print 7, 8, 9
7 8 9


Version-Neutral Printing

  • 2to3 converter
  • Importing from __future__      (  from __future__ import print_function)(最先导入)


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值