Introduction to Functions
Introduction to Functions
Functions Fundamentals
Introduction
A function is a section of code that performs an action. You create a function by writing code in a Python module (a simple text-based document that contains code). The fundamental formula to create a function is:
def function-name(...): . . .
To create a function, start with the def keyword.
Practical Learning: Starting a Project
loan_amount = 4750 interest_rate = 14.50 # % periods = 42 # Number of months print("Loan Amount:", loan_amount) print("Interest Rate:", interest_rate, "%") print("Periods:", periods) print("==================================")
The Name of a Function
When creating a function, the def keyword is followed by a name. The name follows the same options you would apply to the name of a variable.
The Parentheses of a Function
The name of a function is followed by parentheses. The parentheses of a function offer many options. By default, the parentheses are empty. Most of the time, you will write the parentheses on the same line as the name of the function.
The parentheses of a function are followed by a colon (:).
The Body of a Function
The body of a function follows the line after the colon. You will write the code associated with the function starting on the line after the closing of the parentheses and the colon.
Indentation
As seen with conditional statements, indentation consists of pushing a line of code to the right. That indentation is done with regards to the previous line of code. As seen with conditional statements, the code of a function must be indented, usually four characters to the right. This can be illustrated as follows:
some-code continuation
In this case, all the lines of code that belong to the same group are indented at the same level:
some-code line-1 line-2 line-n
In the same way, any line of code that belongs to another dependent line of code must be indented. Here are illustrations:
code-level-1 dependent-1-level-1 dependent-2-level-1 code-level-1 dependent-1-level-1 subdependent-1-level-1 subdependent-2-level-1 dependent-2-level-1 code-level-1
In some computer languages (like C-based languages (C#, Java, C++, JavaScript)), indentation of the body of a function (and of a conditional statement) is only used to make code easy to read (which is also the case for languages like Visual Basic, TypeScript, etc). In some other languages like F#, indentation is an integral part of the code. This means that, in those languages, indentation is required. In the same way, in Python, code indentation is required.
When defining a function, you can write each parenthesis on its own line. The opening parenthesis can be written on the first line. If the closing parenthesis is written on the next line, it must be indented. This would be done as follows:
def calculate( ): . . .
If you want, you can write the opening parenthesis on the line that follows the name of the function. In that case, the parenthesis must be indented. Here is an example:
def calculate (): . . .
Or like this:
def calculate ( ): . . .
Defining or Implementing a Function
When you create a function and write its code, you are said to define or implement the function.
Practical Learning: Defining a Function
def process_loan():
loan_amount = 4750
interest_rate = 14.50 # %
periods = 42 # Number of months
print("Loan Amount:", loan_amount)
print("Interest Rate:", interest_rate, "%")
print("Periods:", periods)
print("==================================")
A typical application uses many functions. As a result, you can create as many functions as you need. If you create functions in a document, the compiler will access them in the order they are called, which is usually different from the order the functions were created.
Calling a Function
After creating/defining/implementing a function, you can use it. Using a function is referred to as calling the function. To do this, in the section of code where you need the result of the function, type its name of the function followed by parentheses. Normally, most functions are called from outside their body (the exception is a category of functions named recursive functions: a recursive function is a function that calls itself).
Practical Learning: Calling a Function
def process_loan():
loan_amount = 4750
interest_rate = 14.50 # %
periods = 42 # Number of months
print("Loan Amount:", loan_amount)
print("Interest Rate:", interest_rate, "%")
print("Periods:", periods)
process_loan()
print("==================================")
Loan Amount: 4750 Interest Rate: 14.5 Periods: 42 ================================== Press any key to continue . . .
The Data Type of a Local Variable
If you declare a (some) variable(s) in the body of a function, if you want, you can specify its (their) data type(s).
Practical Learning: Setting Data Types
def process_loan(): loan_amount : float = 18685 interest_rate : float = 9.95 # % periods : int = 60 # Number of months print("Loan Amount:", loan_amount) print("Interest Rate:", interest_rate, "%") print("Periods:", periods) process_loan() print("==================================")
Loan Amount: 18685 Interest Rate: 9.95 % Periods: 60 ================================== Press any key to continue . . .
def process_loan(): print("Watts' A Loan") print("============================================") print("Enter the information to set up the loan") loan_amount = float(input("Loan Amount: ")) interest_rate : float = float(input("Interest Rate: ")) periods : int = int(input("Number of months: ")) iRate : float = interest_rate / 100.00 years : float = periods / 12 interest_amount : float = loan_amount * iRate * years future_value : float = loan_amount + interest_amount print("============================================") print("\tWatts' A Loan") print('--------------------------------------------') print(f"Loan Amount: {loan_amount}") print(f"Interest Rate: {interest_rate:.2f}%") print(f"Periods: {periods} Months") print('-------------------------------------------') print(f"Interest Amount: {interest_amount:.2f}") print(f"Future Value: {future_value:.2f}") process_loan() print("===========================================")
Watts' A Loan ============================================ Enter the information to set up the loan Loan Amount: 1850 Interest Rate: 16.85 Number of months: 32 ============================================ Watts' A Loan -------------------------------------------- Loan Amount: 1850.0 Interest Rate: 16.85% Periods: 32 Months ------------------------------------------- Interest Amount: 831.27 Future Value: 2681.27 =========================================== Press any key to continue . . .
A Function with a Parameter
Introduction
As stated in our introduction, a function is a section of code that performs a job. In many cases, a function can use only its local values. In some cases, if you want a function to perform a job based a certain value that doesn't depend on the function itself, you may have to provide that value to the function. To make this possible, when creating the function, type a name for the value in the parentheses of the function. Here is an example:
def display(value):
# . . .
A Parameter
The name you write in the parentheses of a function, when defining the function, is called a parameter. After putting a name in the parentheses of a function, in the body of the function, you can use the parameter anyway you like. For example, you can display the value of that parameter by writing in the parentheses of print(). Here is an example:
def send_message(msg):
print(msg)
In the same way, you can involve the parameter in an expression.
Calling a Parameterized Function
When you call a function that has a parameter, type the name of the function and its parentheses. In the parentheses, type a value for the parameter. Here is an example:
def send_message(msg): print(msg) send_message("Please remember to submit your time sheet."))
This would produce:
Please remember to submit your time sheet. Press any key to continue . . .
Practical Learning: Creating a Function with Parameter
def process_loan(): print("Watts' A Loan") print("============================================") print("Enter the informaiton to set up the loan") loan_amount = float(input("Loan Amount: ")) interest_rate : float = float(input("Interest Rate: ")) periods : int = int(input("Number of months: ")) iRate : float = interest_rate / 100.00 years : float = periods / 12 interest_amount : float = loan_amount * iRate * years future_value : float = loan_amount + interest_amount print("============================================") print("\tWatts' A Loan") print('--------------------------------------------') def showPrincipal(a): print(f"Loan Amount: {a}") def showInterestRate(b): print(f"Interest Rate: {b:.2f}%") def showPeriods(c): print(f"Periods: {c} Months") def showAmount(d): print(f"Interest Amount: {d:.2f}") def showFutureValue(e): print(f"Future Value: {e:.2f}") process_loan() print("===========================================")
An Argument
A value you provide in the parentheses of a function is called an argument. When you call a function and provide a value in its parentheses, you are said to pass an argument to the function.
Practical Learning: Passing an Argument to a Function
def process_loan(): print("Watts' A Loan") print("============================================") print("Enter the informaiton to set up the loan") loan_amount = float(input("Loan Amount: ")) interest_rate : float = float(input("Interest Rate: ")) periods : int = int(input("Number of months: ")) iRate : float = interest_rate / 100.00 years : float = periods / 12 interest_amount : float = loan_amount * iRate * years future_value : float = loan_amount + interest_amount print("============================================") print("\tWatts' A Loan") print('--------------------------------------------') showPrincipal(loan_amount) showInterestRate(interest_rate) showPeriods(periods) print('-------------------------------------------') showAmount(interest_amount) showFutureValue(future_value) def showPrincipal(a): print(f"Loan Amount: {a}") def showInterestRate(b): print(f"Interest Rate: {b:.2f}%") def showPeriods(c): print(f"Periods: {c} Months") def showAmount(d): print(f"Interest Amount: {d:.2f}") def showFutureValue(e): print(f"Future Value: {e:.2f}") process_loan() print("===========================================")
Watts' A Loan ============================================ Enter the informaiton to set up the loan Loan Amount: 4750 Interest Rate: 18.725 Number of months: 36 ============================================ Watts' A Loan -------------------------------------------- Loan Amount: 4750.0 Interest Rate: 18.73% Periods: 36 Months ------------------------------------------- Interest Amount: 2668.31 Future Value: 7418.31 =========================================== Press any key to continue . . .
The Data Type of a Parameter
Because Python is an inferred language, you don't have to specify the data type of a parameter. Still, if you want to assist the compiler with the type of a parameter, in the parentheses of the function, after the name of a parameter, you can type a colon and the data type. Here is an example:
def show_detail(cat : str):
print("Loan Category:")
print(cat)
def evaluate():
loan_amount : float = 4750
interest_rate : float = 14.50 # %
periods : int = 42 # Number of months
print("Loan Amount:")
print(loan_amount)
print("Interest Rate:")
print(interest_rate)
print("Periods:")
print(periods)
show_detail("Personal Loan")
print('----------------------------------')
evaluate()
print("==================================")
Introduction to Functions with many Parameters
Introduction
Just like a function can use one parameter, a function can use more than one parameter. When creating a function, to specify its parameters, in its parentheses, write the name of each parameter and separate them with commas. Here is an example:
def add(a, b):
. . .
In the body of the function, you can ignore all parameters and not use them, you can use one of the parameters and ignore the other parameter(s), or you can use all parameters. Here is an example:
def describe(name, price): print("Item Name: ") printname) print("Marked Price: ") print(price)
Other than that, in the body of the function, you can involve a parameter in any appropriate operation you want.
Practical Learning: Creating a Function With Parameters
def present(a, b, c, d, e): print("============================================") print("\tWatts' A Loan") print('--------------------------------------------') print(f"Loan Amount: {a}") print(f"Interest Rate: {b:.2f}%") print(f"Periods: {c} Months") print('-------------------------------------------') print(f"Interest Amount: {d:.2f}") print(f"Future Value: {e:.2f}") def process_loan(): print("Watts' A Loan") print("============================================") print("Enter the informaiton to set up the loan") loan_amount = float(input("Loan Amount: ")) interest_rate : float = float(input("Interest Rate: ")) periods : int = int(input("Number of months: ")) iRate : float = interest_rate / 100.00 years : float = periods / 12 interest_amount : float = loan_amount * iRate * years future_value : float = loan_amount + interest_amount process_loan() print("===========================================")
Calling a Function of many Parameters
After defining a function that uses more than one parameter, you can use it. When calling such a function, write its name and parentheses. In the parentheses, type a value for each parameter, exactly in the order the parameters appear in the function.
Practical Learning: Calling a Function of many Parameters
def present(a, b, c, d, e):
print("============================================")
print("\tWatts' A Loan")
print('--------------------------------------------')
print(f"Loan Amount: {a}")
print(f"Interest Rate: {b:.2f}%")
print(f"Periods: {c} Months")
print('-------------------------------------------')
print(f"Interest Amount: {d:.2f}")
print(f"Future Value: {e:.2f}")
def process_loan():
print("Watts' A Loan")
print("============================================")
print("Enter the informaiton to set up the loan")
loan_amount = float(input("Loan Amount: "))
interest_rate : float = float(input("Interest Rate: "))
periods : int = int(input("Number of months: "))
iRate : float = interest_rate / 100.00
years : float = periods / 12
interest_amount : float = loan_amount * iRate * years
future_value : float = loan_amount + interest_amount
present(loan_amount, interest_rate, periods, interest_amount, future_value)
process_loan()
print("===========================================")
Watts' A Loan ============================================ Enter the informaiton to set up the loan Loan Amount: 7450 Interest Rate: 14.645 Number of months: 38 ============================================ Watts' A Loan -------------------------------------------- Loan Amount: 7450.0 Interest Rate: 14.64% Periods: 38 Months ------------------------------------------- Interest Amount: 3455.00 Future Value: 10905.00 =========================================== Press any key to continue . . .
|
|||
Previous | Copyright © 2021-2022, FunctionX | Thursday 30 December 2021 | Next |
|