gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:52:37 27 4
gpt4 key购买 nike

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com