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

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

问题描述

我是python新手,我正在使用python开发NLP.我在python中编写if-else块时出错.当我仅在那时阻塞时才写得很好:

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

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

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

after entering colon I am pressing enter and it is automatically taking me to the correct indentation.

但是当我尝试在打印语句后按"Enter"键后向其添加else块时, 它只是考虑将其作为IF块的语句,因此它给了我不正确的缩进,因为我想在之后进行else块,而当我尝试编写else块我的自我时,这给了我这个错误.

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

else:  
   ^

IndentationError: unexpected indent

那么写完打印报表后我该怎么办?输入显然不起作用,因为它使光标向前移动,而当我使用空格来指向正确的指针时,它给了我一个错误.

so 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 a 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天全站免登陆