python-2.7 - Python “expected an indented block”

标签 python-2.7 error-handling

我正在运行以下脚本进行验证:

def num_val(x):
while True:
    try:
        userInput = raw_input("Please, enter the length of list " + x + " (only values from 1 to 100 are valid): ")
        val = int(userInput)
    except ValueError:
        print("Entered value must be a number. Please, write the number again")
        continue
    if userInput < 1 or userInput > 100:
        print ("Entered value must be a number in range from 1 to 100. Please write the number again")
    else:
break
num_val("a")

我收到以下消息:
print ("Entered value must be a number in range from 1 to 100. Please write the number again")
    ^
IndentationError: expected an indented block

你能告诉我那条线是什么问题吗?

最佳答案

通过复制和粘贴,您的代码看起来可能包含空格和制表符,这可能会导致奇怪的错误。以下对我有用:

def num_val(x):
    while True:
        try:
            userInput = raw_input("Please, enter the length of list " + x + " (only values from 1 to 100 are valid): ")
            val = int(userInput)
        except ValueError:
            print("Entered value must be a number. Please, write the number again")
            continue
        if val < 1 or val > 100:    # <-- use "val" instead of "userInput"
            print ("Entered value must be a number in range from 1 to 100. Please write the number again")
        else:
            break

num_val("a")

如何预防这类问题?取决于您的编辑器。许多编辑器都有“扩展选项卡”或类似的设置,对于Python代码,您应该利用该功能。这样,当您按下Tab键时,编辑器将插入空格。在Python中,Tab characters line up every 8 columns和其他缩进处的空格可能会使解析器感到困惑。

另请注意,if语句应使用val而不是userInput,因为val是数字,而userInput是文本。

关于python-2.7 - Python “expected an indented block”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35673060/

相关文章:

python - 在 Python 中从 unicode 字符串中去除标点符号的最快方法

python - Pyserial - RS232 9600,8,N,1 发送和接收数据

python - hashlib 模块出现错误

powershell - 使用 Try/Catch 输出错误

python-2.7 - 如何合并两个数据框而不丢失任何行

Python 查找一个列表中介于另一个列表值之间的值的方法

jquery - 如何捕获 Ajax 查询发布错误?

powershell - 使用Invoke-Command时“You cannot call a method on a null-valued expression”

python - Bluemix Python App启动失败

python - 我们如何才能使 __future__ 进口全局化?