Python中可能存在混合缩进? [英] Possible mixed indentation in Python?

查看:103
本文介绍了Python中可能存在混合缩进?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看这个问题,我在计算机上尝试了OP的代码。以下是文本版本和屏幕截图:

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

刚刚发生了什么?这应该是 square 函数,并且已正确实现。可以肯定的是,我复制粘贴了代码,然后再次尝试:

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:

我看不到这些版本的 square ,但只有后者有效。

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

我能想到的唯一原因是我可能混用了制表符和空格,因此 return 语句实际上是缩进的,因此循环仅执行一次。但是我无法复制它,它看起来像是口译员混合缩进检查中令人难以置信的缺陷。所以我有两个问题,或者可能是三个:

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:


  1. 我想念什么?

  2. 如果这是混合缩进的东西,究竟是什么?

  3. 如果这是混合缩进的东西,为什么解释器没有抓住它?显然,Python中(以及一般而言)缩进的整个 idea 都是为了避免此类问题。

  1. What do I miss?
  2. If this is a mixed indentation thing, what it may be, exactly?
  3. 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.


推荐答案

简单!

def square(x):
    runningtotal = 0
    for counter in range(x):
        runningtotal = runningtotal + x
<tab>return runningtotal




First ,制表符将由一到八个空格
取代(从左到右),以至
包括在内的总字符数为 8 < ...>

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 <...>

因此,最后一行的该选项卡将替换为8个空格,并进入循环。

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

这篇关于Python中可能存在混合缩进?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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