python中if和else语句的格式要求,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

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

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.

解决方案

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

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

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

With your updated post:

if xyzzy.endswith('l'):

print xyzzy

else:

something_else

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值