Python期望缩进块 [英] Python expected an indented block

查看:206
本文介绍了Python期望缩进块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,并且想根据几何分布生成一些数字.我在Internet上找到了此代码,但无法正常工作:

I am a newbie to Python and would like to genereate some numbers according to geometric distribution. i found this code on Internet but isn´t work:

  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)

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

When I try to run it tells me the following error:

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

什么是错误,我该如何解决?

What is the error and how I can fix it?

推荐答案

在Python中,缩进很重要. PEP 8 涵盖了良好的缩进样式.

In Python, indentation is significant. PEP 8 covers good indentation style.

以您的一个功能为例,它看起来应该像这样:

To take one of your functions as an example, it should look like this:

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代码.

If it's not indented properly, it's not valid Python code.

这篇关于Python期望缩进块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆