需要缩进?

2024-04-30 03:49:23 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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:

Tags: the代码youifwithitcanprint
1条回答
网友
1楼 · 发布于 2024-04-30 03:49:23

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

Python非常关心缩进。

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

这在代码执行之前得到验证。因此,即使永远无法到达带有缩进错误的代码,它也不会工作。

有不同的缩进错误,阅读这些错误会有很大帮助:

1。IndentationError: expected an indented block

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

  • 下面有一个:没有缩进的块。

下面是两个例子:

示例1,无缩进块:

输入:

if 3 != 4:
    print("usual")
else:

输出:

  File "<stdin>", line 4

    ^
IndentationError: expected an indented block

输出声明您需要在第4行的else:语句之后有一个缩进块。

示例2,未缩进块:

输入:

if 3 != 4:
print("usual")

输出

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

输出声明您需要在第2行的if 3 != 4:语句之后有一个缩进块。

2。IndentationError: unexpected indent

缩进块很重要,但只缩进应该缩进的块。此错误表示:

-前面有一个没有:的缩进块。

示例:

输入:

a = 3
  a += 3

输出:

  File "<stdin>", line 2
    a += 3
    ^
IndentationError: unexpected indent

输出声明它在第2行不需要缩进的块。您应该通过删除缩进来解决这个问题。

3。TabError: inconsistent use of tabs and spaces in indentation

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


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

I have it in the right indentation it still says indent expected I don't know what to do

只需查看错误的行号,然后使用前面的信息修复它。

相关问题 更多 >