Introduction to Built-In Functions
Introduction to Built-In Functions
Fundamentals of Built-In Functions
Overview
To assist you in creating applications, a computer language can come with some functions ready to be used so that you don't have to create your own functions that perform (a) certain operation(s). A function that ships with a computer language is referred to as a built-in function. Python comes with many built-in functions. Those functions (or most of them) can be used immediately in your code. Some of the functions are:
abs | delattr | hash | memoryview | set |
all | dict | help | min | setattr |
any | dir | hex | next | slice |
ascii | divmod | id | object | sorted |
bin | enumerate | input | oct | staticmethod |
bool | eval | int | open | str |
breakpoint | exec | isinstance | ord | sum |
bytearray | filter | issubclass | pow | super |
bytes | float | iter | tuple | |
callable | len | property | type | |
chr | frozenset | list | range | vars |
classmethod | getattr | locals | repr | zip |
compile | globals | map | reversed | __import__ |
complex | hasattr | max | round |
Practical Learning: Introducing Built-In Functions
print("Watts' A Loan") print('=============') print('Enter the information about the loan applicant') fname = "" lname = "" print("==================================================") print("Loan Applicant") print("----------------------") print("First Name:", fname) print("Last Name:", lname) print("==================================================")
Watts' A Loan ============= Enter the information about the loan applicant ================================================== Loan Applicant ---------------------- First Name: Last Name: ================================================== Press any key to continue . . .
Requesting User Input
We have already been introduced to a way to request a value from a user. As a reminder, to let you request a value in your application, the Python language provides a function named input. There are various ways to use the input function. The simplest version is to call it with empty parentheses: input(). To get the value that the user provides, you can assign input() to a variable. The value provided by input() is a string. Here is an example:
print("First Name:")
first_name = input()
As an alternative, you can pass a message to the parentheses of input(). That message will display to tell the user what to do at the prompt.
Introduction to Strings Operations
Converting a Value to a String
Most of the time, values are given to you as strings, in which case you can directly use them as such. In some cases, you are dealing with other types of values, including numbers. Some operations require that you convert a value to a string. To support this, the Python language provides a function named str. To convert a value to a string, type str(). In the parentheses, type the value to be converted.
Adding Strings
You can combine one or more strings to get a new string that includes the other strings. This operation can be performed with the + operator. Here is an example:
print("Watts' A Loan")
print('=============')
print('Enter the information about the loan applicant')
fname = input("First Name: ")
lname = input("Last Name: ")
name_display = "Loan Applicant: " + fname + " " + lname
print("==================================================")
print(name_display)
print("==================================================")
In the same way, to display strings in the parentheses of print(), use the + operator between them. Here is an example:
print("Watts' A Loan")
print('=============')
print('Enter the information about the loan applicant')
fname = input("First Name: ")
lname = input("Last Name: ")
print("==================================================")
print("Loan Applicant: " + fname + " " + lname)
print("==================================================")
If a value you are trying to add to a string is not a string, you can pass it to str() to convert it to a string.
Practical Learning: Adding Strings
print("Watts' A Loan") print("==================================================") print('Enter the information about the loan applicant') fname = input("First Name: ") lname = input("Last Name: ") print('--------------------------------------------------') print("Enter the values of the loan") strCurrentValue = input("Current Value: ") strRate = input("Interest Rate: ") strMonths = input("Number of Months: ") print("==================================================") print("Loan Applicant: " + fname + " " + lname) print("Loan Values") print("Principal:", strCurrentValue) print("Interest Rate: " + strRate + "%") print("Periods:", strMonths, "months") print("==================================================")
Watts' A Loan ================================================== Enter the information about the loan applicant First Name: Alexandra Last Name: Colson -------------------------------------------------- Enter the values of the loan Current Value: 2750 Interest Rate: 15.65 Number of Months: 32 ================================================== Loan Applicant: Alexandra Colson Loan Values Principal: 2750 Interest Rate: 15.65% Periods: 32 months ================================================== Press any key to continue . . .
Numeric Values
Converting a Value to an Integer
In the second lesson, we saw that, to let you convert a value to an integer, Python includes a function named int. To convert a value to a natural number, type int() and include the necessary value in the parentheses.
Practical Learning: Converting a Value to an Integer
print("Watts' A Loan")
print("==================================================")
print('Enter the information about the loan applicant')
fname = input("First Name: ")
lname = input("Last Name: ")
print('--------------------------------------------------')
print("Enter the values of the loan")
strCurrentValue = input("Current Value: ")
strRate = input("Interest Rate: ")
strMonths = input("Number of Months: ")
periods = int(strMonths)
print("==================================================")
print("Loan Applicant: " + fname + " " + lname)
print("Loan Values")
print("Principal:", strCurrentValue)
print("Interest Rate: " + strRate + "%")
print("Periods:", strMonths, "months")
print("==================================================")
Converting to a Floating-Point Number
To support floating-point conversion, Python provides a function named float, to which we were introduced in the second lesson. When calling this function, type float(), and pass the desired value to the parentheses.
Practical Learning: Converting to a Floating-Point Number
print("Watts' A Loan") print("==================================================") print('Enter the information about the loan applicant') fname = input("First Name: ") lname = input("Last Name: ") print('--------------------------------------------------') print("Enter the values of the loan") strCurrentValue = input("Current Value: ") strRate = input("Interest Rate: ") strMonths = input("Number of Months: ") iRate = float(strRate) periods = int(strMonths) principal = float(strCurrentValue) # Performing the necessary calculations interest_rate = iRate / 100.00 time = periods / 12 interest_amount = principal * interest_rate * time future_value = principal + interest_amount print("==================================================") print("Loan Applicant: " + fname + " " + lname) print('--------------------------------------------------') print("Loan Values") print("Principal:", principal) print("Interest Rate: " + str(iRate) + "%") print("Periods:", periods, "months") print('--------------------------------------------------') print("Interest Amount:", interest_amount) print("Future Value:", future_value) print("==================================================")
Watts' A Loan ================================================== Enter the information about the loan applicant First Name: Alexandra Last Name: Colson -------------------------------------------------- Enter the values of the loan Current Value: 6500 Interest Rate: 14 Number of Months: 24 ================================================== Loan Applicant: Alexandra Colson -------------------------------------------------- Loan Values Principal: 6500.0 Interest Rate: 14.0% Periods: 24 months -------------------------------------------------- Interest Amount: 1820.0000000000002 Future Value: 8320.0 ================================================== Press any key to continue . . .
The Absolute Value of a Number
A number can be positive or negative. Here are examples:
number1 = 952 number2 = -4697 number3 = 82.73 number4 = -208_297.516 print("Positive Number: ", number1) print("Negative Number: ", number2) print("Positive Number: ", number3) print("Negative Number: ", number4) print("=================================")
This would produce:
Positive Number: 952 Negative Number: -4697 Positive Number: 82.73 Negative Number: -208297.516 ================================= Press any key to continue . . .
Some operations require that a number be positive, in which case you may have to first convert the number or actually its variable. To assist you with this operation, Python provides a function named abs. When calling this function, pass a number to its parentheses. Here are examples:
number1 = 952 number2 = -4697 number3 = 82.73 number4 = -208_297.516 print("Positive Number:", number1) print("Negative Number:", number2, "converted:", abs(number2)) print("Positive Number:", number3) print("Negative Number:", number4, "converted:", abs(number4)) print("==================================================")
This would produce:
Positive Number: 952 Negative Number: -4697 converted: 4697 Positive Number: 82.73 Negative Number: -208297.516 converted: 208297.516 ================================================== Press any key to continue . . .
We know that a decimal number has two parts separated by a character named the decimal separator, as in xxx.xxxxxx. The value on the right side of the decimal separator is referred to as precision. When you ask the compiler to perform a calculation or to display a value, the compiler tries to show the value as large as possible. If you want to specify how much precision you want, you can call a function named round. It takes two arguments. The first argument is the entire value to be considered. It can be the name of a variable that holds the value. The second argument is the number of decimal values to use. Here are examples:
a = 6557.739 b = 93.849 c = a * b d = a / b e = round(c, 2) f = round(d, 2) g = round(c, 3) h = round(d, 3) print("Number: ", a) print("Number: ", b) print("---------------------------------") print("Multiplication:", c) print("Division: ", d) print("---------------------------------") print("Rounded (2): ", e) print("Rounded (2): ", f) print("Rounded (3): ", g) print("Rounded (3): ", h) print("==================================")
This would produce:
Number: 6557.739 Number: 93.849 --------------------------------- Multiplication: 615437.247411 Division: 69.87542754850877 --------------------------------- Rounded (2): 615437.25 Rounded (2): 69.88 Rounded (3): 615437.247 Rounded (3): 69.875 ================================== Press any key to continue . . .
Other Built-In Functions
Introduction
The Python language ships with many built-in functions. As we saw with functions such as print(), str(), int(), or float(), some built-in functions are immediately available when you start a project. There are many other functions in thousands of modules. Some of those modules are directly available to you. Some others you must acquire one way or another. Regardless, once you know the module that contains a function, in the top section of the document in which you are writing code, type import followed by the name of the module. Then, in your document, you can access any of the functions in that module.
In your document, if you type import followed by the name of the module, if the imported module contains many functions, all of them would be imported. In most cases, you need to use only some specific functions for your application. You need to know the name of each function you want to use. You will know this by experience or though proper documentation.
As seen in the previous lesson about importing variables, to indicate a built-in function you want to use, follow this formula:
from module-name import function-name[;]
If you want to access more than one function, type their names separated by commas:
from module-name import function-name-1, function-name-2, function-name-n[;]
In your code, you can then access any of the listed functions and use it as you see fit.
The Directory of the Current Project
The os module includes many functions you can use. To help you identify the folder in which your project is contained, the os module includes a function named cwd, which stands for current working directory.
Practical Learning: Ending the Lesson
|
|||
Previous | Copyright © 2024, FunctionX | Monday 06 September 2021 | Next |
|