【问题标题】:New to Python- How do I store a biased number generator as function?Python新手-如何将有偏数字生成器存储为函数?
【发布时间】:2016-07-01 00:39:04
【问题描述】:

这不适用于任何项目或任何东西,只是在搞乱。 (在 python shell 中执行此操作)

import random
def rand1():
    random.gauss(0, 0.1) * 0.3 + random.gauss(0, 3) * 0.7

rand1() + 1

它想出了

TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

为什么rand1() 在数学运算中不起作用? 即使我将它存储在像rand2 = rand1() 这样的变量中,它仍然会出现相同的消息。有没有办法将它存储为浮点数而不是 NoneType?

【问题讨论】:

  • 你没有从你的函数中返回任何东西,所以它返回None
  • 你需要返回你的结果
  • 请解释一下,从我的函数中返回一些东西是什么意思?
  • @Cogswellx:看我的回答。

标签: python function nonetype


【解决方案1】:

函数的语法是

def functionname():
# function operations - this is just a comment, noted by the #!
<tab>x = 2 + 2
<tab>return x

这个“返回x”给调用者。标签&lt;tab&gt; 是必要的,让解释器知道它是函数的一部分。

根据我阅读的内容和我写的内容,我认为您的意思是:

import random
def rand1():
    return random.gauss(0, 0.1) * 0.3 + random.gauss(0, 3) * 0.7

rand1() + 1

【讨论】:

  • 谢谢,我想我现在开始明白了。抱歉这个愚蠢的问题(你们回答得真快!)
  • @Cogswellx 没有问题是一个愚蠢的问题。如果您正坐在编译器/解释器面前并且想知道要写什么,那么这里就是您要问的正确地方。如果这解决了您的问题,请单击复选标记。
猜你喜欢
  • 2016-09-15
  • 2014-11-08
  • 2023-03-24
  • 2019-02-28
  • 2014-09-23
  • 2021-11-09
  • 2012-09-12
  • 1970-01-01
  • 2019-10-17
相关资源
最近更新 更多