Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 需要缩进吗?_Python_Indentation - Fatal编程技术网

Python 需要缩进吗?

Python 需要缩进吗?,python,indentation,Python,Indentation,我对python有点陌生,正在进行一个小的文本冒险。到目前为止,我一直都很顺利。我目前正在实现一个剑系统,如果你有一把一定大小的剑,你可以杀死一定大小的怪物。我正在尝试编写另一个怪物遭遇战的代码,我已经编写了剑的代码,但是我正在尝试用else到if…elif…elif语句来完成它,即使我在正确的缩进中,它仍然说应该缩进,我不知道该怎么做,代码如下: print ('you find a monster about 3/4 your size do you attack? Y/N') yesnot

我对python有点陌生,正在进行一个小的文本冒险。到目前为止,我一直都很顺利。我目前正在实现一个剑系统,如果你有一把一定大小的剑,你可以杀死一定大小的怪物。我正在尝试编写另一个怪物遭遇战的代码,我已经编写了剑的代码,但是我正在尝试用
else
if…elif…elif
语句来完成它,即使我在正确的缩进中,它仍然说应该缩进,我不知道该怎么做,代码如下:

print ('you find a monster about 3/4 your size do you attack? Y/N')
yesnotwo=input()
if yesnotwo == 'Y':
    if ssword == 'Y':
        print ('armed with a small sword you charge the monster, you impale it before it can attack it has 50 gold')
        gold += 50
        print ('you now have ' + str(gold) + ' gold')
    elif msword == 'Y':
        print ('armed with a medium sword you charge the monster, you impale the monster before it can attack it has 50 gold')
        gold += 50
        print ('you now have ' + str(gold) + ' gold')
    elif lsword == 'Y':
        print ('armed with a large broadsword you charge the beast splitting it in half before it can attack you find 50 gold ')
        gold += 50
        print ('you now have ' + str(gold) + ' gold')
    else:

事实上,关于Python中的缩进,您需要了解很多事情:

Python非常关心缩进。 在其他语言中,缩进是不必要的,但只用于提高可读性。在Python中,缩进是必要的,它替换了其他语言的关键字
begin/end
{}

这是在执行代码之前验证的。因此,即使从未到达带有缩进错误的代码,它也不会工作

有不同的缩进错误,阅读它们会有很大帮助: 1<代码>缩进错误:应为缩进块

出现这种错误的原因有多种,但常见的原因是:

  • 您有一个
    ,下面没有缩进块。
以下是两个例子:

示例1,无缩进块:

输入:

if 3 != 4:
    print("usual")
else:
if 3 != 4:
print("usual")
a = 3
  a += 3
输出:

  File "<stdin>", line 4

    ^
IndentationError: expected an indented block
  File "<stdin>", line 2
    a += 3
    ^
IndentationError: unexpected indent
输出

  File "<stdin>", line 2
    print("usual")
        ^
IndentationError: expected an indented block
输出:

  File "<stdin>", line 4

    ^
IndentationError: expected an indented block
  File "<stdin>", line 2
    a += 3
    ^
IndentationError: unexpected indent
文件“”,第2行
a+=3
^
缩进错误:意外缩进
输出表示第2行不需要缩进块。您应该通过删除缩进来解决此问题

3<代码>制表符错误:缩进中制表符和空格的使用不一致

  • 但基本上,您在代码中使用了制表符和空格
  • 你不会想要的
  • 删除所有选项卡并将其替换为四个空格
  • 并将编辑器配置为自动执行此操作
  • 你可以得到更多的信息

最后,回到你的问题上来:

我有它在正确的缩进,它仍然说缩进预期我不知道该怎么做


只需查看错误的行号,并使用前面的信息进行修复。

如果
else
下确实没有任何代码,请确保使用相同类型的缩进(即空格vs制表符),你会得到一个缩进错误。这只是你代码的一个片段吗?另外,当我尝试运行这部分代码时,这一切都不起作用,可能是因为我上面有错误,我会检查,可能是因为if-else没有else,它很挑剔请阅读:“空格是首选的缩进方法。制表符应仅用于与已缩进制表符的代码保持一致。”