You will expand your ability to work with Python. You’ll learn about pre-built and user-defined Python functions. You’ll also explore how modules help provide access to reusable code. Finally, you’ll make your code readable.
Learning Objectives
- Incorporate pre-built functions into code.
- Create new, user-defined Python functions.
- Explain how modules are used in Python.
- Identify best practices to improve code readability.
Introduction to functions
Video: Welcome to module 2
This episode builds on the previous videos about Python basics by focusing on writing effective scripts and improving efficiency. Key topics covered include:
- Functions: Reusable sets of instructions, eliminating repetitive code.
- Modules and Libraries: Predefined functions and data types, providing easier access and functionality.
- Code Readability: Strategies for clear and understandable code, benefiting you and others.
This episode marks the next step in your Python journey, equipping you with tools to write better code and unlock its full potential.
Additional Notes:
- The video mentioned starting with functions, modules/libraries, and then code readability.
- This summary focuses on the main takeaways, but more details can be extracted based on the specific content of the video.
Welcome back to our
Python journey! In the previous videos, we learned all about
the basics of Python. We started at the
very beginning by understanding how security
analysts use Python. We learned several
building blocks of Python. We went into detail
learning about data types, variables, and basic statements. Now, we’ll add to this and learn more about how to write
effective Python scripts. We’ll discover ways we can make our efforts more efficient. The upcoming videos are going
to start by introducing functions, which are very
important in Python. Functions allow us to
put together a set of instructions that we can use again and again in our code. Afterwards, we’re going to learn about Python modules
and libraries, which include collections of functions and data types
that we can use with Python. They help us gain access to functions without having
to create them ourselves. Lastly, we’re going
to talk about one of the most important
rules of programming, and that is code readability. We’ll learn all
about ways to make sure everyone can understand
and work with your code. I’m excited that you’ve decided to continue your
Python journey with me, so let’s start learning more!
Video: Introduction to functions
Here’s a summary of the key points about functions in Python:
What are functions?
- Reusable blocks of code that perform specific tasks.
- Help avoid repetitive code and make programs more efficient.
- Can be called multiple times from different parts of your program.
Types of functions:
- Built-in functions: Already available in Python (e.g.,
print()
). - User-defined functions: Created by programmers to meet specific needs.
Benefits of using functions:
- Efficiency: Automate repetitive tasks, saving time and effort.
- Reusability: Write code once, use it multiple times.
- Maintainability: Make changes in one place, updates apply everywhere.
- Readability: Break down complex programs into smaller, easier-to-understand chunks.
Key takeaways:
- Think of functions as “mini-programs” within your larger program.
- Use functions to improve code efficiency, readability, and maintainability.
- Python offers both built-in and user-defined functions for flexibility.
Here’s a tutorial on functions in Python:
Understanding Functions:
- What are they? Functions are reusable blocks of code that perform specific tasks. Think of them as mini-programs within your larger program.
- Why use them?
- Efficiency: Avoid repetitive code, making your programs more streamlined.
- Reusability: Write code once, use it multiple times throughout your program.
- Maintainability: Make changes in one place, and they’ll apply everywhere the function is used.
- Readability: Break down complex programs into smaller, more manageable chunks, improving code clarity.
Types of Functions:
- Built-in functions: These are already available in Python, like
print()
,input()
,len()
, and more. You can call them directly without any extra work. - User-defined functions: These are functions that you create yourself to meet specific needs in your programs.
Creating a User-Defined Function:
- Use the
def
keyword: Pythondef function_name(parameters): # Function body (code to be executed)
- Give it a descriptive name: Choose a name that clearly reflects what the function does.
- Define parameters (optional): These are variables that can receive input values when the function is called.
- Write the code within the function: This is the block of code that will be executed when the function is called.
- Use the
return
statement (optional): To send back a value from the function to the place where it was called.
Calling a Function:
Python
function_name(arguments)
- Replace
function_name
with the actual name of the function you want to call. - Provide any necessary arguments (values) for the function’s parameters.
Example:
Python
def greet(name):
print("Hello, " + name + "!")
greet("Alice") # Output: Hello, Alice!
greet("Bob") # Output: Hello, Bob!
Key Points:
- Functions can take input values (parameters) and produce output values (return statement).
- Indentation is crucial in Python to define the function’s body.
- Functions can call other functions, including themselves (recursion).
Practice and Experiment:
- Start by using built-in functions to get comfortable with the concept.
- Create simple user-defined functions to practice the syntax and concepts.
- Explore more complex functions with multiple parameters and return values.
- Use functions to break down your programs into smaller, more manageable pieces.
- Embrace the power of functions to write more efficient, organized, and reusable code in Python!
As the complexity of
our programs grow, it’s also likely that we’ll
reuse the same lines of code. Writing this code
multiple times would be time-consuming, but luckily we have a way to manage this. We can use functions. A function is a section of code that can be
reused in a program. We already learned one
function when we worked with print and used it to output
specified data to the screen. For example, we printed
“Hello Python.” There are many other functions. Sometimes, we need to
automate a task that might otherwise be repetitive
if we did it manually. Previously, we compared other key Python components
to elements of a kitchen. We compared data types
to categories of food. There are differences
in how we handle vegetables and
meat, and likewise, there are differences in how we handle different data types. We then discussed
how variables are like the containers you
put food in after a meal; what they hold can change. As far as functions, we can think about them
like a dishwasher. If you aren’t using
a dishwasher, you’ll spend a lot of time
washing each dish separately. But a dishwasher automates this and lets you wash
everything at once. Similarly, functions
improve efficiency. They perform
repetitive activities within a program and allow
it to work effectively. Functions are made to be
reused in our programs. They consist of small
instructions and can be called upon any number of times and from anywhere
in our programs. Another benefit to functions is that if we ever had to
make changes to them, we can make those changes
directly in the function, and there’ll be applied
everywhere we use them. This is much better than making the same changes in many different places
within a program. The print() function is an
example of a built-in function. Built-in functions
are functions that exist within Python and
can be called directly. They are available
to us by default. We can also create
our own functions. User-defined functions
are functions that programmers design for
their specific needs. Both types of functions are like mini-programs
within a larger program. They make working in Python much more effective and efficient. Let’s continue learning
more about them.
Video: Create a basic function
Here’s a summary of the key points about defining and calling functions in Python:
Key Steps:
- Define the function:
- Use the
def
keyword followed by the function name and parentheses. - Place a colon at the end of the function header.
- Indent the code within the function to indicate its body.
- Use the
- Call the function:
- Type the function name followed by parentheses.
- Provide any necessary arguments (values) within the parentheses if the function accepts them.
Example:
Python
# Define the function
def greet_employee():
print("Welcome back! You're logged in.")
# Call the function
greet_employee() # Output: Welcome back! You're logged in.
Important Reminders:
- Just defining a function doesn’t execute its code. You need to call it explicitly.
- Indentation is crucial in Python to define the function’s body.
- Functions can be called multiple times throughout your program.
Here’s a tutorial on defining and calling functions in Python:
Understanding Functions:
- Functions are reusable blocks of code that perform specific tasks.
- They help make your programs more organized, efficient, and easier to read.
Defining a Function:
- Use the
def
keyword: Pythondef function_name(parameters): # Function body (code to be executed)
- Choose a descriptive name: Reflect what the function does.
- Define parameters (optional): Variables to receive input values.
- Write the code within the function: Indent to define the body.
Calling a Function:
Python
function_name(arguments)
- Replace
function_name
with the actual function name. - Provide arguments (values) for the function’s parameters (if any).
Example:
Python
def greet(name): # Define a function with a parameter
print("Hello, " + name + "!")
greet("Alice") # Call the function with an argument
Key Points:
- Indentation matters: Python uses indentation to define the function’s body.
- Functions can be called multiple times: Use them throughout your program.
- Call functions before they’re defined: Python allows this for flexibility.
Additional Tips:
- Use clear and meaningful function names.
- Add comments within functions to explain their purpose and logic.
- Test your functions thoroughly to ensure they work as expected.
- Break down complex tasks into smaller, more manageable functions.
Practice defining and calling functions to master this fundamental Python concept!
Let’s start our exploration of user-defined functions
by creating and then running a
very simple function. The first thing we need to do is define our function. When we define a function, we basically tell
Python that it exists. The def keyword is
needed for this. def is placed before a function name to
define a function. Let’s create a function that greets employees
after they log in. First, we’ll comment on what we want to
do with this code. We want to define a function. Now, we’ll go to a new line and use the keyword def
to name our function. We’ll call it greet_employee. Let’s look at this syntax
a little more closely. After our keyword def and the function name, we
place parentheses. Later, we’ll explore adding information inside
the parentheses, but for this simple function, we don’t need to add anything. Also, just like we did with conditional and
iterative statements, we add a colon at the
end of this header. After the colon, we’ll indicate what
the function will do. In our case, we
want the function to output a message once
the employee logs in. So let’s continue
creating our function and tell Python to
print this string. This line is indented because
it’s part of this function. So what happens if
we run this code? Does it print our
message? Let’s try this. It doesn’t. That’s because you also have
to call your function. You may not realize it, but you already have
experience calling functions. Print is a built-in function that we’ve called many times. So to call greet_employee,
we’ll do something similar. Let’s go with a new line. We’ll add another comment because now our purpose
is to call our function. And then, we’ll call the
greet_employee function. We’ll run it again. This time it printed
our welcome message. Great work! We’ve now defined
and called a function. This was a simple function. We’re going to learn
something next that will add to the complexity
of the functions you write.
Reading: Python functions in cybersecurity
Reading
Previously, you explored how to define and call your own functions. In this reading, you’ll revisit what you learned about functions and examine how functions can improve efficiency in a cybersecurity setting.
Functions in cybersecurity
A function is a section of code that can be reused in a program. Functions are important in Python because they allow you to automate repetitive parts of your code. In cybersecurity, you will likely adopt some processes that you will often repeat.
When working with security logs, you will often encounter tasks that need to be repeated. For example, if you were responsible for finding malicious login activity based on failed login attempts, you might have to repeat the process for multiple logs.
To work around that, you could define a function that takes a log as its input and returns all potentially malicious logins. It would be easy to apply this function to different logs.
Defining a function
In Python, you’ll work with built-in functions and user-defined functions. Built-in functions are functions that exist within Python and can be called directly. The print() function is an example of a built-in function.
User-defined functions are functions that programmers design for their specific needs. To define a function, you need to include a function header and the body of your function.
Function header
The function header is what tells Python that you are starting to define a function. For example, if you want to define a function that displays an “investigate activity” message, you can include this function header:
def display_investigation_message():
The def keyword is placed before a function name to define a function. In this case, the name of that function is display_investigation_message.
The parentheses that follow the name of the function and the colon (:) at the end of the function header are also essential parts of the syntax.
Pro tip: When naming a function, give it a name that indicates what it does. This will make it easier to remember when calling it later.
Function body
The body of the function is an indented block of code after the function header that defines what the function does. The indentation is very important when writing a function because it separates the definition of a function from the rest of the code.
To add a body to your definition of the display_investigation_message() function, add an indented line with the print() function. Your function definition becomes the following:
def display_investigation_message():
print(“investigate activity”)
Calling a function
After defining a function, you can use it as many times as needed in your code. Using a function after defining it is referred to as calling a function. To call a function, write its name followed by parentheses. So, for the function you previously defined, you can use the following code to call it:
display_investigation_message()
Although you’ll use functions in more complex ways as you expand your understanding, the following code provides an introduction to how the display_investigation_message() function might be part of a larger section of code. You can run it and analyze its output:
def display_investigation_message():
print("investigate activity")
application_status = "potential concern"
email_status = "okay"
if application_status == "potential concern":
print("application_log:")
display_investigation_message()
if email_status == "potential concern":
print("email log:")
display_investigation_message()
application_log:
investigate activity
The display_investigation_message() function is used twice within the code. It will print “investigate activity” messages about two different logs when the specified conditions evaluate to True. In this example, only the first conditional statement evaluates to True, so the message prints once.
This code calls the function from within conditionals, but you might call a function from a variety of locations within the code.
Note: Calling a function inside of the body of its function definition can create an infinite loop. This happens when it is not combined with logic that stops the function call when certain conditions are met. For example, in the following function definition, after you first call func1(), it will continue to call itself and create an infinite loop:
def func1():
func1()
Key takeaways
Python’s functions are important when writing code. To define your own functions, you need the two essential components of the function header and the function body. After defining a function, you can call it when needed.
Lab: Activity: Define and call a function
Practice Quiz: Test your knowledge: Introduction to functions
In Python, what is a function?
A section of code that can be reused in a program
A Python function is a section of code that can be reused in a program.
Which of the following keywords is essential when defining a function?
def
The def keyword is essential when defining a function. It is placed before a function name to define it.
You want to define a function that performs a status check. Which of the following is a valid header for the function definition?
def status_check():
A valid header for the function definition is def status_check():. Headers should include the def keyword, the name of the function followed by parentheses, and a colon (:).
You are responsible for defining a function alert() that prints out the statement “Security issue detected.” Which of the following blocks of code represent the correct indentation for defining and then calling the function?
def alert():
print("Security issue detected.")
alert()
When defining and then calling a function alert() that prints out the statement “Security issue detected.”, the following block of code demonstrates correct indentation:
def alert():
print("Security issue detected.")
alert()
Work with functions
Video: Use parameters in functions
Here’s a summary of the video about parameters in Python functions:
Key Points:
- Parameters: Placeholders within a function definition that receive values when the function is called.
- Arguments: Actual values passed to a function when it’s called, filling the parameter placeholders.
- Example:
range()
function: Takesstart
andstop
parameters to generate a sequence of numbers. - Creating a function with parameters:
- Define the function with parameter names inside parentheses.
- Use the parameters within the function’s code to perform actions or calculations.
- Calling a function with arguments:
- Pass arguments to the function in the same order as the parameters.
- Multiple parameters:
- Separate parameters with commas in both the function definition and calls.
- Benefits of parameters:
- Make functions flexible and reusable by accepting different inputs.
- Customize function behavior based on specific needs.
Overall message: Understanding parameters is essential for writing versatile and adaptable Python functions.
Here’s a tutorial on parameters in Python functions, incorporating visual aids:
Understanding Parameters and Arguments:
- Parameters: Placeholders within a function definition that receive values when the function is called. Think of them as variables defined within the function’s scope.
- Arguments: The actual values you pass to a function when you call it. These values fill in the parameter placeholders.
Defining a Function with Parameters:
Syntax:
def function_name(parameter1, parameter2, ...):
# Function body using the parameters
Example:
def greet_user(name, age):
print("Hello, " + name + "! You are " + str(age) + " years old.")
Calling a Function with Arguments:
Specify arguments in the same order as parameters:
greet_user("Alice", 30) # Output: Hello, Alice! You are 30 years old.
Multiple Parameters:
Separate parameters with commas:
def calculate_area(length, width):
return length * width
area = calculate_area(5, 4) # Output: 20
Key Points:
- Parameters make functions reusable and adaptable by allowing them to take different inputs.
- Arguments customize function behavior for specific needs.
- The order of arguments matters when calling functions.
- Functions can have multiple parameters, separated by commas.
Example: Using Parameters for Calculations:
Python
def calculate_discount(price, discount_rate):
discount = price * discount_rate
discounted_price = price - discount
return discounted_price
final_price = calculate_discount(100, 0.2) # Output: 80.0
Benefits of Using Parameters:
- Flexibility: Functions can work with different data without code duplication.
- Modularity: Break down complex problems into smaller, manageable functions.
- Readability: Improve code clarity by encapsulating logic within functions.
Best Practices:
- Use descriptive parameter names to enhance code readability.
- Provide clear function documentation explaining parameter usage.
- Handle potential errors related to invalid argument types or values.
Experiment and Practice:
- Create your own functions with parameters to solidify your understanding.
- Explore different scenarios to see how parameters enhance code flexibility.
- Practice with real-world examples to appreciate their practical benefits.
The following block of code defines and calls a function. Which component of the code is an argument?
def display_username(username):
print("Username is", username)
display_username("bmoreno")
“bmoreno”
In this code block, the component that is an argument is “bmoreno”. Arguments are the data brought into a function when it is called.
Previously, we defined and
called our first function. It didn’t require any information
from outside the function, but other functions might. This means we need to talk about
using parameters in functions. In Python, a parameter is an object that
is included in a function definition for use in that function. Parameters are accepted into a function
through the parentheses after a function name. The function that we created in the last
video isn’t taking in any parameters. Now, let’s revisit another function
called range() that does use parameters. If you recall,
the range() function generates a sequence of numbers from a start point to
the value before the stop point. Therefore,range() does include
parameters for the start and stop indices that each
accept an integer value. For instance,
it could accept integers 3 and 7. This means the sequence it
generates will run from 3 to 6. In our previous example, we wrote a function that displayed
a welcome message when someone logged in. It would be even more welcoming if
we included the employee’s name with the message. Let’s define a function with a parameter
so we can greet employees by name! When we define our function, we’ll include the name of the parameter
that our function depends on. We place this parameter, the name
variable, inside the parentheses. The rest of the syntax stays the same. Now, let’s go to the next line and
indent so we can tell Python what
we want this function to do. We want it to print a message that welcomes
the employee using the name that’s passed into the function. Bringing this variable into our print
statement requires a few considerations. Like before, we start with
the welcome message we want to print. In this case, though, we’re not stopping our message after
we tell them they’re logged in. We want to continue and
add the employee’s name to the message. That’s why we’re placing
a comma after “You’re logged in” and then adding the name variable. Since this is a variable and
not a specific string, we don’t place it in quotation marks. Now that our function is set up, we’re ready to call it with the specific
argument that we want to pass in. In Python, an argument is the data brought
into a function when it is called. For example,
earlier, when we passed 3 and 7 into the range() function,
these were arguments. In our case, let’s imagine we want to
greet an employee named Charley Patel. We’ll call our greet_employee()
function with this argument. And when we run this, Charley Patel
gets a personalized welcome message! In this example, we only have one
parameter in our function. But we can have more. Let’s explore an example of this. Maybe instead of a single name parameter,
we have a parameter for first name and
a second parameter for last name. If so, we would need to
adjust the code like this. First, when we define the function, we include both parameters and
separate them with a comma. Then, when we call it, we also include
two arguments. This time we’re greeting someone with the first name of Kiara and
with the last name of Carter. These are also separated by a comma. Let’s run this and welcome Kiara Carter! As we just explored,
using more than one parameter just requires a few adjustments. Great work in this video! We learned a lot about working
with parameters in a function. This understanding is something you’ll
need as you continue to write Python scripts.
Video: Return statements
Here’s a summary of the video about return statements in Python functions:
Key Points:
- Return Statements: Used within functions to send information back to the code that called the function.
- Purpose: Facilitate communication between different parts of a program and make functions more versatile.
- Example:
calculate_fails()
Function:- Takes
total_attempts
andfailed_attempts
as parameters. - Calculates the percentage of failed attempts.
- Returns the calculated percentage using the
return
statement.
- Takes
- Assigning Returned Values: Store the returned value in a variable for further use.
- Using Returned Values:
- Use returned values in conditional statements to control program flow.
- Employ them in calculations or other operations within the program.
Key Takeaways:
- Return statements are essential for creating functions that produce output and share data with other parts of the program.
- Understanding return statements is crucial for building effective and adaptable Python programs.
Here’s a tutorial on return statements in Python functions, incorporating visual aids:
Understanding Return Statements:
- Purpose: Used within functions to send a value back to the code that called the function.
- Syntax:
return value_to_return
- Terminates Function Execution: Once a return statement is encountered, the function stops running and returns the specified value.
Example: Calculating Failed Login Percentage:
Python
def calculate_fails(total_attempts, failed_attempts):
fail_percentage = failed_attempts / total_attempts
return fail_percentage # Returns the calculated percentage
percentage = calculate_fails(4, 2) # Call the function and store the returned value
print(percentage) # Output: 0.5 (50%)
Key Points:
- Functions can return any data type (numbers, strings, lists, etc.).
- If no return statement is specified, the function returns
None
by default. - Multiple return statements can exist within a function, but only the first one executed will return a value.
Using Returned Values:
- Assigning to Variables: Store returned values in variables for further use.
- Directly Using in Code: Incorporate returned values into expressions, conditional statements, or other operations.
Example: Handling Account Lockout:
Python
percentage = calculate_fails(4, 2)
if percentage >= 0.5:
print("Account locked") # Use the returned value in a conditional statement
Benefits of Return Statements:
- Modular Code: Break down complex problems into smaller, reusable functions.
- Function Composition: Combine functions to create more complex operations.
- Clear Information Flow: Communicate results and outputs between different parts of your program.
Best Practices:
- Use clear and descriptive variable names for returned values.
- Document the expected return type in function comments or docstrings.
- Handle potential errors or invalid inputs gracefully within the function.
Experiment and Practice:
- Create functions with return statements to solidify your understanding.
- Explore different scenarios to see how return values enhance code flexibility and reusability.
- Practice with real-world examples to appreciate their practical benefits.
We previously learned how we can
pass arguments into a function. We can do more than pass
information into a function. We can also send information out of one! Return statements allow us to do this. A return statement is a Python statement
that executes inside a function and sends information back
to the function call. This ability to send information back
from a function is useful to a security analyst in various ways. As one example, an analyst might
have a function that checks whether someone is allowed to
access a particular file and will return a Boolean value of “True” or
“False” to the larger program. We’ll explore another example. Let’s create a function related
to analyzing login attempts. Based on the information it takes in,
this function will compute the percentage of failed attempts and
return this percentage. The program could use this
information in a variety of ways. For example, it might be used to determine
whether or not to lock an account. So let’s get started and learn how to
return information from a function. Just like before, we start by defining our
function. We’ll name it calculate fails() and we’ll set two parameters
related to login attempts: one for total_attempts and
one for failed_attempts. Next, we’ll tell Python what we
want this function to do. We want this function to store
the percentage of failed attempts in a variable called fail_percentage. We need to divide failed_attempts by
total_attempts to get this percentage. So far, this is similar to what
we’ve learned previously. But now, let’s learn how to return
the fail percentage. To do this,
we need to use the keyword return. Return is used to return
information from a function. In our case, we’ll return
the percentage we just calculated. So after the keyword return,
we’ll type fail_percentage. This is our variable that
contains this information. Now, we’re ready to call this function.
We’ll calculate the percentage for a user who has logged in 4 times
with 2 failed attempts. So, our arguments are 4 and 2. When we run this,
the function returns the percentage of failed attempts. It’s .5, or 50 percent, but in some Python environments,
this might not be printed to the screen. We cannot use the specific variable named
fail_percentage outside of the function. So, in order to use this information
in another part of the program, we would need to return the value from the
function and assign it to a new variable. Let’s check this out. This time, when the function is called, the value that’s returned is stored
in a variable called percentage. Then, we can use this
variable in additional code. For example, we can write a conditional
that checks if the percentage of failed attempts is greater than or
equal to 50 percent. When this condition is met, we can tell
Python to print an “Account locked” message. Let’s run this code. And this time, the percentage
isn’t returned to the screen. Instead, we get the “Account locked”
message. Coming up, we’ll discuss more functions,
but this time, we’ll go over a few that are ready for
use and built in to Python!
Reading: Functions and variables
Reading
Previously, you focused on working with multiple parameters and arguments in functions and returning information from functions. In this reading, you’ll review these concepts. You’ll also be introduced to a new concept: global and local variables.
Working with variables in functions
Working with variables in functions requires an understanding of both parameters and arguments. The terms parameters and arguments have distinct uses when referring to variables in a function. Additionally, if you want the function to return output, you should be familiar with return statements.
Parameters
A parameter is an object that is included in a function definition for use in that function. When you define a function, you create variables in the function header. They can then be used in the body of the function. In this context, these variables are called parameters. For example, consider the following function:
def remaining_login_attempts(maximum_attempts, total_attempts):
print(maximum_attempts – total_attempts)
This function takes in two variables, maximum_attempts and total_attempts and uses them to perform a calculation. In this example, maximum_attempts and total_attempts are parameters.
Arguments
In Python, an argument is the data brought into a function when it is called. When calling remaining_login_attempts in the following example, the integers 3 and 2 are considered arguments:
remaining_login_attempts(3, 2)
These integers pass into the function through the parameters that were identified when defining the function. In this case, those parameters would be maximum_attempts and total_attempts. 3 is in the first position, so it passes into maximum_attempts. Similarly, 2 is in the second position and passes into total_attempts.
Return statements
When defining functions in Python, you use return statements if you want the function to return output. The return keyword is used to return information from a function.
The return keyword appears in front of the information that you want to return. In the following example, it is before the calculation of how many login attempts remain:
def remaining_login_attempts(maximum_attempts, total_attempts):
return maximum_attempts – total_attempts
Note: The return keyword is not a function, so you should not place parentheses after it.
Return statements are useful when you want to store what a function returns inside of a variable to use elsewhere in the code. For example, you might use this variable for calculations or within conditional statements. In the following example, the information returned from the call to remaining_login_attempts is stored in a variable called remaining_attempts. Then, this variable is used in a conditional that prints a “Your account is locked” message when remaining_attempts is less than or equal to 0. You can run this code to explore its output:
def remaining_login_attempts(maximum_attempts, total_attempts):
return maximum_attempts - total_attempts
remaining_attempts = remaining_login_attempts(3, 3)
if remaining_attempts <= 0:
print("Your account is locked")
Your account is locked
In this example, the message prints because the calculation in the function results in 0.
Note: When Python encounters a return statement, it executes this statement and then exits the function. If there are lines of code that follow the return statement within the function, they will not be run. The previous example didn’t contain any lines of code after the return statement, but this might apply in other functions, such as one containing a conditional statement.
Global and local variables
To better understand how functions interact with variables, you should know the difference between global and local variables.
When defining and calling functions, you’re working with local variables, which are different from the variables you define outside the scope of a function.
Global variables
A global variable is a variable that is available through the entire program. Global variables are assigned outside of a function definition. Whenever that variable is called, whether inside or outside a function, it will return the value it is assigned.
For example, you might assign the following variable at the beginning of your code:
device_id = “7ad2130bd”
Throughout the rest of your code, you will be able to access and modify the device_id variable in conditionals, loops, functions, and other syntax.
Local variables
A local variable is a variable assigned within a function. These variables cannot be called or accessed outside of the body of a function. Local variables include parameters as well as other variables assigned within a function definition.
In the following function definition, total_string and name are local variables:
def greet_employee(name):
total_string = “Welcome” + name
return total_string
The variable total_string is a local variable because it’s assigned inside of the function. The parameter name is a local variable because it is also created when the function is defined.
Whenever you call a function, Python creates these variables temporarily while the function is running and deletes them from memory after the function stops running.
This means that if you call the greet_employee() function with an argument and then use the total_string variable outside of this function, you’ll get an error.
Best practices for global and local variables
When working with variables and functions, it is very important to make sure that you only use a certain variable name once, even if one is defined globally and the other is defined locally.
When using global variables inside functions, functions can access the values of a global variable. You can run the following example to explore this:
username = "elarson"
def identify_user():
print(username)
identify_user()
elarson
The code block returns “elarson” even though that name isn’t defined locally. The function accesses the global variable. If you wanted the identify_user() function to accommodate other usernames, you would have to reassign the global username variable outside of the function. This isn’t good practice. A better way to pass different values into a function is to use a parameter instead of a global variable.
There’s something else to consider too. If you reuse the name of a global variable within a function, it will create a new local variable with that name. In other words, there will be both a global variable with that name and a local variable with that name, and they’ll have different values. You can consider the following code block:
username = "elarson"
print("1:" + username)
def greet():
username = "bmoreno"
print("2:" + username)
greet()
print("3:" + username)
1:elarson
2:bmoreno
3:elarson
The first print statement occurs before the function, and Python returns the value of the global username variable, “elarson”. The second print statement is within the function, and it returns the value of the local username variable, which is “bmoreno”. But this doesn’t change the value of the global variable, and when username is printed a third time after the function call, it’s still “elarson”.
Due to this complexity, it’s best to avoid combining global and local variables within functions.
Key takeaways
Working with variables in functions requires understanding various concepts. A parameter is an object that is included in a function definition for use in that function, an argument is the data brought into a function when it is called, and the return keyword is used to return information from a function. Additionally, global variables are variables accessible throughout the program, and local variables are parameters and variables assigned within a function that aren’t usable outside of a function. It’s important to make sure your variables all have distinct names, even if one is a local variable and the other is a global variable.
Video: Explore built-in functions
Here’s a summary of the video about built-in functions in Python:
Key Points:
- Built-in Functions: Ready-to-use functions within Python, callable by name.
- Combining Functions: Nest functions by passing one’s output as another’s input.
- Understanding Inputs and Outputs:
- Know the expected data types and number of parameters for each function.
- Understand the data type of the returned value.
- Examples:
print()
: Outputs objects to the screen.type()
: Returns the data type of an object.max()
: Returns the largest value among inputs.sorted()
: Sorts the elements of a list.
Key Takeaways:
- Built-in functions offer efficient solutions for common tasks.
- Understanding their inputs, outputs, and interactions is crucial for effective use.
- Familiarity with various built-in functions expands Python programming capabilities.
Here’s a tutorial on built-in functions in Python, incorporating visual aids:
What are Built-in Functions?
- Predefined functions within Python that you can call directly, saving you time and effort in writing code.
- Offer efficient solutions for common programming tasks.
- Cover a wide range of functionalities, including input/output, data manipulation, conversions, and more.
Common Built-in Functions:
- print(): Outputs objects to the console.
- Example:
print("Hello, world!")
- Example:
- type(): Returns the data type of an object.
- Example:
print(type(5.2))
# Output: <class ‘float’>
- Example:
- max(): Returns the largest value among its arguments.
- Example:
largest = max(3, 9, 6)
# largest will be 9
- Example:
- min(): Returns the smallest value among its arguments.
- Example:
smallest = min(17, 4, 22)
# smallest will be 4
- Example:
- sorted(): Returns a sorted version of a list.
- Example:
sorted_numbers = sorted([5, 2, 8, 1])
# [1, 2, 5, 8]
- Example:
- len(): Returns the length of an object (number of items in a sequence).
- Example:
username_length = len("admin")
# 5
- Example:
- input(): Prompts the user for input and returns it as a string.
- Example:
name = input("Enter your name: ")
- Example:
- str(): Converts a value to a string.
- Example:
number_string = str(42)
# “42”
- Example:
- int(): Converts a value to an integer.
- Example:
age = int("35")
# 35
- Example:
- float(): Converts a value to a floating-point number.
- Example:
price = float("9.99")
# 9.99
- Example:
- abs(): Returns the absolute value of a number.
- Example:
distance = abs(-15)
# 15
- Example:
Combining Functions:
- Nest functions to create more complex operations.
- Pass the output of one function as an argument to another.
- Example:
print(type(sorted([5, "hello", 3.14])))
Key Points:
- Consult Python’s documentation for a comprehensive list of built-in functions and their usage.
- Understand the expected inputs and outputs of each function to use them correctly.
- Experiment with different functions to expand your programming capabilities.
- Use built-in functions to write more concise and efficient code.
Now that we know how to
create our own functions, let’s also explore a few of
Python’s built-in functions. As we discussed previously, built-in functions are
functions that exist within Python and can
be called directly. Our only job is to call them by their name! And we’ve already described a few
throughout the course; for example, Python’s
print() and type() functions. Let’s quickly review those
two built-in functions before learning about new ones! First, print() outputs a
specified object to the screen. And then, the type() function returns
the data type of its input. Previously, we’ve been using functions independently
from one another. For example, we asked
Python to print something, or we asked Python to return the
data type of something. As we begin to explore
built-in functions, we’ll often need to use
multiple functions together. We can do this by passing one function into
another as an argument. For example, in
this line of code, Python first returns the
data type of “Hello” as a string. Then, this returned value is
passed into the print() function. This means the data type of string will be printed
to the screen. print() and type() are not the only
functions you’ll see used together in this way. In all cases, the general
syntax is the same. The inner function is
processed first and then its returned value is passed
to the outer function. Let’s consider another aspect of working with
built-in functions. When working with functions, you have to understand what their expected inputs
and outputs are. Some functions only
expect specific data types and will return a type error
if you use the wrong one. Other functions need
a specific amount of parameters or return
a different data type. The print() function, for example can take in any data
type as its input. It can also take in any
number of parameters, even ones with
different data types. Let’s explore the input and
output of the print() function. We’ll enter three arguments. The first contains
string data. Then, a comma is used to separate this from
the second argument. This second argument
is an integer. Finally, after another comma, our third argument
is another string. Now, let’s run this code. Perfect! This printed
out just as expected! The type() function also
takes in all data types, but it only accepts
one parameter. Let’s explore this
input and output too. Our first line of code will first determine
the data type of the word “security” and then pass what it returns
into a print() function. And the second line of
code will do the same thing with
the value of 73.2. Now, let’s run this
and see what happens. Python first returns output that tells us that the word
“security” is string data. Next, it returns another
line of output that tells us that 73.2 is float data. Now, we know what to consider before using
a built-in function. We have to know exactly
how many parameters it requires and what data
types they can be. We also need to know
what kind of output it produces. Let’s learn a couple of new built-in functions
and think about this. We’ll start with max(). The max() function returns the largest numeric
input passed into it. It doesn’t have a
defined number of parameters that it accepts. Let’s explore the max() function. We’ll pass three arguments into max() in the
form of variables. So let’s first define
those variables. We’ll set the value of a to 3, b to 9, and c to 6. Then, we’ll pass
these variables into the max() function and print
them. Let’s run this. It tells us the highest
value among those is 9. Now, let’s study one more built-in function:
the sorted() function. The sorted() function sorts
the components of a list. This function can be very
useful in a security setting. When working with lists, we often have to sort them.
With lists of numbers, we sort them from smallest to largest or the
other way around. With lists of string data, we might need to sort
them alphabetically. Imagine you have a
list that contains usernames in your organization and you wanted to sort
them alphabetically. Let’s use Python’s sorted()
function for this. We’ll specify our list through a
variable named usernames. In this list, we’ll include all of the usernames
we want to sort. Now, we’ll use the
sorted() function to sort these names by passing the usernames variable into it. And then we’ll pass its output into the print statement so it can
be displayed on the screen. When we run it, everything
is now in order! These are just a few of the built-in functions
available for your use. As you work more in Python, you’ll become familiar with others that can help
you in your programs.
Rading: Work with built-in functions
Reading
Previously, you explored built-in functions in Python, including print(), type(), max(), and sorted(). Built-in functions are functions that exist within Python and can be called directly. In this reading, you’ll explore these further and also learn about the min() function. In addition, you’ll review how to pass the output of one function into another function.
print()
The print() function outputs a specified object to the screen. The print() function is one of the most commonly used functions in Python because it allows you to output any detail from your code.
To use the print() function, you pass the object you want to print as an argument to the function. The print() function takes in any number of arguments, separated by a comma, and prints all of them. For example, you can run the following code that prints a string, a variable, another string, and an integer together:
month = "September"
print("Investigate failed login attempts during", month, "if more than", 100)
Investigate failed login attempts during September if more than 100
type()
The type() function returns the data type of its argument. The type() function helps you keep track of the data types of variables to avoid errors throughout your code.
To use it, you pass the object as an argument, and it returns its data type. It only accepts one argument. For example, you could specify type(“security”) or type(7).
Passing one function into another
When working with functions, you often need to pass them through print() if you want to output the data type to the screen. This is the case when using a function like type(). Consider the following code:
print(type("This is a string"))
<class 'str'>
It displays str, which means that the argument passed to the type() function is a string. This happens because the type() function is processed first and its output is passed as an argument to the print() function.
max() and min()
The max() function returns the largest numeric input passed into it. The min() function returns the smallest numeric input passed into it.
The max() and min() functions accept arguments of either multiple numeric values or of an iterable like a list, and they return the largest or smallest value respectively.
In a cybersecurity context, you could use these functions to identify the longest or shortest session that a user logged in for. If a specific user logged in seven times during a week, and you stored their access times in minutes in a list, you can use the max() and min() functions to find and print their longest and shortest sessions:
time_list = [12, 2, 32, 19, 57, 22, 14]
print(min(time_list))
print(max(time_list))
2
57
sorted()
The sorted() function sorts the components of a list. The sorted() function also works on any iterable, like a string, and returns the sorted elements in a list. By default, it sorts them in ascending order. When given an iterable that contains numbers, it sorts them from smallest to largest; this includes iterables that contain numeric data as well as iterables that contain string data beginning with numbers. An iterable that contains strings that begin with alphabetic characters will be sorted alphabetically.
The sorted() function takes an iterable, like a list or a string, as an input. So, for example, you can use the following code to sort the list of login sessions from shortest to longest:
time_list = [12, 2, 32, 19, 57, 22, 14]
print(sorted(time_list))
[2, 12, 14, 19, 22, 32, 57]
This displays the sorted list.
The sorted() function does not change the iterable that it sorts. The following code illustrates this:
time_list = [12, 2, 32, 19, 57, 22, 14]
print(sorted(time_list))
print(time_list)
[2, 12, 14, 19, 22, 32, 57]
[12, 2, 32, 19, 57, 22, 14]
The first print() function displays the sorted list. However, the second print() function, which does not include the sorted() function, displays the list as assigned to time_list in the first line of code.
One more important detail about the sorted() function is that it cannot take lists or strings that have elements of more than one data type. For example, you can’t use the list [1, 2, “hello”].
Key takeaways
Built-in functions are powerful tools in Python that allow you to perform tasks with one simple command. The print() function prints its arguments to the screen, the type() function returns the data type of its argument, the min() and max() functions return the smallest and largest values of an iterable respectively, and sorted() organizes its argument.
Resources for more information
These were just a few of Python’s built-in functions. You can continue learning about others on your own:
- The Python Standard Library documentation: A list of Python’s built-in functions and information on how to use them
Lab: Activity: Create more functions
Practice Quiz: Test your knowledge: Arguments, parameters, and return statements
Fill in the blank: In the following code, the integers 5 and 12 are _____:
for i in range(5, 12):
print(i)
arguments
The integers 5 and 12 are arguments in the following code:
for i in range(5, 12):
print(i)
An argument is the data brought into a function when it is called. In this case, 5 and 12 are brought into the range() function when it is called.
What is the correct way to define the function addition() if it requires the two parameters num1 and num2?
def addition(num1, num2):
The correct way to define the function addition() if it requires the two parameters num1 and num2 is def addition(num1, num2):. If a function requires multiple parameters, you should place them in parentheses and separate them with commas when defining the function.
Which of the following lines of code has correct syntax for printing the data type of the string “elarson”?
print(type(“elarson”))
The code print(type(“elarson”)) has correct syntax for printing the data type of the string “elarson”. The inner function is processed first, and then its returned value is passed to the outer function. The argument “elarson” is first passed into the type() function. It returns its data type, and this is passed into the print() function.
Which function definition includes the correct syntax for returning the value of the result variable from the doubles() function?
def doubles(num):
result = num * 2
return result
The following block of code demonstrates the correct syntax for returning the value of the result variable from the doubles() function:
def doubles(num):
result = num * 2
return result
The return keyword is used to return information from a function. It is placed before the information that you want to return. In this case, that is the result variable.
Learn from the Python community
Video: Modules and libraries
Key points:
- Libraries: Collections of modules that provide pre-built code for various tasks.
- Modules: Python files containing functions, variables, classes, and other reusable code.
- Python Standard Library: A vast collection of commonly used modules included with Python.
- Examples of Standard Library modules:
re
: For pattern matching (useful for searching log files).csv
: For working with CSV files.glob
andos
: For interacting with the command line.time
anddatetime
: For handling timestamps.
- External libraries: Can be downloaded for extended functionality.
Beautiful Soup
: For parsing HTML website files.NumPy
: For arrays and mathematical computations.
Benefits of libraries and modules:
- Save time: Provide pre-programmed code, reducing development time.
- Improve code readability: Organize code into logical units.
- Expand functionality: Offer specialized tools for various tasks.
Encouragement: Explore different libraries and modules to enhance your Python skills and tackle diverse tasks efficiently.
Welcome to the world of modules and libraries in Python! This tutorial will guide you through these powerful tools that streamline your coding experience and empower you to achieve more.
Modules: The Building Blocks
- What are modules? Think of them as reusable Python files containing functions, variables, classes, and other code. They organize your code into manageable units, making it more readable and maintainable.
- Creating a module: Simply save your Python code as a
.py
file. - Using a module: Import it using the
import
statement:
Python
import my_module # Replace 'my_module' with the actual module name
Accessing elements: Use dot notation:
Python
my_module.my_function()
my_module.my_variable
Libraries: Collections of Modules
- What are libraries? They are collections of modules that provide specialized functionality for various tasks.
- Types of libraries:
- Python Standard Library: A vast collection of modules included with Python, offering tools for common tasks like working with files, interacting with the command line, handling dates and times, and much more.
- External libraries: Third-party libraries that you can install to extend Python’s capabilities even further.
Key Standard Library Modules
os
: Interact with the operating system (file paths, environment variables, etc.).sys
: Access system-specific parameters and functions.math
: Perform mathematical operations.random
: Generate random numbers.datetime
: Work with dates and times.json
: Read and write JSON data.csv
: Handle CSV files.re
: Perform regular expression operations for pattern matching.
Installing External Libraries
- Use the
pip
package manager:
Bash
pip install <library_name>
Popular External Libraries
- NumPy: Powerful array and matrix operations for numerical computing.
- Pandas: Data analysis and manipulation tools, built on top of NumPy.
- Matplotlib: Creating visualizations and plots.
- Requests: Making HTTP requests to interact with web services.
- Beautiful Soup: Parsing HTML and XML documents for web scraping.
Best Practices
- Choose the right library: Explore available libraries to find the best fit for your specific task.
- Use clear import statements: Be specific about which modules and functions you import to avoid naming conflicts.
- Document your code: Explain how you’re using modules and libraries to improve readability and collaboration.
Ready to explore? Experiment with different modules and libraries to expand your Python skills and tackle diverse projects efficiently!
What is the difference between a module and a library in Python?
A module is a Python file that contains additional functions, variables, and other kinds of runnable code. A Python library is a collection of modules.
A module is a Python file that contains additional functions, variables, and other kinds of runnable code. A Python library is a collection of modules.
Hello again! Previously, we learned about
built-in functions in Python. Built-in functions come standard
with every version of Python and consist of functions such as print(),
type(), max(), and many more. To access additional pre-built functions,
you can import a library. A library is a collection of
modules that provide code users can access in their programs. All libraries are generally
made up of several modules. A module is a Python file that
contains additional functions, variables, classes, and
any kind of runnable code. Think of them as saved Python files
that contain useful functionality. Modules may be made up of small and
simple lines of code or be complex and lengthy in size. Either way, they help save programmers
time and make code more readable. Now, let’s focus specifically
on the Python Standard Library. The Python Standard Library
is an extensive collection of usable Python code that often
comes packaged with Python. One example of a module from the Python
Standard Library is the re module. This is a useful module for a security analyst when they’re tasked
with searching for patterns in log files. Another module is the csv module. It allows you to work
efficiently with CSV files. The Python Standard Library also
contains glob and os modules for interacting with the command
line as well as time and datetime for working with timestamps. These are just a few of the modules
in the Python Standard Library. In addition to what’s always available
through the Python Standard Library, you can also download external libraries. A couple of examples are Beautiful Soup
for parsing HTML website files and NumPy for arrays and
mathematical computations. These libraries will assist you
as a security analyst in network traffic analysis,
log file parsing, and complex math. Overall, Python libraries and modules are useful because they provide
pre-programmed functions and variables. This saves time for the user. I encourage you to explore some of the
libraries and modules we discussed here and the ways they might be helpful
to you as you work in Python.
Reading: Import modules and libraries in Python
Reading
Previously, you explored libraries and modules. You learned that a module is a Python file that contains additional functions, variables, classes, and any kind of runnable code. You also learned that a library is a collection of modules that provide code users can access in their programs. You were introduced to a few modules in the Python Standard Library and a couple of external libraries. In this reading, you’ll learn how to import a module that exists in the Python Standard Library and use its functions. You’ll also expand your understanding of external libraries.
The Python Standard Library
The Python Standard Library is an extensive collection of Python code that often comes packaged with Python. It includes a variety of modules, each with pre-built code centered around a particular type of task.
For example, you were previously introduced to the following modules in the Python Standard Library:
- The re module, which provides functions used for searching for patterns in log files
- The csv module, which provides functions used when working with .csv files
- The glob and os modules, which provide functions used when interacting with the command line
- The time and datetime modules, which provide functions used when working with timestamps
Another Python Standard Library module is statistics. The statistics module includes functions used when calculating statistics related to numeric data. For example, mean() is a function in the statistics module that takes numeric data as input and calculates its mean (or average). Additionally, median() is a function in the statistics module that takes numeric data as input and calculates its median (or middle value).
How to import modules from the Python Standard Library
To access modules from the Python Standard Library, you need to import them. You can choose to either import a full module or to only import specific functions from a module.
Importing an entire module
To import an entire Python Standard Library module, you use the import keyword. The import keyword searches for a module or library in a system and adds it to the local Python environment. After import, specify the name of the module to import. For example, you can specify import statistics to import the statistics module. This will import all the functions inside of the statistics module for use later in your code.
As an example, you might want to use the mean() function from the statistics module to calculate the average number of failed login attempts per month for a particular user. In the following code block, the total number of failed login attempts for each of the twelve months is stored in a list called monthly_failed_attempts. Run this code and analyze how mean() can be used to calculate the average of these monthly failed login totals and store it in mean_failed_attempts:
import statistics
monthly_failed_attempts = [20, 17, 178, 33, 15, 21, 19, 29, 32, 15, 25, 19]
mean_failed_attempts = statistics.mean(monthly_failed_attempts)
print("mean:", mean_failed_attempts)
mean: 35.25
The output returns a mean of 35.25. You might notice the outlying value of 178 and want to find the middle value as well. To do this through the median() function, you can use the following code:
import statistics
monthly_failed_attempts = [20, 17, 178, 33, 15, 21, 19, 29, 32, 15, 25, 19]
median_failed_attempts = statistics.median(monthly_failed_attempts)
print("median:", median_failed_attempts)
median: 20.5
This gives you the value of 20.5, which might also be useful for analyzing the user’s failed login attempt statistics.
Note: When importing an entire Python Standard Library module, you need to identify the name of the module with the function when you call it. You can do this by placing the module name followed by a period (.) before the function name. For example, the previous code blocks use statistics.mean() and statistics.median() to call those functions.
Importing specific functions from a module
To import a specific function from the Python Standard Library, you can use the from keyword. For example, if you want to import just the median() function from the statistics module, you can write from statistics import median.
To import multiple functions from a module, you can separate the functions you want to import with a comma. For instance, from statistics import mean, median imports both the mean() and the median() functions from the statistics module.
An important detail to note is that if you import specific functions from a module, you no longer have to specify the name of the module before those functions. You can examine this in the following code, which specifically imports only the median() and the mean() functions from the statistics module and performs the same calculations as the previous examples:
from statistics import mean, median
monthly_failed_attempts = [20, 17, 178, 33, 15, 21, 19, 29, 32, 15, 25, 19]
mean_failed_attempts = mean(monthly_failed_attempts)
print("mean:", mean_failed_attempts)
median_failed_attempts = median(monthly_failed_attempts)
print("median:", median_failed_attempts)
mean: 35.25
median: 20.5
It is no longer necessary to specify statistics.mean() or statistics.median() and instead the code incorporates these functions as mean() and median().
External libraries
In addition to the Python Standard Library, you can also download external libraries and incorporate them into your Python code. For example, previously you were introduced to Beautiful Soup (bs4) for parsing HTML files and NumPy (numpy) for arrays and mathematical computations. Before using them in a Jupyter Notebook or a Google Colab environment, you need to install them first.
To install a library, such as numpy, in either environment, you can run the following line prior to importing the library:
%pip install numpy
This installs the library so you can use it in your notebook.
After a library is installed, you can import it directly into Python using the import keyword in a similar way to how you used it to import modules from the Python Standard Library. For example, after the numpy install, you can use this code to import it:
import numpy
Key takeaways
The Python Standard Library contains many modules that you can import, including re, csv, os, glob, time, datetime, and statistics. To import these modules, you must use the import keyword. Syntax varies depending on whether or not you want to import the entire module or just specific functions from it. External libraries can also be imported into Python, but they need to be installed first.
Video: Code readability
This video highlights the importance of code readability in Python and introduces the PEP 8 style guide as a resource for achieving consistent formatting and conventions.
Key points:
- Python’s readability is enhanced by its clear language and community-driven style guides.
- PEP 8 provides recommendations for syntax, comments, and indentation.
- Comments clarify code intention and are crucial for both initial understanding and future revisions.
- Proper indentation groups related lines and ensures correct program execution.
- Adhering to style guides like PEP 8 improves code readability, maintainability, and collaboration.
- Readable code is essential for security professionals working on and modifying Python projects.
Next steps:
The course will delve deeper into developing effective code practices for enhanced readability.
Remember: Readable code is not just a stylistic preference; it’s essential for efficient collaboration, maintenance, and long-term success in Python projects.
Welcome to the tutorial on Code Readability in Python!
Writing clear and concise code is crucial for efficient collaboration, maintenance, and long-term success in Python projects. This tutorial will guide you through essential practices to achieve this goal.
Key Principles:
- Code is Read More Often Than Written: Prioritize readability for both yourself and others.
- Consistency is Key: Adhere to style guides for consistency and clarity.
- Clarity is King: Write code that’s easy to understand at a glance.
Essential Practices:
- PEP 8 Style Guide:
- Your go-to resource for Python coding conventions.
- Covers indentation, spacing, naming conventions, and more.
- Meaningful Variable and Function Names:
- Use descriptive names that convey their purpose.
- Avoid abbreviations or single-letter names.
- Example:
user_name
instead ofun
orx
.
- Comments:
- Explain complex code sections, algorithms, or non-obvious logic.
- Keep comments concise and up-to-date with code changes.
- Use clear language and avoid unnecessary jargon.
- Proper Indentation:
- Visually represents code structure and relationships.
- Python enforces indentation for code blocks.
- PEP 8 recommends 4 spaces per indentation level.
- Line Length and Spacing:
- Limit lines to 79 characters for readability.
- Use blank lines to separate logical code sections.
- Whitespace:
- Use spaces around operators and after commas for visual clarity.
- Docstrings:
- Multi-line comments embedded within functions and classes.
- Describe their purpose, parameters, and return values.
- Type Hints:
- Indicate expected variable and function argument types.
- Improve code clarity and enable static type checking.
Tools for Readability:
- Linters: Analyze code for style violations and potential errors.
- Code Formatters: Automatically format code according to PEP 8.
Remember: Code readability is an ongoing practice. Continuously evaluate and refine your code to make it as clear and understandable as possible for both you and your collaborators.
Happy coding!
Welcome back! One of the advantages
to programming in Python is that it’s a very readable language. It also helps that the Python community
shares a set of guidelines that promote clean and neat code.
These are called style guides. A style guide is a manual
that informs the writing, formatting, and design of documents. As it relates to programming, style guides are intended to help
programmers follow similar conventions. The PEP 8 style guide is a resource
that provides stylistic guidelines for programmers working in Python. PEP is short for
Python Enhancement Proposals. PEP 8 provides programmers with
suggestions related to syntax. They’re not mandatory, but
they help create consistency among programmers to make sure that
others can easily understand our code. It’s essentially based on
the principle that code is read much more often than it’s written. This is a great resource for
anyone who wants to learn how to style and format their Python code in a manner
consistent with other programmers. For example, PEP 8 discusses comments. A comment is a note programmers make
about the intention behind their code. They are inserted in computer programs to
indicate what the code is doing and why. PEP 8 gives specific recommendations,
like making your comments clear and keeping them up-to-date
when the code changes. Here’s an example of
code without a comment. The person who wrote it might
know what’s going on, but what about others who need to read it? They might not understand the context
behind the failed-attempts variable and why it prints “Account locked”
if it’s greater than 5. And the original writer might need to
revisit this code in the future, for example, to debug the larger program. Without the comment,
they would also be less efficient. But in this example we’ve added a comment. All the readers can quickly
understand what our program and its variables are doing. Comments should be short and
right to the point. Next, let’s talk about another important
aspect of code readability: indentation. Indentation is a space added at
the beginning of a line of code. This both improves readability and
ensures that code is executed properly. There are instances when you
must indent lines of code to establish connections
with other lines of code. This groups the indented
lines of code together and establishes a connection with a previous
line of code that isn’t indented. The body of a conditional
statement is one example of this. We need to make sure this printed
statement executes only when the condition is met. Indenting here provides
this instruction to Python. If the printed statement were not
indented, Python would execute this printed statement outside of
the conditional and it would always print. This would be problematic because
you would get a message that updates are needed, even if they’re not. To indent, you must add at least one
space before a line of code. Typically, programmers are two to four
spaces for visual clarity. The PEP 8 style guide
recommends four spaces. At my first engineering job,
I wrote a script to help validate and launch firewall rules. Initially, my script worked well, but it became hard to read a year later when
we were trying to expand its functionality. My programming knowledge and coding style had evolved over that year, as
had the coding practices of my teammates. Our organization did not use a coding
style guide at that time, so our codes were very different,
hard to read, and did not scale well. This caused a lot of challenges and
required additional work to fix. Ensuring that code is readable and
can be modified over time is why it’s important for security professionals
to adhere to coding style guides and why style guides are so
important for organizations to utilize. The ability to write readable code
is key when working in Python. As we head into the next
part of our course, we’ll continue to develop effective
code practices for better readability.
Reading: Ensure proper syntax and readability in Python
Reading
Previously, you were introduced to the PEP 8 style guide and its stylistic guidelines for programmers working in Python. You also learned about how adding comments and using correct indentation makes your code more readable. Additionally, correct indentation ensures your code is executed properly. This reading explores these ideas further and also focuses on common items to check in the syntax of your code to ensure it runs.
Comments
A comment is a note programmers make about the intentions behind their code. Comments make it easier for you and other programmers to read and understand your code.
It’s important to start your code with a comment that explains what the program does. Then, throughout the code, you should add additional comments about your intentions behind specific sections.
When adding comments, you can add both single-line comments and multi-line comments.
Single-line comments
Single-line comments in Python begin with the (#) symbol. According to the PEP 8 style guide, it’s best practice to keep all lines in Python under 79 characters to maintain readability, and this includes comments.
Single-line comments are often used throughout your program to explain the intention behind specific sections of code. For example, this might be when you’re explaining simpler components of your program, such as the following for loop:
# Print elements of 'computer_assets' list
computer_assets = ["laptop1", "desktop20", "smartphone03"]
for asset in computer_assets:
print(asset)
Note: Comments are important when writing more complex code, like functions, or multiple loops or conditional statements. However, they’re optional when writing less complex code like reassigning a variable.
Multi-line comments
Multi-line comments are used when you need more than 79 characters in a single comment. For example, this might occur when defining a function if the comment describes its inputs and their data types as well as its output.
There are two commonly used ways of writing multi-line comments in Python. The first is by using the hashtag (#) symbol over multiple lines:
# remaining_login_attempts() function takes two integer parameters,
# the maximum login attempts allowed and the total attempts made,
# and it returns an integer representing remaining login attempts
def remaining_login_attempts(maximum_attempts, total_attempts):
return maximum_attempts - total_attempts
Another way of writing multi-line comments is by using documentation strings and not assigning them to a variable. Documentation strings, also called docstrings, are strings that are written over multiple lines and are used to document code. To create a documentation string, use triple quotation marks (“”” “””).
You could add the comment to the function in the previous example in this way too:
"""
remaining_login_attempts() function takes two integer parameters,
the maximum login attempts allowed and the total attempts made,
and it returns an integer representing remaining login attempts
"""
Correct indentation
Indentation is space added at the beginning of a line of code. In Python, you should indent the body of conditional statements, iterative statements, and function definitions. Indentation is not only necessary for Python to interpret this syntax properly, but it can also make it easier for you and other programmers to read your code.
The PEP 8 style guide recommends that indentations should be four spaces long. For example, if you had a conditional statement inside of a while loop, the body of the loop would be indented four spaces and the body of the conditional would be indented four spaces beyond that. This means the conditional would be indented eight spaces in total.
count = 0
login_status = True
while login_status == True:
print("Try again.")
count = count + 1
if count == 4:
login_status = False
Maintaining correct syntax
Syntax errors involve invalid usage of the Python language. They are incredibly common with Python, so focusing on correct syntax is essential in ensuring that your code runs. Awareness of common errors will help you more easily fix them.
Syntax errors often occur because of mistakes with data types or in the headers of conditional or iterative statements or of function definitions.
Data types
Correct syntax varies depending on data type:
- Place string data in quotation marks.
- Example: username = “bmoreno”
- Do not add quotation marks around integer, float, or Boolean data types.
- Examples: login_attempts = 5, percentage_successful = .8, login_status = True
- Place lists in brackets and separate the elements of a list with commas.
- Example: username_list = [“bmoreno”, “tshah”]
Colons in headers
The header of a conditional or iterative statement or of a function definition must end with a colon. For example, a colon appears at the end of the header in the following function definition:
def remaining_login_attempts(maximum_attempts, total_attempts):
return maximum_attempts - total_attempts
Key takeaways
The PEP 8 style guide provides recommendations for writing code that can be easily understood and read by other Python programmers. In order to make your intentions clear, you should incorporate comments into your code. Depending on the length of the comment, you can follow conventions for single-line or multi-line comments. It’s also important to use correct indentation; this ensures your code will run as intended and also makes it easier to read. Finally, you should also be aware of common syntax issues so that you can more easily fix them.
Resources for more information
Learning to write readable code can be challenging, so make sure to review the PEP 8 style guide and learn about additional aspects of code readability.
- PEP 8 – Style Guide for Python Code: The PEP 8 style guide contains all standards of Python code. When reading this guide, it’s helpful to use the table of contents to navigate through the concepts you haven’t learned yet.
Video: Dorsa: Use Python efficiently on a cybersecurity team
- The speaker, Dorsa, is a security engineer who emphasizes the importance of collaboration in Python for cybersecurity professionals.
- Collaboratively written Python code allows for a more uniform and efficient coding process.
- Sharing code snippets among team members makes the code base more readable and allows for easier collaboration.
- Dorsa shares an example from Google where collaboratively written code reduced the onboarding process from hours to minutes.
- Communication and expressing the need for help are important when working in a team and developing code in Python.
- Dorsa encourages learners to search for and reuse existing functions and methods found on the internet.
- She also suggests talking to colleagues, attending meetups, and engaging with other security professionals to expand Python coding skills in cybersecurity.
Hi, my name is Dorsa and
I’m a security engineer. What I love the
most about my job is that I get to look at different infrastructures
and system designs on a daily basis. One piece of advice for
individuals who are starting out in their
cybersecurity profession, it’s very important to work collaboratively in
Python and one of the key aspects of
that is to listen to the feedback that your
team members provide. Python allows for
many different ways of accessing different
information. When you share Python code snippets amongst
your team members, it allows the code
to be more uniform and the coding process
to be more efficient. It makes the code
base a lot more readable and it allows for other engineers to work
on your code after you, I’ve seen many examples of when collaboratively
written Python code has been helpful
in the industry. One of the examples is
when at Google we wrote a collaboratively written
code base which allowed for an onboarding
process to be reduced from six or seven hours
to a couple of minutes. Collaboration was a key part
of this process because otherwise it would have taken many many years for one single
individual to write it. One individual is not able to understand every fine detail of each system and if we don’t have multiple
engineers working on it, they would have made this
process a lot more difficult. Communication is very important
when you’re working in a team and especially if you’re developing
code in Python, you need to express whether you need help
throughout the process because your team
members are there to ensure that you are successful. At the end of the
day, your success means that your team
is also successful. As you advance in your career as someone who writes
code in Python, you’ll realize that
there are a lot of functions and methods
that are just sticking around on the
internet and you will be able to find them
with a quick search and those methods will
come in handy and you will be able to reuse them
for your pieces of code. A really good resource for you to learn new skills and expand your Python coding skills is to talk to your colleagues,
attend meetups, talk to different security professionals who don’t work at your company because
everyone has an insight on how to
make your coding skills, especially in
cybersecurity better.
Practice Quiz: Test your knowledge: Learn from the Python community
Which of these is not included in the Python Standard Library?
NumPy
The NumPy library is not included in the Python Standard Library. It is an external library that must be downloaded.
Which of the following resources provides recommendations about including comments in your code?
PEP 8
The PEP 8 style guide is a resource that provides stylistic guidelines for programmers working in Python, including recommendations about comments. This includes guidelines such as making comments clear and keeping them up-to-date when code changes.
Which of the following code blocks have correct indentation?
if username == "elarson":
print("Welcome, elarson!")
The following block of code demonstrates correct indentation:
if username == "elarson":
print("Welcome, elarson!")
The body of a conditional statement, which is the print() function in this case, must be indented for the code to execute properly.
What is a Python module?
A Python file that contains additional functions, variables, and any kind of runnable code
A Python module is a Python file that contains additional functions, variables, and any kind of runnable code.
Review: Write effective Python code
Video: Wrap-up
Python Course Recap: Functions, Modules, and Beyond!
Key Learnings:
- Functions: Powerful tools for repetitive tasks, built-in & custom.
- Modules & Libraries: Expanding Python’s capabilities with external functions.
- Code Readability & Best Practices: Writing clean, understandable code for future reference.
Outcome: Equipped to leverage Python for task automation and security analysis.
Next Steps: Diving deeper into Python’s power for automating tasks and improving your security analyst skills.
A Warm Farewell: Thank you for your dedication! See you in the next videos!
Great work on making it this
far in the Python course! You’ve put in a lot of work and effort towards
learning more about how you can use Python
effectively and efficiently. Let’s quickly recap the concepts you learned throughout the videos. First, we started by understanding the role
of functions in Python. They can save you a lot of time! You learned how to incorporate built-in functions and how to develop your own function
to meet your needs. We then shifted our focus
towards modules and libraries, which gave us access to a lot more functions than
those built into Python. Lastly, we moved
to learning about code readability and
best practices to write clean,
understandable code. With these understandings, you’re ready to
learn how powerful Python can really be
for task automation and how it can help you going
forward as a security analyst. Thank you for taking the time to go through this
course with me. I’ll meet you in
the next videos!
Reading: Reference guide: Python concepts from module 2
Reading: Glossary terms from module 2
Terms and definitions from Course 7, Module 2
Argument (Python): The data brought into a function when it is called
Built-in function: A function that exists within Python and can be called directly
Comment: A note programmers make about the intention behind their code
Function: A section of code that can be reused in a program
Global variable: A variable that is available through the entire program
Indentation: Space added at the beginning of a line of code
Library: A collection of modules that provide code users can access in their programs
Local variable: A variable assigned within a function
Module: A Python file that contains additional functions, variables, classes, and any kind of runnable code
Parameter (Python): An object that is included in a function definition for use in that function
PEP 8 style guide: A resource that provides stylistic guidelines for programmers working in Python
Python Standard Library: An extensive collection of Python code that often comes packaged with Python
Return statement: A Python statement that executes inside a function and sends information back to the function call
Style guide: A manual that informs the writing, formatting, and design of documents
User-defined function: A function that programmers design for their specific needs
Quiz: Module 2 challenge
Which of the following choices is a valid header in a function definition?
def remove_user(username):
Which of the following calls to the sorted() function uses correct syntax?
sorted([532, 73, 85])
What is a parameter?
An object that is included in a function definition for use in that function
AI
The correct answer is The data brought into a function when it is called.
Explanation:
- Parameters act as placeholders for values that are passed into a function when it’s invoked. They enable a function to operate on different inputs, making it more versatile.
- Example:
Python
def greet(name): # "name" is the parameter
print("Hello, " + name + "!")
greet("Alice") # "Alice" is the argument passed to the parameter
Here, “name” is the parameter, and “Alice” is the argument provided when the function is called.
Key points:
- Arguments are the actual values supplied to the function during the call.
- Parameters are the variables defined within the function’s parentheses that receive those values.
- They allow functions to be flexible and adaptable to different situations.
Fill in the blank: A collection of modules that users can access in their programs is a _____.
library
AI
The correct answer is library.
Explanation:
- Libraries are organized collections of modules that provide pre-written code to extend Python’s functionality.
- They offer a vast range of tools and features, saving developers time and effort.
- Popular libraries include NumPy for numerical computations, Pandas for data analysis, and Matplotlib for data visualization.
Key points:
- Modules are individual files containing Python code, often grouped into libraries for easier access.
- Libraries act as repositories of reusable code, promoting efficiency and code sharing.
- They are essential for tasks like data manipulation, scientific computing, web development, and more.
What does this line of code return?
print(max(1,3,7))
7
What is returned from the following user-defined function if you pass it the argument of 2?
def multiples(num):
multiple = num * 3
return multiple
multiples(2)
6
Which of the following choices is a resource that provides stylistic guidelines for programmers working in Python?
PEP 8
What is an advantage of including this comment in the following code? Select all that apply.
# For loop iterates to print an alert message 5 times
for i in range(5):
print("alert")
- It can help other programmers understand the purpose of this loop.
- It can help you understand the code if you revisit it in the future.
Which of the following statements accurately describe functions? Select all that apply.
- When functions are updated, the changes are applied everywhere they are used.
- Functions can be reused throughout a program.
- Functions are useful for automation.
You imported a Python module, what do you now have access to in Python?
Additional functions, variables, classes, and other kinds of runnable code
Which of the following calls to the type() function uses correct syntax?
type([55, 81, 17])
Fill in the blank: A collection of modules that users can access in their programs is a _____.
library
What does this line of code return?
print(type(“h32rb17”))
str
What is returned from the following user-defined function if you pass it the arguments 2 and 3?
def add(num1, num2):
result = num1 + num2
return result
add(2, 3)
5
What are built-in functions?
Functions that exist with Python and can be called directly
Fill in the blank: A Python file that contains additional functions, variables, classes, and any kind of runnable code is called a _____.
module