Python期待有缩进的代码块

-2 投票
2 回答
17623 浏览
提问于 2025-04-17 12:02

我刚开始学习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 个回答

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)
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代码了。

撰写回答