什么是错误,什么是缩进块?

时间:2017-04-13 19:05:59

标签: python indentation

当我运行下面的程序时

from sys import argv
# this one is like your scripts with argv

def print_two(*args):
arg1=args,
arg2 = args,
print "arg1: %r, arg2: %r" % arg1, % arg2

# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2)

# this just takes one argument
def print_one(arg1):
print "arg1: %r" % arg1s

# this one takes no arguments
def print_none():
print "I got nothing."

print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()

输出:

IndentationError: expected an indented block
PS C:\Users\user> python F:\software\Python\ex18.py   
File "F:\software\Python\ex18.py", line 4     
arg1,arg2 = args       
^

2 个答案:

答案 0 :(得分:3)

在Python中,缩进很重要。你应该看看PEP 8,更具体地说是缩进部分。请记住:如果您的代码没有缩进,那么它就不是有效的Python代码。

根据this Python 3 tutorial

  

块是程序或脚本中的一组语句。通常它由至少一个语句和块的声明组成,具体取决于编程或脚本语言。

     

允许使用块进行分组的语言称为块结构化语言。通常,块也可以包含块,因此我们得到嵌套块结构。

     

脚本或程序中的块用作将要处理的语句分组的方法,就好像它们是一个语句一样。在许多情况下,它还可以作为限制变量和函数的词法范围的方法。

     

enter image description here

因此,如果正确缩进代码,代码应该可以正常工作:

from sys import argv
# this one is like your scripts with argv

def print_two(*args):
    arg1=args,
    arg2 = args,
    print "arg1: %r, arg2: %r" % arg1, % arg2

# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
    print "arg1: %r, arg2: %r" % (arg1, arg2)

# this just takes one argument
def print_one(arg1):
    print "arg1: %r" % arg1s

# this one takes no arguments
def print_none():
    print "I got nothing."

print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()

答案 1 :(得分:0)

您的代码没有正确缩进。错误说清楚了。

1)你必须缩进你的代码。 Python严格遵循缩进。

2)在第7行中,您的代码arg1arg2应该重新格式化。

应该打印print_one函数arg1中的

3),而不是arg1s

您可以按如下方式运行代码。

from sys import argv
# this one is like your scripts with argv

def print_two(*args):
    arg1=args,
    arg2 = args,
    print "arg1: %r, arg2: %r" % (arg1, arg2)

# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
    print "arg1: %r, arg2: %r" % (arg1, arg2)

# this just takes one argument
def print_one(arg1):
    print "arg1: %r" % arg1

# this one takes no arguments
def print_none():
    print "I got nothing."

print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()