示例20:以艰难的方式学习Python

时间:2016-01-11 19:34:50

标签: python

我试图找到有关Python中+ =做什么的信息,但找不到任何令我满意的信息。在例如20的研究演习中,他要求您使用+ =重写脚本。即使只是一个小例子,它的作用或它可以取代它将是有帮助的。我怎么能改写这个?

from sys import argv

script, input_file = argv

def print_all(f):
    print f.read()

def rewind(f):
    print f.seek(0)

def print_a_line(line, f):
    print line, f.readline()

print "Here is the file: %r" % input_file

current_file = open(input_file)

print_all(current_file)

print "Now let's start from the beginning..."

rewind(current_file)

print "Here are the first three lines of the file:"

current_line = 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)

current_file.close()

3 个答案:

答案 0 :(得分:2)

+=运算符意味着向现有变量添加内容。 n += 2n = n + 2

相同

在您的示例中,不是current_line = current_line + 1,而是current_line += 1

答案 1 :(得分:0)

它从字面上解释了+=在此页面上的含义。

http://learnpythonthehardway.org/book/ex20.html

  

问:什么是+=

     

答:你知道我怎么用英语重写"它是"作为"它"?或者我可以重写"你是"作为"你"?在英语中,这称为收缩,这有点像两个操作=+的收缩。这意味着x = x + yx += y相同。

答案 2 :(得分:0)

+ =是Syntactic Sugar。您可以将Syntactic Sugar视为一个额外的东西,使某些东西变得更容易或更清晰。

这个特殊的Syntactic Sugar用于向现有变量(左边的变量,也称为左值)添加一个值(右边的值,也称为右值)。

你可以写

variable += 1 

as

variable = variable + 1 

和口译员没有什么不同。您也可以对其他运营商执行相同的操作。

var -= 8   # Subtracting
var *= 3   # Multiplication
var %= 2   # Modulus (Remainder of division)
var /= 4   # Division

或者你可能根本就没有。无论您的想法如何,您的代码都清晰易懂,易于打字。这真的是一种偏好。我通常会尝试坚持使用多种编程风格的一种或另一种类型。

相关问题