【问题标题】:How should I write a function with a numbers extension? [duplicate]我应该如何编写带有数字扩展名的函数? [复制]
【发布时间】:2019-10-15 17:52:10
【问题描述】:

我正在尝试创建一个代码,其中包含一个函数,用于计算两个数字之间的随机数(我在编写代码时选择该随机数),然后将其从 Num1 中取出。但是,当我运行它时,它生成的数字总是0。请你告诉我如何正确编写这个函数!这是下面的代码。

import random
MinNum = int(0)
MaxNum = int(0)
Num1 = int(36)

def RandomNum(x,y,z):
    MinNum = x
    MaxNum = y
    Num1 = z
    Num1 = Num1 - random.randint(MinNum, MaxNum)

RandomNum(5,17,Num1) # - I would type it in the code like this
print(Num1) # - This should print a number that is equal to: 36 - the number generated.

【问题讨论】:

  • 你的函数不会返回任何东西,也不会产生其他副作用,因此调用它绝对没有意义。
  • 你的函数所做的只是创建一些局部变量。你要么需要 return 从中获取一些东西,要么让它改变一些全局变量(避免这种情况)
  • 如果你想改变函数中的全局变量,你必须先将它们声明为global——否则默认情况下它们只是只能在函数内访问的局部变量。跨度>

标签: python function


【解决方案1】:

您似乎对局部变量和全局变量感到困惑。要使RandomNum 能够更改Num1 的值,您需要将变量设为全局变量,否则,它将创建一个单独的Num1 变量,该变量仅适用于RandomNum 函数的持续时间。这称为作用域。

例如

def f():
    a = 2 # this a is local to the f() function.
    print('Inside of f (local scope), a =', a)

a = 1 # this is set in the global scope
f()
print('On the global level (global scope) a =', a) # Now that are f() function is finished, a will go back to being equal to 1

输出

在 f(局部范围)内,a = 2

在全局级别(全局范围)a = 1


但是,您可以将变量声明为全局变量,就像这样。

def f():
    global a # this time a will refer to the same variable inside and outside of our f() function
    a = 2
    print('Inside of f (local scope), a =', a)

a = 1
f()
print('On the global level (global scope) a =', a)

然后你得到

在 f(局部范围)内,a = 2

在全局级别(全局范围)a = 2


如果我们将此应用到您的代码中,我们可以像这样修复它。

import random
MinNum = int(0)
MaxNum = int(0)
Num1 = int(36)

def RandomNum(x,y,z):
    global MinNum, MaxNum, Num1
    MinNum = x
    MaxNum = y
    Num1 = z
    Num1 = Num1 - random.randint(MinNum, MaxNum)

RandomNum(5,17,Num1)
print(Num1)

然而,让函数返回一些东西而不是操作全局变量更为常见。你的函数也可以这样重写。

import random

def RandomNum(minNum, maxNum, subtractedFrom):
    return subtractedFrom - random.randint(minNum, maxNum)

num1 = RandomNum(5, 17, 36)
print(result)

虽然确实没有理由首先拥有这个功能,因为RandomNum(5, 17, 36)random.randint(19, 31) 是一样的,所以你的代码可以简单地写成

import random
print( random.randint(19, 31) )

【讨论】:

  • 感谢您回答问题!它真的很有帮助。我需要从变量中减去它的原因是因为这就是我正在处理的项目中将要发生的事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-13
  • 2017-06-30
  • 2019-08-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多