B

Module 6: Custom Functions

  • Coding basics for:

- reusability: can be used in multiple places in the program without having to rewrite them again

- readability: custom naming a group of code

-maintainability: easier to find and fix bugs when custom codes are isolated

- def: the keyword is used to define the custom function

ex.)

def writeHaiku():

   print("Python, the language")

   print("Of simplicity and power")

   print("A joy to program in")

Writing writeHaiku will assign the print demands to a variable. 

For instance:

  • When wanting to print the command again, you would type “writeHaiku()” as is and the code will print the 3 lines without having to retype the lines of so many print statements.


Parameters:

  • Parameters allows us to use a function with additional information provided for the function

  • For instance:

def sayHello (strName):

   print("Hello, " + strName)

sayHello("Bill")

  • def: to start the custom function that tells the program

  • sayHello is the variable name we create to reuse the code in other parts of the program

  • (strName): is the string that is used to create the string method to let the program know that we will add a replacement to the string. Parameters are only accessible from the inside of the parentheses, in this case (strName). Without this, the program won’t do anything.

  • print(“Hello,” + strName) - this is to print the complex string into the console.

  • We then assign an argument that is known as “Bill” which is a string name that can be used in a data for the parameter of the function. 

  • Concatenated: adding two or more strings together.

  • For instance:

  • # Define the addNumbers function

  • def addNumbers(intNum1, intNum2):

  •    # Create a variable intAnswer, and set it to the value of intNum1 plus intNum2

  •    intAnswer = intNum1 + intNum2

  •    # Use an f-string to print out the values of the variables in a sentence.

  •    print(f"The sum of {intNum1} and {intNum2} is {intAnswer}.")

  • # Call the function, using 5 and 7 as the arguments.

  • addNumbers(5, 7)

  • Console prints: The sum of 5 and 7 is 12.

  • Above code takes two parameters (intNum1) and (intNum2). 

  • The argument is the 5 and 7 in the parentheses from addNumbers

The Return Keyword:

Functions that not only do something, but save or return something.

Nothing will happen to the console when dealing with return systems.

# Define a function that says "Hi Bill!"

def sayHiBill():

   # Create a string for the message

   strHiBill = "Hi Bill!"

   # Send the message back to Python

   return strHiBill

sayHiBill()

The sayHiBill() function returns the message

# Set strMessage to the value of what is returned by the sayHiBill() function.

strMessage = sayHiBill()

# Print out the value of strMessage

print(strMessage)

The above code prints the message to the console. Or we could also do:

print(sayHiBill())

The above code will do the exact same thing but with less coding.

If there are no arguments, then there is no need to apply anything inside the parentheses


Do something and return something:

Functions not only do something or return something, but can do both.

For instance: with two parameters provided:

# Define a custom function called addNumbers, with two parameters.

def addNumbers(intNum1, intNum2):

   # DO something - Print a message that we are adding the numbers

   print(f"Now adding {intNum1} and {intNum2}...")

   # RETURN something - Send back the sum of the two numbers given.

   return intNum1 + intNum2


# Call the function addNumbers with 3 and 4 as the arguments.

intResult = addNumbers(3, 4)

# Use an f string to print out the result in a nice sentence.

print(f"The answer is {intResult}.")

Console:

Now adding 3 and 4...

The answer is 7.


Optional Parameters:

We can make parameters optional: meaning we can use a parameter inside a function while having to apply no argument. 

For instance:

# Define a function called sayHi, with one optional parameter.

def sayHi(strName="Bill"):

   # Print a greeting using an f-string to insert the value of the parameter.

   print(f"Hello, {strName}!")


# Call the function with no argument.

sayHi()

# Call the function again, but with "George" as the argument.

sayHi("George")

Console:

Hello, Bill!

Hello, George!

We can use more than one optional parameter:

# Define the function sayIntro with optional parameters strName and intAge

def sayIntro(strName = "Bill", intAge = 47):

   # Print a sentence, inserting the values of the parameters using an f-string.

   print(f"My name is {strName}, and I am {intAge} years old.")


# Call the function with no arguments

sayIntro()

# Call the function with two arguments.

sayIntro("George", 25)

# Call the function with one argument, unnamed.

sayIntro("Sam")

# Call the function using a named argument to specify the intAge parameter.

sayIntro(intAge=25)


Console will type:

My name is Bill, and I am 47 years old.

My name is George, and I am 25 years old.

My name is Sam, and I am 47 years old.

My name is Bill, and I am 25 years old.

Defining a function:

def functionName (parameters):

code block in function

And Calling a function:

functionName (arguments)