错误是什么?缩进块是什么? [重复]

问题描述 投票:0回答:2

当我运行下面的程序时

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       
^
python indentation
2个回答
3
投票

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

根据这个Python 3教程

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

允许使用块进行分组的语言称为块结构语言。一般来说,块也可以包含块,因此我们得到了嵌套的块结构。

脚本或程序中的块充当将语句分组的一种方式,将它们视为一个语句。在许多情况下,它还可以用作限制变量和函数的词法范围的方法。

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

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()

0
投票

您的代码缩进不正确。错误说得很清楚。

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

2) 在第 7 行中,您的代码

arg1
arg2
应该重新格式化。

3) 在

print_one
函数
arg1
中应该打印,而不是
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()
© www.soinside.com 2019 - 2024. All rights reserved.