python中缩进在程序中_Python中可能存在混合缩进?

1586010002-jmsa.png

Looking at this question, I tried OP's the code on my machine. Here are a text version and a screenshot:

utSId.png

What just happened? This supposed to be a square function, and it is implemented correctly. To be sure, I copy-pasted the code, and tried it again:

JXif4.png

Well, I can't see any difference between these versions of square, but only the latter works.

The only reason I can think of is that I may have mixed tabs and spaces, so the return statement is actually indented, and so the loop is executed exactly once. But I could not reproduce it, and it looks like an unbelievable flaw in the interpreter's mixed-indentation-check. So I have two questions, or maybe three:

What do I miss?

If this is a mixed indentation thing, what it may be, exactly?

If this is a mixed indentation thing, why wasn't it caught by the interpreter? Obviously the whole idea of indentation in python (and in general) is to avoid such problems. And it's too important to let such things slip.

解决方案

Easy!

def square(x):

runningtotal = 0

for counter in range(x):

runningtotal = runningtotal + x

return runningtotal

First, tabs are replaced (from left to right) by one to eight spaces

such that the total number of characters up to and including the

replacement is a multiple of eight <...>

So this tab at the last line is replace with 8 spaces and it gets into the loop.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值