PYTHON TUTORIALS

Python Tutorials: Functions

[Enter image here]

Programming is all about automating repetitive tasks. What better way to do this than to encapsulate multiple lines of code into a single line of code. Functions allow you to contain multiple lines of code to execute a repeatable action. This tutorial will cover the following learning objectives:

  • How to Define Functions
  • Difference Between Args and Kwargs

How to Define Functions




Summary

  • A Function is a block of reusable code. To invoke, or call a function, place a pair of parantheses ("()") after the function name. Example:
    def hello_message():
       print("Hello, World!")

    hello_message()
    OUTPUT: "Hello, World"!
  • Functions allow Arguments which allow users to input custom data to make the function fit their needs. Example:
    def hello_message(name):
       print(f'Hello, {name}!')

    hello_message('Greg')
    OUTPUT: "Hello, Greg!"
  • The Return statement is used to end a function and send a result back to the caller. Example:
    def create_username(first_name, last_name, age):
       username = f'{first_name}{last_name}{age}'
       return username

    create_username('Thomas', 'Smith', 23)
    OUTPUT: "ThomasSmith23"
  • NOTE: When placing a float in an f-string, it's smart to specify the number of decimal places the value will display. The example below shows how to display only two decimal places:
    print(f"You owe ${amount:.2f}")
       print(character)
  • NOTE: The difference between Arguments and Parameters is very thin. Arguments are the dynamic data storage units created when the function is defined, whereas Parameters are what the user enters to change the function's output.

Exercise

Congratulations! You just completed the Functions Tutorial! To help test your knowledge, let's practice creating some Functions.
**It's highly recommended that you complete the exercise outlined in the previous tutorial before beginning this exercise.**

Instructions:

  1. Open your IDE (e.g., VS Code, PyCharm, Spyder).
  2. Create a New Python File. Name it "functions.py"
  3. In the Newly Created Python File, complete the following tasks:
    1. Define a function named "triple_list_elements" that iterates over each element in a given list of numbers and exponentiates each element to the power of three. Add an Argument that allows the user to specify the list. Test the function with a customized list.
    2. Define a function named "get_username" that gets a user's input from a specified prompt. Add a Return statement that returns the username.
    3. Define a function that adds three numbers together and returns the output as another variable, printed in the Console.
  4. Exercise Completed! Click here to view the answers.
  5. Have any issues with the above exercise? Post your question on Discord!