How do I write a function and a return?

Question

How do I write a function and a return?

Solution

The basic syntax of a function can be seen below:

def function_name(optional_parameters):
  # Code MUST be indented 2 spaces to be inside of the function
  return value_to_be_returned

If you were to replace the generic names in the example above, you’d have a working function! There are some key things to notice here:
def - this word must be there, but only when you’re defining the function, there’s no need to write it when you call a function.
function_name - this is where you write the name of your function.
(optional_parameters) - here you write parameter names that you can give values when you use your function by passing arguments.
: - don’t forget the colon at the end of this line!
Inside the function, your code needs to be indented with 2 spaces to be considered part of the function’s code. Otherwise your code will be outside of the function!
return - anything after this word on this line will be returned and the function will exit immediately. Nothing runs in a function after a return is executed!
value_to_be_returned - replace this with whatever you intend for your function to return

Practice and Extra Study

>>> def my_func():
	pass

>>> print (my_func())
None
>>> 
>>> def my_func():
	return

>>> print (my_func())
None
>>> 
>>> def my_func():
	print ()

	
>>> print (my_func())

None
>>> 

Garner some evidence from this without the verbose lecture that could ensue.

None describes the return value of all the above functions since they all have none.

Notice that print () did consume a line, but it, too has no return value.

>>> def my_func():
	return print ()

>>> print (my_func())

None
>>> 

Bottom line, None is a very useful indicator to incorporate into our logic, with provisos. We still need to trap it on call returns.

>>> print ("Whoo hoo!" if my_func() else "Darn!")

Darn!
>>> 

Beauty of logic is negation…

>>> print ("Whoo hoo!" if not my_func() else "Darn!")

Whoo hoo!
>>> 
1 Like