Bootstrap FreeKB - Python (Scripting) - Pass values into a function
Python (Scripting) - Pass values into a function

Updated:   |  Python (Scripting) articles

If you are not familiar with functions, refer to Getting Started with functions in Python.

AVOID TROUBLE

A function must be defined before the function is called in the script. For example, let's say you call the "foo" function before the foo function is defined.

#!/usr/bin/python
return_greeting("Hello World")

def return_greeting(greeting):
  print(greeting)

 

This will return an error that looks something like this because a function must be defined before the function is called.

Traceback (most recent call last):
  File "/home/john.doe/testing.py", line 3, in <module>
    Hello("World")
NameError: name 'Hello' is not defined

 

In this example, values "Hello" and then "World" are passed into the return_greeting function. The values passed into the return_greeting function are placed in the "greeting" variable.

#!/usr/bin/python

def return_greeting(greeting):
  print(greeting)

return_greeting("Hello")
return_greeting("World")

 

Here is how you would pass two (or more) values into a function.

#!/usr/bin/python

def return_greeting(one,two):
  print(one)
  print(two)

return_greeting("Hello", "World")

 

Let's say you do something like this, where the return_greeting function expects one argument but no arguments were passed in.

#!/usr/bin/python3
def return_greeting(greeting):
  print(greeting)

return_greeting(

 

This will cause the following Traceback.

Traceback (most recent call last):
  File "testing.py", line 5, in <module>
    return_greeting()
TypeError: return_greeting() missing 1 required positional argument: 'greeting'

 

Or like this, passing in two or more arguments.

def return_greeting(greeting):
  print(greeting)

return_greeting("Hello", "World")

 

This will cause the following Traceback.

Traceback (most recent call last):
  File "testing.py", line 5, in <module>
    return_greeting("Hello", "World")
TypeError: return_greeting() takes 1 positional argument but 2 were given

 

*args can be used to pass in optional values which can be very useful in preventing exception NameError: global name 'my_variable' is not defined from being raised.

#!/usr/bin/python

def return_greeting(*args):
  if args:
    for argument in args:
      print(argument)

return_greeting("Hello", "World")

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 3d3f2e in the box below so that we can be sure you are a human.