Python期望一个缩进块

时间:2012-01-31 16:26:28

标签: python indentation

我是Python的新手,想根据几何分布生成一些数字。我在互联网上找到了这个代码但不起作用:

  import random
from math import ceil, log

def geometric(p):

# p should be in (0.0, 1.0].
if ((p <= 0.0) or (p >=1.0)):
raise ValueError("p must be in the interval (0.0, 1.0]")
elif p == 1.0:
# If p is exactly 1.0, then the only possible generated value is 1.
# Recognizing this case early means that we can avoid a log(0.0) later.
# The exact floating point comparison should be fine. log(eps) works just
# dandy.
return 1

# random() returns a number in [0, 1). The log() function does not
# like 0.
U = 1.0 - random.random()

# Find the corresponding geometric variate by inverting the uniform variate.
G = int(ceil(log(U) / log(1.0 - p)))
return G

p=1.0/2.0
for i in range(10):
print geometric(p)

当我尝试运行它时会告诉我以下错误:

    File "test.py", line 8
    if (p <= 0.0) or (p >=1.0):
     ^
IndentationError: expected an indented block

错误是什么以及如何解决?

2 个答案:

答案 0 :(得分:6)

在Python中,缩进很重要。 PEP 8涵盖了良好的缩进风格。

以您的某个功能为例,它应如下所示:

def geometric(p):
    # p should be in (0.0, 1.0].
    if ((p <= 0.0) or (p >=1.0)):
        raise ValueError("p must be in the interval (0.0, 1.0]")
    elif p == 1.0:
        # If p is exactly 1.0, then the only possible generated value is 1.
        # Recognizing this case early means that we can avoid a log(0.0) later.
        # The exact floating point comparison should be fine. log(eps) works just
        # dandy.
        return 1

如果它没有正确缩进,则它不是有效的Python代码。

答案 1 :(得分:2)

正确的语法(每个块的缩进。大多数在以“:”结尾的行后开始):

import random
from math import ceil, log

def geometric(p):

  # p should be in (0.0, 1.0].
  if ((p <= 0.0) or (p >=1.0)):
    raise ValueError("p must be in the interval (0.0, 1.0]")
  elif p == 1.0:
    # If p is exactly 1.0, then the only possible generated value is 1.
    # Recognizing this case early means that we can avoid a log(0.0) later.
    # The exact floating point comparison should be fine. log(eps) works just
    # dandy.
    return 1

  # random() returns a number in [0, 1). The log() function does not
  # like 0.
  U = 1.0 - random.random()

  # Find the corresponding geometric variate by inverting the uniform variate.
  G = int(ceil(log(U) / log(1.0 - p)))
  return G

p=1.0/2.0
for i in range(10):
  print geometric(p)