简体   繁体   English

另一个函数的Python参数传递

[英]Python Parameter passing for another function

I have created two functions namely inputData(): and validateNumber(): In the inputData() function I enter a value and stores it in a variable called number.我创建了两个函数,即 inputData(): 和 validateNumber():在 inputData() 函数中,我输入一个值并将其存储在一个名为 number 的变量中。 And then I want to pass that parameter to validateNumber(): function.然后我想将该参数传递给 validateNumber(): 函数。 But it isn't work :( It would be fine if anyone explain me the error :) Regards.但这不起作用:(如果有人向我解释错误就好了:) 问候。

Here's the code:这是代码:

def inputData(): 
    number = int(input("Enter a Number: ")) 
    print(number)
    return number 

def validateNumber(number): 
    n=2 
    while number > n:
        if number%n==0 and n!=number:
            print("Not Prime") 
            break 
        else: 
            print("Prime") 
            break 
    return number

inputData()
validateNumber()

这是错误代码

You need to perform the function call as follows:您需要按如下方式执行函数调用:

validateNumber(inputData())

or

number = inputData()
validateNumber(number)

with def validateNumber(number) you are telling python that the function validateNumber must receive one parameter when it is called.使用def validateNumber(number)你告诉 python 函数validateNumber在调用时必须接收一个参数。 But, you are not passing the parameter to it when you call it.但是,当您调用它时,您并没有将参数传递给它。

If you are new to programming, check this tutorial: Python Functions , to understand:如果您不熟悉编程,请查看本教程: Python 函数,以了解:

  • What are functions什么是函数
  • How to define them如何定义它们
  • How to use them.如何使用它们。

You need to store the value of inputData() function in some variable then pass it to second function like this您需要将 inputData() 函数的值存储在某个变量中,然后像这样将其传递给第二个函数

>> number = inputData()
>> validateNumber(number)

You're not passing the inputted number to the validate function.您没有将输入的数字传递给验证函数。

returned_input_number = inputData()
validateNumber(returned_input_number)

Also, I find it a bit odd that your validateNumber function returns a number.另外,我觉得你的 validateNumber 函数返回一个数字有点奇怪。 It might be better to return True or False (depending on if the number is valid or not).返回 True 或 False 可能会更好(取决于数字是否有效)。 Either that, or maybe 'validate' is the wrong name for the function.或者,或者“验证”是该函数的错误名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM