Skip to content
Home » Google Career Certificates » Google Cybersecurity Professional Certificate » Automate Cybersecurity Tasks with Python » Module 2: Write effective Python code

Module 2: Write effective Python code

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:

  1. Use the def keyword: Pythondef function_name(parameters): # Function body (code to be executed)
  2. Give it a descriptive name: Choose a name that clearly reflects what the function does.
  3. Define parameters (optional): These are variables that can receive input values when the function is called.
  4. Write the code within the function: This is the block of code that will be executed when the function is called.
  5. 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:

  1. 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.
  2. 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:

  1. Use the def keyword: Pythondef function_name(parameters): # Function body (code to be executed)
  2. Choose a descriptive name: Reflect what the function does.
  3. Define parameters (optional): Variables to receive input values.
  4. 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

Lab: Activity: Define and call a function

Practice Quiz: Test your knowledge: Introduction to functions

In Python, what is a function?

Which of the following keywords is essential when defining a function?

You want to define a function that performs a status check. Which of the following is a valid header for the function definition?

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?

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: Takes start and stop 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 and failed_attempts as parameters.
    • Calculates the percentage of failed attempts.
    • Returns the calculated percentage using the return statement.
  • 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

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!")
  • type(): Returns the data type of an object.
    • Example: print(type(5.2)) # Output: <class ‘float’>
  • max(): Returns the largest value among its arguments.
    • Example: largest = max(3, 9, 6) # largest will be 9
  • min(): Returns the smallest value among its arguments.
    • Example: smallest = min(17, 4, 22) # smallest will be 4
  • sorted(): Returns a sorted version of a list.
    • Example: sorted_numbers = sorted([5, 2, 8, 1]) # [1, 2, 5, 8]
  • len(): Returns the length of an object (number of items in a sequence).
    • Example: username_length = len("admin") # 5
  • input(): Prompts the user for input and returns it as a string.
    • Example: name = input("Enter your name: ")
  • str(): Converts a value to a string.
    • Example: number_string = str(42) # “42”
  • int(): Converts a value to an integer.
    • Example: age = int("35") # 35
  • float(): Converts a value to a floating-point number.
    • Example: price = float("9.99") # 9.99
  • abs(): Returns the absolute value of a number.
    • Example: distance = abs(-15) # 15

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

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)

What is the correct way to define the function addition() if it requires the two parameters num1 and num2?

Which of the following lines of code has correct syntax for printing the data type of the string “elarson”?

Which function definition includes the correct syntax for returning the value of the result variable from the doubles() function?

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 and os: For interacting with the command line.
    • time and datetime: 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

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:

  1. PEP 8 Style Guide:
    • Your go-to resource for Python coding conventions.
    • Covers indentation, spacing, naming conventions, and more.
    PEP 8 Style Guide: [Insert image of PEP 8 Style Guide]
  2. Meaningful Variable and Function Names:
    • Use descriptive names that convey their purpose.
    • Avoid abbreviations or single-letter names.
    • Example: user_name instead of un or x.
  3. 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.
  4. Proper Indentation:
    • Visually represents code structure and relationships.
    • Python enforces indentation for code blocks.
    • PEP 8 recommends 4 spaces per indentation level.
    Python Indentation Example: [Insert image of Python code with proper indentation]
  5. Line Length and Spacing:
    • Limit lines to 79 characters for readability.
    • Use blank lines to separate logical code sections.
  6. Whitespace:
    • Use spaces around operators and after commas for visual clarity.
  7. Docstrings:
    • Multi-line comments embedded within functions and classes.
    • Describe their purpose, parameters, and return values.
  8. 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

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?

Which of the following resources provides recommendations about including comments in your code?

Which of the following code blocks have correct indentation?

What is a Python module?

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

Quiz: Module 2 challenge

Which of the following choices is a valid header in a function definition?

Which of the following calls to the sorted() function uses correct syntax?

What is a parameter?

Fill in the blank: A collection of modules that users can access in their programs is a _____.

What does this line of code return?
print(max(1,3,7))

What is returned from the following user-defined function if you pass it the argument of 2?

Which of the following choices is a resource that provides stylistic guidelines for programmers working in Python?

What is an advantage of including this comment in the following code? Select all that apply.

Which of the following statements accurately describe functions? Select all that apply.

You imported a Python module, what do you now have access to in Python?

Which of the following calls to the type() function uses correct syntax?

Fill in the blank: A collection of modules that users can access in their programs is a _____.

What does this line of code return?
print(type(“h32rb17”))

What is returned from the following user-defined function if you pass it the arguments 2 and 3?

What are built-in functions?

Fill in the blank: A Python file that contains additional functions, variables, classes, and any kind of runnable code is called a _____.