Search code examples
pythonfunctionvariablesparameters

How can I use existing variables and their values as parameters for a function (Python)?


I believe what I am asking is pretty simple, however none of my searches have turned up useful information.

So, all I want is to be able to access a preexisting variable in a program and use its value as a parameter of one of my own functions.

print("Please enter a number")
number = int(input())

def addTwo(number):
    newNumber = number + 2
    print("Your number plus two is ", str(newNumber))

So if you entered the number 4:

Please enter a number
>>> 4
Your number plus two is 6

That's all I need and hopefully it is simple! Thanks!


Solution

  • As @BrenBarn suggested

    print("Please enter a number")
    number = int(input())
    
    def addTwo(number):
        newNumber = number + 2
        print("Your number plus two is ", str(newNumber))
    
    addTwo(number)
    

    You simply pass parameters to your function which takes exactly one argument number.