python - Python 中缺少必需的位置参数

标签 python function return-value

下面是我试图在我的代码中做的事情的例子......

def func():
x = int (input ('enter x: '))
return x

def func2():
y = int (input( 'enter y: '))
return y

def func3(x,y):
print(randomint(x,y))

def main():
func()
func2()
func3()

main()

我想知道的是,为什么我不能使用我通过输入定义并在函数结束时返回的 x 和 y 变量?当这个程序试图运行时,它说函数缺少必需的参数。愚蠢的我知道,我是 python 的新手。

此外,我如何在我正在创建的一个函数中使用变量,这些变量是在另一个单独的函数中定义的?谢谢!

最佳答案

你说你知道如何缩进所以我不打算讨论这个,手头的问题是你需要从 funcfunc2 在他们被抓到之后。

你可以这样做:

def func():
    x = int (input ('enter x: '))
    return x

def func2():
    y = int (input( 'enter y: '))
    return y

def func3(x,y): # there's two positional value so you will need to pass two values to it when calling
    print(randomint(x,y))

def main():
    x = func() # catch the x
    y = func2() # catch the y
    func3(x,y) # pass along x and y which acts as the two positional values
    # if you're lazy, you can directly do:
    # func3(func(), func2()) which passes the return values directly to func3

main()

另一种方法是使用全局语句,但这不是适合您的情况的最佳方法。

提示:如果您使用随机模块,随机整数被调用:random.randint(x,y)

关于python - Python 中缺少必需的位置参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43334191/

相关文章:

python - 反转 'newsdate',没有找到任何参数。尝试了 1 种模式 : ['newsdate/(?P<year>[0-9]+)$' ]

jquery函数将html代码加载到div中,然后将其他内容加载到加载的html内的div中

c - 在 C 中传递、编辑和返回变量

c - 是否可以在函数原型(prototype)中指定返回类型而不是在c中的函数定义中指定返回类型?

php - jQuery Ajax 返回整个页面

python - 了解 python 字典的顺序

android - 我们如何为基于 python 的应用程序创建 android apk

python - 使用 Azure API 在 Azure Boards 上创建新任务

c++ - 判断2个数是否为=、>或<的函数

jquery - 获取 jQuery MultiSelect 下拉列表中的值?