【问题标题】:Is there a problem with how I am indenting this if loop? [duplicate]我如何缩进这个 if 循环有问题吗? [复制]
【发布时间】:2019-10-20 07:46:51
【问题描述】:

我现在正在学习 python,并且正在制作图形。它工作了一段时间,创建了一个窗口并显示了正确的图形,但不知何故我弄乱了格式,现在运行程序时它总是显示错误。

我已经尝试删除格式并让 VS Code 为我自动格式化,但仍然显示相同的错误。

这里是first.py

from graphics import *
import time
def isset(v):
    return v in locals() or v in globals()  
a = GraphWin('Test', 1000, 800)
a.setCoords(1000, -800, -1000, 800)
a.setBackground('white')
b = Entry(Point(0, 0), 20)
b.setFill('white')
b.draw(a);
c = Text(Point(0, 80), 'What is your name?')
c.draw(a)
while True:
    key = a.checkKey()
    if key == 'Return':
        if b.getText():
            d = Text(Point(0, 0), 'Hello, '+str(b.getText())+'!')
        b.setText('')
        b.undraw()
        c.undraw()
        d.draw(a)
        time.sleep(2)
        d.undraw()
        b.draw(a)
        c = Text(Point(0, 80), 'How old are you?')
        c.draw(a)
        break

while True:
    key = a.checkKey()
    if key == 'Return':
        if b.getText():
            d = Text(Point(0, 0), 'You are '+str(b.getText())+' years old!')
            b.undraw()
            c.undraw()
            d.draw(a)
            time.sleep(1)
        for i in range(5, 0, -1):
            if isset('e'):
                e.undraw()
            e = Text(Point(0, -80), 'Window closing in: '+str(i))
            e.draw(a)
            time.sleep(1)
            break

这是终端输出:

$ python3 first.py
  File "first.py", line 17
    d = Text(Point(0, 0), 'Hello, '+str(b.getText())+'!')
                                                        ^
TabError: inconsistent use of tabs and spaces in indentation

请告诉我我做错了什么!

我终其一生都无法弄清楚我的代码发生了什么,这让我发疯了。

【问题讨论】:

  • 从上面复制你的python代码,保存到一个文件中,然后尝试运行它。这应该删除所有标签。
  • if 不是循环。此外,错误意味着它所说的。我假设你知道什么是空格,什么是制表符。您不能假设一个制表符代表特定数量的空格,或者在缩进中切换空格和制表符的顺序。实际上,您应该选择一个并坚持下去。更实际的是,use four spaces per indent and do not use tabs - 这是社区标准。
  • 您使用的是哪个文本编辑器?我在使用 vscode 时遇到过类似的挑战,但可以通过更改您的偏好轻松解决。

标签: python python-3.x


【解决方案1】:

您同时使用空格和制表符进行缩进。只要您保持一致,Python 都接受。使用制表符或空格,不能同时使用。

【讨论】:

  • 谢谢你我删除了所有缩进,然后重新缩进,它可以工作
猜你喜欢
  • 2015-11-28
  • 2019-03-18
  • 2011-02-06
  • 1970-01-01
  • 1970-01-01
  • 2021-10-03
  • 2014-12-05
相关资源
最近更新 更多