簡體   English   中英

Python期望縮進塊

[英]Python expected an indented block

我是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

有什么錯誤,我該如何解決?

在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代碼。

正確的語法(每個塊縮進。其中大多數以“:”結尾的行之后開始):

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM