How to pass in a variable to a function under a condition

How to pass in a variable to a function under a condition

Six1Seven1
Advocate Advocate
509 Views
2 Replies
Message 1 of 3

How to pass in a variable to a function under a condition

Six1Seven1
Advocate
Advocate

Hi,

 

Sorry for all the posts. I have run into a problem. This stems back to my novice programming experience... My question is, how do I pass in an argument to a function only sometimes, only when a condition is true. Here is an example...

 

#call the function----------------------------

 

if checkbox == True:

    Function1(x, y, z)

else:

    Function1(x,y)

 

 

#define the function-----------------------

 

def Function1(x,y,z)       <----- Problem! variable z is only present when checkbox is TRUE.

 

 

Thus, i get an error. How do i define the function to only pass in the variable 'Z' when the checkbox is true? Sorry, I am still inexperienced in programming.

 

 

Thanks!

0 Likes
Accepted solutions (1)
510 Views
2 Replies
Replies (2)
Message 2 of 3

ekinsb
Alumni
Alumni
Accepted solution

Python supports optional arguments in a function.  For your function

 

def Function1(x, y, z):

 

You can make the last argument optional by defining a default value for it.  If you don't provide a value when calling the function the default value will be used.  The first example below will set z to zero.

 

def Function1(x, y, z=0):

 

If you need to know if the value was assigned by the caller or is the default you could use something else because in the example above, zero would be a valid value to use.  The example below uses None and then you could check for that in the function to see if a value was provided or not.

 

def Function1(x, y, z=None):

 

In both cases the function would be called using:

 

Function1(23, 3.6)

 

or

 

Function1(21, 34.6, 1.2)

 

 


Brian Ekins
Inventor and Fusion 360 API Expert
Mod the Machine blog
0 Likes
Message 3 of 3

Six1Seven1
Advocate
Advocate

Brian, that worked great.

 

Thank you very much

0 Likes