Python中IF-ELSE块的缩进 [英] Indentation of an IF-ELSE block in Python

查看:89
本文介绍了Python中IF-ELSE块的缩进的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python新手,并且正在使用Python在 NLP 上进行工作.我在Python中编写 if-else 块时出错.当我当时只编写一个 if 块时,它工作正常:

I am Python newbie and I am working on NLP using Python. I am having an error in writing an if-else block in Python. When I am writing only an if block at that time it is working fine:

if xyzzy.endswith('l'):
    print xyzzy

输入冒号(:)后,我按 Enter ,它会自动将我带到正确的缩进位置.

After entering a colon (:) I am pressing Enter and it is automatically taking me to the correct indentation.

但是当我尝试在打印语句后按 Enter 键后向其中添加 else 块时,它认为它是 IF 块,所以它给了我不正确的缩进,因为之后我想要一个 else 块,而当我尝试编写else块我的自我时,却给了我这个错误./p>

But when I am trying to add an else block to it after pressing the Enter key after the print statement, it is considering it to be statement of an IF block only, so it is giving me incorrect indentation as I want an else block after, while when I am trying to write else block my self it is giving me this error.

else:
   ^

IndentationError:意外缩进

写完打印报告后我该怎么办? Enter 显然不起作用,因为它将光标向前移动,而当我使用 space 指向正确的指针时,这给我一个错误.

What should I do after writing print statement? Enter is clearly not working, because it is taking the cursor forward, while when I use space to come to the correct pointer it is giving me an error.

推荐答案

很难从帖子中看出问题所在,但是 if-else 的格式如下

It's hard to see from your post what the problem is, but an if-else is formatted like so

 if someCondition:
     do_something       # could be a single statement, or a series of statements
 else:
     do_something_else  # could be a single statement, or a series of statements

即, else 必须与相应的 if 处于相同级别.

I.e., the else needs to be at the same level as the corresponding if.

if 上查看此 Python文档/教程,以及其他教程.

有时候您的编辑器会自动为您缩进,并且您手动编辑时,事情也会变得一团糟,因此您必须弄清楚编辑器如何处理缩进(例如,是否始终使用 tabs 或空格?,如果您按回车键会怎样?

Sometimes when your editor does autoindent for you and you edit manually too things might get messed up, so you'll have to figure out how your editor handles indentations (e.g., is it always using tabs or spaces?, what happens if you hit return etc).

此外,请注意不要混用制表符和空格,这也会引起问题(很难发现,因为它们都是不可见的")

Also, be wary of mixing tabs and spaces, that will cause problems too (hard to spot since both are "invisible")

更新后的帖子:

   if xyzzy.endswith('l'):
       print xyzzy
   else:
       something_else

这篇关于Python中IF-ELSE块的缩进的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆