You will get an introduction to the Python programming language and how Python is used in cybersecurity. You’ll also explore foundational Python concepts including data types, variables, conditional statements, and iterative statements.
Learning Objectives
- Explain how the Python programming language is used in security.
- Describe how various data types are handled in Python.
- Incorporate variables into Python code.
- Write conditional statements in Python.
- Write iterative statements in Python.
- Get started with the course
- Introduction to Python programming in cybersecurity
- Video: Welcome to module 1
- Video: Python and cybersecurity
- Reading: Get to know Python
- Video: Create a basic Python script
- Reading: Python environments
- Reading: Lab tips and troubleshooting steps
- Lab: Exemplar: Practice writing Python code
- Video: Akash: Python and the cybersecurity professional
- Practice Quiz: Test your knowledge: Introduction to Python programming in cybersecurity
- Core Python components
- Conditional and iterative statements
- Video: Conditional statements in Python
- Reading: More on conditionals in Python
- Lab: Activity: Create a conditional statement
- Lab: Exemplar: Create a conditional statement
- Video: For loops
- Video: While loops
- Reading: More on loops in Python
- Integers in the loop condition
- Exemplar: Create loops
- Practice Quiz: Test your knowledge: Conditional and iterative statements
- Review: Introduction to Python
Get started with the course
Video: Introduction to Course 7
Python for Security: Dive into Automation and Efficiency
Why Python?
- Demand is high: Cybersecurity skills are in high demand, and Python adds automation power to your toolkit.
- Diverse tasks: Security requires flexibility, and Python handles a wide range of security work.
- Join the community: Engineers, data scientists, and security professionals all leverage Python.
Your Guide:
- Angel, Security Engineer at Google: Learn from a Google practitioner and real-world security expert.
- Gradual learning: Start with basics, build your skills, and apply your knowledge to security tasks.
What you’ll learn:
- Basic Python programming: Concepts, readability, and practical application.
- Automating tasks: Parse files, build tools, and streamline your workflow.
- Strings & lists: Manipulate data relevant to security analysis.
- Opening & parsing files: Extract valuable information from security contexts.
- Debugging code: Identify and fix issues to keep your work efficient.
Ready to unlock the power of Python for cybersecurity? Start your journey today!
This summary captures the key points of the provided text, emphasizing the demand for Python in security, the course structure, and the instructor’s expertise. It also uses a tone that is both informative and inviting to encourage learners to engage with the material.
The demand for security
professionals has never been higher. Organizations across the world require
professionals with your knowledge and skills to protect their
systems from attackers. And with the number of
threats on the rise, security professionals often
perform a diverse set of tasks. It’s for this reason that we’ll incorporate another
tool as part of our security toolbox. A tool that can simplify
many common security tasks. A tool that’s used not only
by security professionals but also by engineers and
data scientists. That tool is Python. Hi there! Congratulations on getting to
the next step in your security journey. My name is Angel, and
I am a Security Engineer at Google. I’m excited to be joining
you in this course. If you’ve been following along
sequentially, you’ve already applied the specific tools that security
professionals use during the detection, analysis, and response processes. And you also learned how to communicate
with your computer through Linux and SQL. Now, we’ll focus on how programming
in Python can be used for some common security tasks. As you consider your next career step, you might find that Python skills
will help you in your everyday work. This course is designed for
learning Python, starting with the basics. Then you’ll gradually
build on those basics and apply what you learn to gain hands-on
practice with security-related examples. Fortunately, Python is known for
its readability. And just like all languages,
it will get easier with practice. Pretty soon, you might be using
Python in your security career. Python can automate the manual effort
of important tasks like file parsing. Python has helped me a lot
in my career here at Google. I am part of a team responsible for protecting Google’s infrastructure,
which includes everything that employees use—from laptops and desktops
to the network and cloud resources. We do this by engineering
security solutions and automating the repeatable
parts of our work. What I like about Python is that it has
cross-platform support, and a lot of tools have already been developed by members of
the security community that use Python. This makes it easy for me to find
the tools I need and get support with blockers so I can complete both my
professional and personal projects. My hope is that this course
will be helpful to you. Let’s explore what we’ll cover. First, you’ll be introduced to basic
programming concepts in Python. You’ll learn why Python has been adopted
by security professionals around the world. You will also develop and
run your first program. After this, we’ll focus on
writing effective Python code. We’ll discuss concepts that help
make our work more efficient. Our next main topic is on
working with strings and lists. These will be relevant to a lot of the
data that you will encounter in a security context. And finally, you’ll wrap up the course with an exploration
of putting Python into practice. You’ll learn about opening and
parsing files and about debugging code. Python is certainly a useful skill for
security analysts. Let’s get started.
Video: Ángel: My personal career journey
Ángel’s Journey to Cybersecurity: Curiosity, Learning, and Resilience
Motivation:
- Curiosity: Childhood tinkering with technology sparked Ángel’s interest in “breaking things” to understand how they work.
- Impact: Security’s proactive approach to identifying vulnerabilities resonated with him.
- Personal experience: Major industry events like Project Aurora fueled his desire to be part of the solution.
Career Progression:
- Network engineer: Starting point in technology infrastructure.
- Cybersecurity specialization: Learning through online courses, certifications, and applying automation skills (Python) to his work.
- Adaptability: Embracing continuous learning and reinvention as key factors for career advancement and staying relevant in security.
Key takeaways:
- Curiosity, passion, and willingness to learn are critical for a successful cybersecurity career.
- Diverse perspectives and problem-solving approaches are valuable assets in the field.
- Resilience and perseverance are essential to overcome challenges and thrive in this dynamic environment.
This summary captures the essence of Ángel’s story, highlighting his motivations, career path, and key takeaways for aspiring cybersecurity professionals. It emphasizes the importance of curiosity, lifelong learning, and personal resilience in this crucial field.
My name is Ángel, and I’m a
Security Engineer at Google. There were a number of things in my life that led me to security. One of them was definitely curiosity when I was growing up. My parents are accountants,
and so they had pocket calculators and
mechanical pencils and pens. And I was always
breaking them up and taking pieces apart and trying to figure
out how they work. This led me to
technology in general, and the same concept
applied again—just trying to figure out how things work and breaking them. That’s basically what
security’s trying to do: breaking things to
figure out whether or not somebody else could
break them before you do. I started as a network engineer. This was setting up firewalls, setting up switches and routers
for different companies. I wanted to join cybersecurity
mostly because I felt very motivated about the things that were going on
in the industry. Project Aurora was Google getting hacked by
a foreign actor. I was reading this
and I was thinking, “I wish I could work with the people that are working
on this on the front lines.” When I was starting to get into cybersecurity and I wanted
to make a jump in my career, what I wanted to learn,
where I needed to be. One example is learning
automation through Python. I took online classes, I completed certifications—security
certifications, very popular ones—and then I just started to incorporate some of these
aspects into my current job. When I was moving from Mexico
to the U.S. to work here, I had to learn how
to be flexible. You have to learn new things in order to advance your career. Sometimes even you have to learn new things just to stay
at the same spot you are. In security, I think
in all of technology, but especially in security, you constantly have
to reinvent yourself, keep learning how things work, and keep learning how you
can help the industry. One important skill throughout
my life and in my career as a cybersecurity
professional is resiliency. I learned a lot about resiliency
when I first moved here in the U.S. and things didn’t go
the way I expected them to, and I have to keep trying new things and
hope for the best. And that is really no different from what we do as
security professionals. We do this on a
day-to-day basis. We have to either figure out
ways to make things work, we have to figure
out ways to make projects function the
way we need them to, or we have to figure out
ways to get past a problem. We need more professionals in cybersecurity with
different backgrounds, and that means
different experiences, different ways of seeing things, different ways of approaching
and solving problems. We need more people like
you in this industry.
Introduction to Python programming in cybersecurity
Video: Welcome to module 1
- The comparison: Learning Python is like learning a human language: code lines communicate with computers like sentences communicate with people.
- Python for security analysts: This section teaches the basics to start exploring key components for security tasks.
- Building the foundation:
- Data types: Understanding different kinds of data Python can handle (numbers, text, etc.).
- Variables: Naming and storing data for later use in your program.
- Statements:
- Conditional statements: Adding logic by making decisions based on conditions.
- Iterative statements: Repeating lines of code automatically to save time.
- Benefits for security analysts:
- Automation: Freeing up time from repetitive tasks for more challenging work.
- Increased productivity: Reduced workload and human error.
- Focus on engineering tasks: More creativity, collaboration, and problem-solving.
- Ready to begin? This section sets the stage for diving into Python programming for security analysts.
This summary captures the key points of the passage, highlighting the comparison to human language, the focus on fundamental Python components, and the benefits for security analysts. It also emphasizes the call to action, inviting the reader to start learning Python.
The process of learning a new programming language is similar to learning
a new language. For instance, like
any human language, programming consists of words organized together to
form lines of code. Lines of code are used to
communicate with a computer, similar to a sentence, telling it how to
perform a task. In this section, we’re going to start learning the
language needed to communicate with
a computer as we explore some key
components of Python. We’ll start by introducing
the basics of programming, starting with why security
analysts use Python. Next, we’ll start building
the foundations for Python. We’ll discuss data types. Then we’ll cover variables. Lastly, we’re going
to learn about specific statements
we can make in Python, like
conditional statements. Conditional statements help us incorporate logic
into our programs. The second type of
statement we’ll learn about is the
iterative statement. Iterative statements allow
us to repeat a line of code multiple times without
having to rewrite it. Learning Python helped me succeed in my career
because using Python allows me to free up time from repetitive
tasks, and instead, focus on more challenging
tasks and problems. Successfully applying automation reduces
my overall workload, increases productivity, and reduces the risk
of human error. The use of automation
also allows me to focus on my
engineering tasks, which require more creativity, collaboration, and
problem-solving. Are you ready to
start programming in Python? Let’s begin.
Video: Python and cybersecurity
Security professionals leverage various tools, including computer programming, to automate tasks and analyze data. This section focuses on Python, a versatile language suitable for diverse applications like web development, AI, and security automation.
Python in Security:
- Automating tasks: Python streamlines repetitive tasks like analyzing logs, managing access control lists, and analyzing network traffic.
- Combining tasks: Python simplifies multi-step procedures by automating workflows like delivering files and sending notifications.
Advantages of Python:
- User-friendly: Simple syntax, concise code, and human-like readability.
- Large community: Extensive online resources, tutorials, and support.
- Rich libraries: Built-in functionalities for diverse tasks, reducing coding needs.
- High demand: Valuable skill across various industries.
Next Steps:
- Run your first Python code in the next video.
This summary captures the key points of the passage, highlighting the role of Python in security automation, its advantages, and the upcoming practical session. It condenses the information while retaining the excitement for learning the language.
Introduction
- Python’s role: Explain Python’s popularity in cybersecurity due to readability, extensive libraries, and versatility.
- Benefits: Highlight automation, data analysis, tool development, and rapid prototyping.
- Target audience: Specify the tutorial’s level (beginner or intermediate) and areas of focus.
Setting Up Python
- Installation: Guide learners through installing Python and an integrated development environment (IDE) like PyCharm or Visual Studio Code.
- Basic syntax: Cover variables, data types (int, float, string, boolean), operators, and control flow (if/else, loops).
Security Libraries
- Introduction: Introduce popular libraries:
- Requests: For making HTTP requests to interact with web services.
- Beautiful Soup: For parsing and extracting data from HTML and XML.
- Paramiko: For secure remote connections (SSH).
- Scapy: For network packet manipulation and analysis.
- Nmap: For network scanning and vulnerability detection.
- OWASP ZAP: For web application security testing.
- Examples: Demonstrate basic usage of each library with security-related tasks.
Common Use Cases
- Log analysis: Parsing and filtering security logs for anomalies and patterns.
- Network scanning: Detecting vulnerabilities and potential threats.
- Vulnerability assessment: Identifying security weaknesses in systems or applications.
- Penetration testing: Simulating attacks to assess system defenses.
- Malware analysis: Examining malicious code to understand its behavior.
- Incident response: Automating tasks during security breaches.
Hands-on Exercises:
- Create tasks: Guide learners through practical exercises in each use case, providing code examples and challenges.
- Encourage experimentation: Foster exploration and problem-solving.
Resources and Further Learning:
- Recommended books and courses: Point learners to additional materials for deeper study.
- Online communities and forums: Encourage participation in communities for support and knowledge sharing.
Conclusion
- Reiterate key points: Summarize Python’s significance in cybersecurity and its diverse applications.
- Encourage continued learning: Stress the importance of ongoing practice and exploration.
Why might a security analyst choose Python to automate tasks? Select three answers.
- Python programmers can follow standard guidelines
- Python resembles human language and is easy to read.
- Python programmers can find a lot of support online.
A security analyst might choose Python to automate tasks because they can find a lot of support online and follow standard guidelines. An analyst might also choose Python to automate tasks because it resembles human language and is easy to read.
Security professionals
use a variety of tools. One of those tools is
computer programming. Programming is used to create
a specific set of instructions for a computer to execute tasks. Let’s take an example
of a vending machine. Think of a vending machine as a computer
that supplies food or drinks to customers. To receive an item, the customer
inserts the money into the machine and then select the item they want. Let’s say the customer provides
the machine with a value of $5. The machine stores this value
while you make your selection. If you select a candy bar that costs $2, the machine takes this input,
otherwise known as an instruction, and then understands to
output your candy bar for $2 and provides the change back of $3. There are many programming
languages in existence. Here, we’ll focus on Python. Python is considered to be
a general-purpose language. This means that it can create
a variety of different programs, and it isn’t a specialized in any
particular problem in fields such as web development and
artificial intelligence. Python is typically used to build websites
and perform data analysis. In security, the main reason we use Python
is to automate our tasks. Automation is the use of
technology to reduce human and manual effort to perform common and
repetitive tasks. Python is generally best for
automating short, simple tasks. For example, a security analyst
who’s dealing with a security incident might have a log
with necessary information. Reading through these manually
would take too much time, but Python can help sort through this so
the analysts can find what they need. As another example, an analyst might use
Python to manage an access control list, the list that controls who can
access the system and its resources. It would be potentially less
consistent if the analysts had to manually remove an employee’s access
every time they left the company. However, a Python program can
periodically monitor this instead. Or, Python could also perform some automated
tasks like analyzing network traffic. Though these tasks can be done
through outside applications, they are also possible through Python. In addition to automating
individual tasks, Python can combine separate
tasks into one workstream. For example, imagine a playbook indicates
that an analyst needs to resolve a certain situation by delivering a file
and then notifying the proper individuals. Python can connect these
processes together. So why exactly might a security professional
choose Python for these tasks? There are several advantages Python
has as a programming language. For one, Python is user-friendly
because it resembles human language, it requires less code, and
it’s easy to read. Python programmers also have the benefit
of following standard guidelines to ensure consistency with the design and
readability of code. Another great reason for learning Python is that there’s
a large amount of online support. Python also has an extensive collection
of built-in code that we can import and use to perform many different tasks. These are just some of the reasons why
Python continues to be in high demand across different industries
throughout the world. You’ll most likely use it
in your security career. Wow! All of this sounds great. Let’s take a short break, and next, we’ll
finally get to run some Python code. I’ll meet you in the next video.
Reading: Get to know Python
Reading
In this reading, you will explore how programming works, how a computer processes the Python programming language, and how Python is used in cybersecurity.
How programming works
Programming is a process that can be used to create a specific set of instructions for a computer to execute tasks. Computer programs exist everywhere. Computers, cell phones, and many other electronic devices are all given instructions by computer programs.
There are multiple programming languages used to create computer programs. Python is one of these. Programming languages are converted to binary numbers, which are a series of 0s and 1s that represent the operations that the computer’s central processing unit (CPU) should perform. Each instruction corresponds to a specific operation, such as adding two numbers or loading a value from memory.
It would be very time-consuming for humans to communicate this way. Programming languages like Python make it easier to write code because you can use less syntax when instructing computers to perform complex processes.
Using Python to program
Python is a general purpose programming language that can be used to solve a variety of problems. For example, it can be used to build websites, perform data analysis, and automate tasks.
Python code must be converted through an interpreter before the computer can process it. An interpreter is a computer program that translates Python code into runnable instructions line by line.
Python versions
There are multiple versions of Python. In this course, you are using Python 3. While using Python, it’s important to keep track of the version you’re using. There are differences in the syntax of each version. Syntax refers to the rules that determine what is correctly structured in a computing language.
Python in cybersecurity
In cybersecurity, Python is used especially for automation. Automation is the use of technology to reduce human and manual effort to perform common and repetitive tasks. These are some specific areas of cybersecurity in which Python might be used to automate specific tasks:
- Log analysis
- Malware analysis
- Access control list management
- Intrusion detection
- Compliance checks
- Network scanning
Key takeaways
Python is a programming language, or in other words, a language used to create instructions for a computer to complete tasks. Programming languages are converted to binary numbers that a machine can understand. It’s important to be aware that there are multiple versions of Python, and they have differences in syntax. Python is especially useful in cybersecurity for automating repetitive tasks.
Video: Create a basic Python script
- Script vs. Program: Explains the difference between a script (specific instructions) and a program (larger production with design choices).
- Comments: Introduces comments as notes explaining code intention.
- First Code Line: Writes and runs
print("Hello Python!")
to understand print function and string syntax. - Next Steps: Introduces basic Python components for further exploration.
This summary captures the key points of the introduction to Python scripting and running code, emphasizing the learning process through practical examples and clear explanations. It also sets the stage for learning about fundamental building blocks of the language.
1. Choose a Text Editor or IDE:
- Text editors: Simpler for basic scripts. Popular options include:
- Notepad++ (Windows)
- Sublime Text (cross-platform)
- Visual Studio Code (cross-platform)
- Integrated Development Environments (IDEs): Offer more features for larger projects. Popular options include:
- PyCharm (cross-platform)
- Thonny (beginner-friendly)
2. Create a New File:
- Open your chosen editor or IDE.
- Click “File” > “New” or use a keyboard shortcut (usually Ctrl+N or Command+N) to create a new, blank file.
3. Start Writing Code:
- Begin with a comment: Python
# This is my first Python script
- Comments are ignored by Python but help explain code for humans.
- Print a message: Python
print("Hello, world!")
- The
print()
function displays output in the console.
- The
4. Save the File:
- Click “File” > “Save” or use a keyboard shortcut (usually Ctrl+S or Command+S).
- Choose a descriptive filename ending with
.py
(e.g.,my_first_script.py
).
5. Run the Script:
Method 1: Using a Terminal or Command Prompt:
- Open a terminal or command prompt.
- Navigate to the directory where you saved the script using the
cd
command (e.g.,cd Desktop/my_scripts
). - Type
python
followed by the script’s filename and press Enter (e.g.,python my_first_script.py
).
Method 2: Using an IDE:
- Most IDEs have built-in buttons or options to run the current script. Look for a “Run” button or a menu item like “Run” > “Run Python File”.
6. See the Output:
- The console will display the output of your script, such as:
Hello, world!
Congratulations! You’ve created and run your first Python script!
Explore Further:
- Add more lines of code: Experiment with different functions and calculations.
- Learn about variables and data types: Store and manipulate different information in your scripts.
- Use control flow: Add decision-making (if statements) and loops (for and while) to create more complex logic.
- Break down tasks into smaller functions: Make your code more organized and reusable.
- Explore Python libraries: Import and use existing code packages for various tasks (e.g., math, data analysis, web development).
Which of the following options is a Python comment?
# Print authorized usernames
# Print authorized usernames is a Python comment. Comments are notes that programmers make about the intention behind their code, and they begin with the # symbol.
Hi there. Previously, we
discussed the basics of Python. Now we’ll practice
writing and running code. When we work in Python, we refer to what we write
as a “script” or a “program.” There are subtle differences
between the two. Let’s compare a computer program to a theater performance. Almost every theater performance includes a written script. Actors study and memorize a script to say it out
loud to an audience. However, that’s not
the only component. There’s also the
whole performance. Directors make decisions
on what lighting to use, or costumes, or what
the stage looks like. The performance as a whole involves a lot of
design choices, like set design,
lighting, and costumes. The process of creating
this production is similar to the process of
programming in Python. Programming involves a
lot of design decisions. But the process of scripting
in Python is more like writing the specific words
that the actors will say. In Python, it’s good practice
to start with a comment. A comment is a note programmers make about the intention
behind their code. Let’s add one now. We start with the hash symbol
to indicate that this is a comment. And then we’ll add
details about our intention. Here we’re going to print “Hello Python” to the screen. Okay, now let’s write our first
line of Python code. This code uses print. Print outputs a specified
object to the screen. After print, we put what we want to output
in parentheses. In this case, we want to output
the string “Hello Python!” We must place string
data in quotation marks. These quotation marks are just one example of syntax that you will
encounter in Python. Syntax refers to the
rules that determine what is correctly structured
in a computing language. And now, we’ll run this code so the computer can
output the string. You just ran your
first line of code. Since our syntax is correct, the string is now displayed. Now that you’ve experience writing and running
code in Python, we’re ready to discuss its basic components.
Meet you soon.
Reading: Python environments
Reading
You can run Python through a variety of environments. These environments include notebooks, integrated development environments (IDEs), and the command line. This reading will introduce you to these environments. It will focus primarily on notebooks because this is how you’ll interact with Python in this course.
Notebooks
One way to write Python code is through a notebook. In this course, you’ll interact with Python through notebooks. A notebook is an online interface for writing, storing, and running code. They also allow you to document information about the code. Notebook content either appears in a code cell or markdown cell.
Code cells
Code cells are meant for writing and running code. A notebook provides a mechanism for running these code cells. Often, this is a play button located within the cell. When you run the code, its output appears after the code.
Markdown cells
Markdown cells are meant for describing the code. They allow you to format text in the markdown language. Markdown language is used for formatting plain text in text editors and code editors. For example, you might indicate that text should be in a certain header style.
Common notebook environments
Two common notebook environments are Jupyter Notebook and Google Colaboratory (or Google Colab). They allow you to run several programming languages, including Python.
Integrated development environments (IDEs)
Another option for writing Python code is through an integrated development environment (IDE), or a software application for writing code that provides editing assistance and error correction tools. Integrated development environments include a graphical user interface (GUI) that provides programmers with a variety of options to customize and build their programs.
Command line
The command line is another environment that allows you to run Python programs. Previously, you learned that a command-line interface (CLI) is a text-based user interface that uses commands to interact with the computer. By entering commands into the command line, you can access all files and directories saved on your hard drive, including files containing Python code you want to run. You can also use the command line to open a file editor and create a new Python file.
Key takeaways
Security analysts can access Python through a variety of environments, including notebooks, integrated development environments, and the command line. In this course, you’ll use notebooks, which are online interfaces for interacting with code. Notebooks contain code cells for writing and running code as well as markdown cells for plain text descriptions.
Reading: Lab tips and troubleshooting steps
Reading
Throughout this certificate you will use Qwiklabs and Jupyter Notebooks to complete hands-on activities that include Linux command line, packet capture, and Python programming tasks. In this reading, we will cover some tips and troubleshooting steps for using Qwiklabs and Jupyter Notebooks on your computer.
Browser compatibility
Make sure your internet browser is updated regularly. Qwiklabs and Jupyter Notebooks require the latest version of Google Chrome, Firefox, Safari, or Microsoft Edge. If your browser is outdated or you are using a browser that is not supported by Qwiklabs or Jupyter Notebooks, you may encounter a problem. If your browser is up to date and you are using one of the browsers listed above and still encountering problems try restarting your browser or clearing your browser’s cache and cookies. You can also use incognito mode which prevents your browser from storing cookies and other temporary data.
Note: The Qwiklabs user interface works best with Google Chrome.
Internet connection
Qwiklabs and Jupyter Notebooks require a stable internet connection. If you are experiencing problems starting or completing Qwiklabs or Jupyter Notebooks, your internet connection may be slow or unreliable. Some signs of an unstable internet connection may be freezing labs, difficulty connecting to virtual machines, or the inability to type or enter commands within the lab environment.
Pro Tip: If you are unable to complete a Qwiklab or Jupyter Notebooks lab on one device, try using another device.
Troubleshooting steps
To summarize, here are the troubleshooting steps to try if you encounter a problem with Qwiklabs or Jupyter Notebooks.
- Make sure you are using the latest version of a supported browser: Google Chrome, Firefox, Safari, or Microsoft Edge.
- Restart your browser and clear your browser’s cache and cookies. You can also use incognito mode.
- Check your internet connection and make sure it is stable. You can try restarting your router and modem to regain a stable connection.
- Try restarting Qwiklabs or Jupyter Notebooks again.
- For Qwiklabs only: If problems persist or you receive a message stating that you have exceeded the quota for a Qwiklab, submit this form to Qwiklabs support for assistance.
Lab: Exemplar: Practice writing Python code
Video: Akash: Python and the cybersecurity professional
- Python is an important language for cybersecurity engineers.
- Python can be used to automate tasks and write scripts.
- Learning Python can be fulfilling and there are many resources available.
- Cybersecurity is an exciting field with unlimited threats.
- Stick with learning Python, as it is an essential skill that will serve you throughout your career.
[MUSIC] My name is Akash, and
I work as a Security Engineer at Google. As a cybersecurity engineer, you would end
up using Python for most of your career. It’s very important that you learn Python. When you are moving into cybersecurity, you would be dealing with millions
of data points and things like that, which is going to be very hard for
you to go through manually. So, that’s when Python comes in to
automate and write scripts and small programs that will be able to
do the same thing in a split second. Learning Python is super fun. When you
see like ten lines of code doing things like parsing through megabytes of data
within seconds, it can be very fulfilling. There’s a lot of resources for Python,
and a lot of open-source communities, and the people are very helpful. Stay curious and
take up small problems and then get your hands
dirty with doing it and don’t be afraid of looking up syntax and
learn online resources. My job as a security engineer at
Google Chrome is to protect our customers from foreign governments and
very persistent threats across the world. The threats are unlimited,
there’s no limit to it, and that’s what makes
cybersecurity very exciting. So, stick with it, it’s an essential
skill that will take some time initially to develop but
will serve you throughout the career.
Practice Quiz: Test your knowledge: Introduction to Python programming in cybersecurity
What tasks would a security analyst most likely automate with Python? Select three answers.
Managing an access control list, Sorting through a log file, Analyzing network traffic
A security analyst would most likely automate the following tasks with Python: sorting through a log file, managing an access control list, and analyzing network traffic. Python is most commonly used in cybersecurity to automate common and repetitive tasks.
What are some benefits of using Python in security? Select all that apply.
- Python helps automate short, simple tasks.
- Python reduces manual effort.
- Python can combine separate tasks into one workstream.
Python reduces the manual effort needed to perform common and repetitive tasks. It helps automate short, simple tasks and can combine separate tasks into one workstream.
Which of the following code blocks contains a valid Python comment?
# This prints a "Try again" message
print("Try again")
The following code block contains a valid Python comment:
# This prints a “Try again” message
print(“Try again”)
A comment is a note programmers make about the intention behind their code. Comments begin with the hash symbol (#).
Which line of code outputs the string u003cvaru003eu0022invalid usernameu0022u003c/varu003e to the screen?
print(“invalid username”)
The code print(“invalid username”) outputs the string “invalid username” to the screen. The print() function outputs the object specified inside the parentheses to the screen. To output a string, it must be placed in quotation marks.
Core Python components
Video: Data types in Python
This video explores data categories in Python, likening them to categorizing ingredients in cooking. Similar to vegetables and meat, Python uses data types to handle different kinds of data. Key types covered are:
- String: Characters enclosed in quotes, for text and symbols.
- Float: Numbers with decimals, like 2.1 or 10.5.
- Integer: Whole numbers without decimals, like 0 or 5,000.
- Boolean: True or False values used for logic.
- List: Ordered collections of data enclosed in brackets, like usernames for a file.
These basic types, along with further Python skills, will let you manipulate and analyze data effectively.
Understanding Data Types
- Just like ingredients in a kitchen have categories (vegetables, meat, etc.), data in Python also has different types.
- Each data type determines how Python stores and handles the information.
- Using the correct data type is essential for writing accurate and efficient code.
Common Data Types in Python:
- Strings:
- Represent text data, enclosed in single or double quotes.
- Examples: “Hello, world!”, ‘Python is awesome’, “123” (as text, not a number for calculation)
- Integers:
- Represent whole numbers without decimals.
- Examples: 42, -10, 0
- Used for mathematical operations and counting.
- Floats:
- Represent numbers with decimal points.
- Examples: 3.14159, -2.5, 10.0
- Used for real-world values like measurements and calculations involving decimals.
- Booleans:
- Represent logical values, either True or False.
- Used for decision-making and conditional logic in code.
- Lists:
- Ordered collections of items, enclosed in square brackets.
- Can contain elements of different data types.
- Examples: [“apple”, “banana”, “cherry”], [1, 2, 3], [“Alice”, 25, True]
- Used to group related data together.
Key Points:
- Python automatically assigns a data type to variables based on their initial value.
- You can check the data type of a variable using the
type()
function. - Data types are essential for performing operations and manipulations on data.
- Understanding data types is fundamental to learning Python programming effectively.
Additional Tips:
- Use clear and descriptive variable names to make your code more readable.
- Consider using comments to explain the purpose of variables and code blocks.
- Experiment with different data types to see how they behave in Python.
- Practice writing code to solidify your understanding of data types.
Ready to explore more?
- Learn about operations and functions specific to each data type.
- Discover other data types like tuples, dictionaries, and sets.
- Dive into more complex data structures and algorithms using Python’s powerful capabilities!
Which data type can only have a value of True or False?
Boolean
The Boolean data type can only have a value of True or False. Boolean data is data that can only be one of two values: either True or False.
Our next topic relates to
categorizing data in Python. First, let’s take a moment to consider another environment
where we apply categories. We’ll think about
working in the kitchen. When cooking, we can
categorize the ingredients we use; for example, carrots and
peppers are vegetables, and chicken and beef are meat. These categories are important because they affect how we
handle these ingredients. When working in Python, data types achieve
a similar purpose. A data type is a category for a particular
type of data item. Python uses several data types. We’ll focus on string, float, integer,
Boolean, and list data. When we printed the text “Hello Python!” in our
previous video, this was an example of a string. String data is
data consisting of an ordered sequence
of characters. These characters
could be letters, symbols, spaces,
and even numbers. Numbers in the string data type cannot be used for calculations. All characters in a string must be placed inside
quotation marks. Luckily, Python will tell you by giving you an error message if you forget a quotation mark. Let’s use our code
from before and explore what happens when we leave off the quotation mark. Notice how one of our quotation marks is missing
at the end of the string. When we run this code, we’ll receive an error message. Python also supports
numeric data types as well. When working with numeric data, we don’t put quotation
marks around the data. Numeric data includes
floats and integers. Float data is data consisting of a number
with a decimal point. This includes fractions like 2.1 or 10.5. It also includes
whole numbers with a decimal point like 2.0 or
10.0. Integer data is
data consisting of a number that does not
include a decimal point. Numbers such as 0, -9, and 5,000
are valid integers. So far, we’ve used the print
function to output a string. But it can also be
used with float and integer types
for calculations. Let’s try out an
example of this. First, since it’s good practice, let’s add a comment to explain
the purpose of our code. Then, we’ll tell Python
what to calculate. The output gives us the answer. 1 plus 1 is 2. We can use print with
float and integer data to perform all kinds of mathematical
operations like addition, subtraction, multiplication,
and division. The third data type in
Python is called a Boolean. Boolean data is data that can
only be one of two values: either True or False. Booleans are useful for
logic in our programs. For example, let’s compare numbers and determine the Boolean values
of these comparisons. First, we’ll use the
print function to evaluate if 10 is
less than 5. Then, we’ll also evaluate if 9 is less than 12.
So, what do you think? 10 is not less than 5, but 9 is less than 12, right? Let’s see how Python handles
this when we run it. Python agrees. The first line of output
tells us that it’s False to say 10 is
less than 5. The second tells us it’s True to say 9 is less than 12. We’ll use Boolean more when we start including
conditions in our code. And the last data type
we’ll cover is lists. List data is a data
structure that consists of a collection of
data in sequential form. We’ll create and
print a list that prints all the usernames of the three individuals that have access to a
confidential file. First, we’ll add our comment about an intention
to print this list. After the keyword print, we’ll add our list. We need to place the
list in brackets. After this, we place
the individual items in the list in quotation marks and separate them with commas. Now let’s run this. As expected, we get the list. When it prints, it
still has the brackets. This is just the beginning of
what you can do with lists. As you grow with
your Python skills, you’ll learn about
how you can access and edit individual
items in the list. So that was a brief summary of five major data types in Python: string, integer, float, Boolean, and list. These data types are some of the more common ones you’ll work with as we progress
through our lessons.
Reading: More about data types
Reading
Previously, you explored data types in Python. A data type is a category for a particular type of data item. You focused on string, list, float, integer, and Boolean data. These are the data types you’ll work with in this course. This reading will expand on these data types. It will also introduce three additional types.
String
In Python, string data is data consisting of an ordered sequence of characters. Characters in a string may include letters, numbers, symbols, and spaces. These characters must be placed within quotation marks. These are all valid strings:
- “updates needed”
- “20%”
- “5.0”
- “35”
- “**/**/**”
- “”
Note: The last item (“”), which doesn’t contain anything within the quotation marks, is called an empty string.
You can use the print() function to display a string. You can explore this by running this code:
print("updates needed")
updates needed
The code prints “updates needed”.
You can place strings in either double quotation marks (“”) or single quotation marks (”). The following code demonstrates that the same message prints when the string is in single quotation marks:
print('updates needed')
updates needed
Note: Choosing one type of quotation marks and using it consistently makes it easier to read your code. This course uses double quotation marks.
List
In Python, list data is a data structure that consists of a collection of data in sequential form. Lists elements can be of any data type, such as strings, integers, Booleans, or even other lists. The elements of a list are placed within square brackets, and each element is separated by a comma. The following lists contains elements of various data types:
- [12, 36, 54, 1, 7]
- [“eraab”, “arusso”, “drosas”]
- [True, False, True, True]
- [15, “approved”, True, 45.5, False]
- []
Note: The last item [], which doesn’t contain anything within the brackets, is called an empty list.
You can also use the print() function to display a list:
print([12, 36, 54, 1, 7])
[12, 36, 54, 1, 7]
This displays a list containing the integers 12, 36, 54, 1, and 7.
Integer
In Python, integer data is data consisting of a number that does not include a decimal point. These are all examples of integer data:
- -100
- -12
- -1
- 0
- 1
- 20
- 500
Integers are not placed in quotation marks. You can use the print() function to display an integer. When you run this code, it displays 5:
print(5)
5
You can also use the print() function to perform mathematical operations with integers. For example, this code adds two integers:
print(5 + 2)
7
The result is 7. You can also subtract, multiply, or divide two integers.
Float
Float data is data consisting of a number with a decimal point. All of the following are examples of float data:
- -2.2
- -1.34
- 0.0
- 0.34
Just like integer data, float data is not placed in quotation marks. In addition, you can also use the print() function to display float data or to perform mathematical calculations with float data. You can run the following code to review the result of this calculation:
print(1.2 + 2.8)
4.0
The output is 4.0.
Note: Dividing two integer values or two float values results in float output when you use the symbol /:
print(1/4)
print(1.0/4.0)
0.25
0.25
The output of both calculations is the float value of .25.
If you want to return a whole number from a calculation, you must use the symbol // instead:
print(1//4)
print(1.0//4.0)
0
0.0
It will round down to the nearest whole number. In the case of print(1//4), the output is the integer value of 0 because using this symbol rounds down the calculation from .25 to the nearest whole number. In the case of print(1.0//4.0), the output is the float value of 0.0 because it maintains the float data type of the values in the calculation while also rounding down to the nearest whole number.
Boolean
Boolean data is data that can only be one of two values: either True or False.
You should not place Boolean values in quotation marks. When you run the following code, it displays the Boolean value of True:
print(True)
True
You can also return a Boolean value by comparing numbers. Because 9 is not greater than 10, this code evaluates to False:
print(9 > 10)
False
Additional data types
In this course, you will work with the string, list, integer, float and Boolean data types, but there are other data types. These additional data types include tuple data, dictionary data, and set data.
Tuple
Tuple data is a data structure that consists of a collection of data that cannot be changed. Like lists, tuples can contain elements of varying data types.
A difference between tuple data and list data is that it is possible to change the elements in a list, but it is not possible to change the elements in a tuple. This could be useful in a cybersecurity context. For example, if software identifiers are stored in a tuple to ensure that they will not be altered, this can provide assurance that an access control list will only block the intended software.
The syntax of a tuple is also different from the syntax of a list. A tuple is placed in parentheses rather than brackets. These are all examples of the tuple data type:
- (“wjaffrey”, “arutley”, “dkot”)
- (46, 2, 13, 2, 8, 0, 0)
- (True, False, True, True)
- (“wjaffrey”, 13, True)
Pro tip: Tuples are more memory efficient than lists, so they are useful when you are working with a large quantity of data.
Dictionary
Dictionary data is data that consists of one or more key-value pairs. Each key is mapped to a value. A colon (:) is placed between the key and value. Commas separate key-value pairs from other key-value pairs, and the dictionary is placed within curly brackets ({}).
Dictionaries are useful when you want to store and retrieve data in a predictable way. For example, the following dictionary maps a building name to a number. The building name is the value, and the number is the key. A colon is placed after the key.
{ 1: “East”,
2: “West”,
3: “North”,
4: “South” }
Set
In Python, set data is data that consists of an unordered collection of unique values. This means no two values in a set can be the same.
Elements in a set are always placed within curly brackets and are separated by a comma. These elements can be of any data type. This example of a set contains strings of usernames:
{“jlanksy”, “drosas”, “nmason”}
Key takeaways
It’s important for security analysts who program in Python to be familiar with various Python data types. The data types that you will work with in this course are string, list, integer, float and Boolean. Additional data types include tuple, dictionary, and set. Each data type has its own purpose and own syntax.
Video: Work with variables in Python
- Variables: Like containers, hold data (strings, numbers, etc.) with a descriptive name.
- Creating Variables: Assign a value to a variable using
name = value
. - Calling Variables: Use their name to access the stored data.
- Benefits of Variables: Simplify code, avoid repetition, store complex data.
- Variable Data Types: Can store string, number, Boolean, list, etc.
- Checking Data Type: Use the
type(variable)
function. - Type Errors: Occurs when mixing incompatible data types (e.g., adding string and number).
- Reassigning Variables: Change the stored data with
name = new_value
.
This summary captures the key points of the content and uses concise language. It emphasizes the practical aspects of variables and potential pitfalls like type errors.
Understanding Variables:
- Imagine them as containers that hold data for later use in your code.
- Give them descriptive names (e.g.,
age
,username
,total_score
) to make your code more readable. - They can store different data types: numbers, text, lists, and more.
Creating Variables:
- Use the assignment operator
=
to create a variable and assign a value to it:
Python
name = "Alice"
age = 30
is_active = True
Calling Variables:
- Use the variable name to access the stored data:
Python
print("Hello, " + name + "!")
print("You are", age, "years old.")
Reassigning Variables:
- Change the value stored in a variable by using
=
again:
Python
name = "Bob" # Now the variable 'name' holds "Bob"
Key Points:
- Data Types Matter: Be mindful of the data type each variable holds to avoid errors.
- Check Data Types: Use
type(variable)
to check the data type. - Type Errors: Mixing incompatible data types (e.g., adding a string and a number) leads to errors.
- Best Practices:
- Use meaningful variable names.
- Comment your code to explain variable usage.
- Avoid overly complex variable names.
Common Operations with Variables:
- Printing:
print(variable_name)
- Combining strings:
full_name = first_name + " " + last_name
- Mathematical operations:
result = value1 + value2
,difference = value1 - value2
, etc. - Comparisons:
is_equal = value1 == value2
,is_greater = value1 > value2
, etc.
Practice and Explore:
- Experiment in a Python environment to create, modify, and use variables.
- Try different data types and operations.
- Apply variables to solve simple problems.
- Gradually tackle more complex examples.
Remember: Working with variables is a fundamental skill in Python programming. Mastering it will empower you to write more dynamic and versatile code!
Which of the following lines of code assigns the variable username a value of "jrafael"?
username = “jrafael”
The code username = “jrafael” assigns the variable username a value of “jrafael”. The syntax for assigning a variable requires a name for the variable, then an equals sign (=), and finally the value for the variable.
Previously, we
compared data types to the categories we have for different ingredients
we use when cooking, like vegetables or meat. Some of these
categories we use for data types are the string, float, integer, Boolean, and list. Now, let’s make another comparison. When
working in the kitchen, we also use
storage containers. These containers can hold
a lot of different things. After one meal, a
container might hold rice, and after another, it could hold something
different, like pasta. In a similar way, in
Python, we have variables. A variable is a container
that stores data. To create a variable, you need a name for it. Then,
you add an equals sign and then an object
to store in it. Creating a variable is
often called assignment. The best practice for
naming variables is to make the names relevant to what
they’re being used for. Let’s use a variable
to store a device ID. We’ll name our
variable device_ID, add the equals sign, and then
assign it a value of h32rb17. Because the data type for
this variable is a string, we’ll place that value in quotation marks.
Let’s run the code. Our variable is now
saved into Python. The purpose of
creating variables is to use them
later in the code. Using variables can also be
referred to as “calling” them. To call a variable,
you type its name. This tells Python to use the object that the
variable contains. Let’s add to the code we’ve just written and call a variable. Let’s just have it
print the variable. To do this, we use the
print function and ask it to print the value stored in the
device ID variable. When using a variable
in our print function, we don’t use quotation marks. This time, when we run
it, something happens. Python prints h32rb17
to the screen. Let’s add one more line of code to demonstrate
the difference between printing a variable
and printing a string. We’ll ask Python to print a string that contains
another device ID: m50pi31. Because this is string
data and not a variable, we place it in quotation marks. Now, let’s run the code
and see the results. It executes both
print statements. The first reads the
variable and prints the value it contains: h32rb17. And the second reads the specified
string and prints m50pi31. But if we could use
the string directly, why do we need variables? Well, we often use variables to simplify
our code or make it cleaner and easier to read. Or if we needed a very
long string or number, storing it in a variable
would let us use it throughout our code
without typing it all out. In the previous example, the variable stored
string data, but variables can store a
variety of data types. Variables have the data type of the object currently
storing them. If you’re unsure about the data type stored
inside of a variable, you can use the type function. The type function is a function that returns the
data type of its input. Let’s use the type
function in Python. We’ll start by creating our variable. Then, we’ll add a line of code that
includes the type function. This line asks Python to
tell us the data type of the device ID variable and to assign this to a new
variable called data_type. After this, we can print the data_type
variable to the screen. Perfect! Python tells us that the value that device
ID contains a string. When working with variables, it’s important to keep
track of their data types. If you don’t, you could
get a type error. A type error is an error that results from
using the wrong data type. For example, if you try to
add a number and a string, you will get a type error because Python cannot combine those two data types together. It can only add two
strings or two numbers. Let’s demonstrate a type error. First, we’ll reuse our device ID variable that
stores a string value. Then, we’ll define
another variable called number and assign
an integer value to it. Let’s add a print statement
that outputs the sum of these variables, and
then we’ll run this. We ended up with an error because we cannot add
a string to a number. Let’s cover one more topic
related to variables. Earlier, we mentioned how
variables are like containers. What they hold can change. After we define a variable, we can always change the
object inside of it. This is called reassignment. Reassigning a variable is very similar to assigning it
in the first place. Let’s try this out and
reassign a variable. We’ll start by assigning
the same string of h32rb17 to our
variable device_ID. We will also include a line of code to print this variable. Now, let’s try
reassigning the variable. We type this variable’s
name, add an equals sign, and then add the new object. In this case, we’ll
use the string n73ab07 as the new device ID. We’ll also ask Python to
print the variable again. Let’s see what happens
when we run this. Python prints two
lines of output. The first print statement
came before reassignment, so it first prints the
string of h32rb17. But the second print statement
came after it changed. That’s why the second
output to the screen is the string n73ab07. With this code, we
reassigned a variable with a string value to
another string value, but it’s also
possible to reassign a variable to a value
of another data type. For instance, we can
reassign a variable with a string value
to an integer value. Variables are an
essential part of Python, and as we progress
through this course, you’ll become more
familiar with them.
Reading: Assign and reassign variables in Python
Reading
Previously, you’ve explored variables and how to assign and reassign them in Python. In this reading, you’ll expand your understanding of these topics. You’ll also learn about the general practice of naming variables so that you can avoid syntax errors and improve code readability.
What are variables?
In a programming language, a variable is a container that stores data. It’s a named storage location in a computer’s memory that can hold a value. It stores the data in a particular data type, such as integer, string, or Boolean. The value that is stored in a variable can change.
You can think of variables as boxes with labels on them. Even when you change the contents of a box, the label on the box itself remains the same. Similarly, when you change the value stored in a variable, the name of the variable remains the same.
Security analysts working in Python will use a variety of variables. Some examples include variables for login attempts, allow lists, and addresses.
Working with variables
In Python, it’s important to know both how to assign variables and how to reassign them.
Assigning and reassigning variables
If you want to create a variable called username and assign it a value of “nzhao”, place the variable to the left of the equals sign and its value to the right:
# Assign ‘username’
username = “nzhao”
If you later reset this username to “zhao2”, you still refer to that variable container as username.
# Reassign ‘username’
username = “zhao2”
Although the contents have changed from “nzhao” to “zhao2”, the variable username remains the same.
Note: You must place “nzhao” and “zhao2” in quotation marks because they’re strings. Python automatically assigns a variable its data type when it runs. For example, when the username variable contains the string “nzhao”, it’s assigned a string data type.
Assigning variables to variables
Using a similar process, you can also assign variables to other variables. In the following example, the variable username is assigned to a new variable old_username:
# Assign a variable to another variable
username = “nzhao”
old_username = username
Because username contains the string value of “nzhao” and old_username contains the value of username, old_username now contains a value of “nzhao”.
Putting it together
The following code demonstrates how a username can be updated. The username variable is assigned an initial value, which is then stored in a second variable called old_username. After this, the username variable is reassigned a new value. You can run this code to get a message about the previous username and the current username:
username = "nzhao"
old_username = username
username = "zhao2"
print("Previous username:", old_username)
print("Current username:", username)
Previous username: nzhao
Current username: zhao2
Best practices for naming variables
You can name a variable almost anything you want, but there are a few guidelines you should follow to ensure correct syntax and prevent errors:
- Use only letters, numbers, and underscores in variable names. Valid examples: date_3, username, interval2
- Start a variable name with a letter or underscore. Do not start it with a number. Valid examples: time, _login
- Remember that variable names in Python are case-sensitive. These are all different variables: time, Time, TIME, timE.
- Don’t use Python’s built-in keywords or functions for variable names. For example, variables shouldn’t be named True, False, or if.
Additionally, you should follow these stylistic guidelines to make your code easier for you and other security analysts to read and understand:
- Separate two or more words with underscores. Valid examples: login_attempts, invalid_user, status_update
- Avoid variables with similar names. These variables could be easily confused with one another: start_time, starting_time, time_starting.
- Avoid unnecessarily long names for variables. For instance, don’t give variables names like variable_that_equals_3.
- Names should describe the data and not be random words. Valid examples: num_login_attempts, device_id, invalid_usernames
Note: Using underscores to separate multiple words in variables is recommended, but another convention that you might encounter is capitalizing the first letter of each word except the first word. Example: loginAttempt
Key takeaways
It’s important for security analysts to have a fundamental understanding of variables. Variables are containers of data. They are assigned values and can also be reassigned other values or variables. It’s helpful to remember the best practices for naming variables in order to create more functional, readable code.
Lab: Exemplar: Assign Python variables
Practice Quiz: Test your knowledge: Core Python components
Which of the following data items are float data? Select all that apply.
15.0, -2.11
15.0 and -2.11 are examples of float data. Float data is data consisting of a number with a decimal point.
What code displays the data type of the variable username?
username = ["elarson", "bmoreno", "tshah"]
data_type = type(username)
print(data_type)
The data type of the variable username is displayed by the following code:
username = [“elarson”, “bmoreno”, “tshah”]
data_type = type(username)
print(data_type)
The type() function returns the data type of its input. In this case, that input is the username variable, which contains a list. This data type is assigned to the data_type variable and is displayed through the print() function.
In the following code, what is the data type of login_success?
login_success = [“success”, “success”, “fail”, “success”]
List
List is the data type of login_success. List data is a data structure that consists of a collection of data in sequential form. Lists are placed in brackets.
What is the output of the following code?
failed_attempts = 3
failed_attempts = 4
print(failed_attempts)
4
The output of the code is 4. This code initially assigns the value of failed_attempts to 3, but it then reassigns the value of this variable to 4 before printing it. The print() function is placed after this and displays this reassigned value of 4.
Conditional and iterative statements
Video: Conditional statements in Python
– Automation: – Using technology to reduce manual effort for repetitive tasks. – Conditional statements are crucial for automating tasks in code.
– if Statements: – Begin with if
followed by a condition. – If the condition is True, the indented code block executes. – Example: if failed_attempts > 5:
– Header and Body: – The first line (condition) is the header. – The indented code after it is the body.
– Comparison Operators: – Used to define conditions: – ==
(equal to) – !=
(not equal to) – >
(greater than) – <
(less than) – >=
(greater than or equal to) – <=
(less than or equal to)
– Double Equals Sign (==
): – Checks for value equality. – Example: if operating_system == "OS 2":
– else Statements: – Execute code when the if
condition is False. – Follow the if
statement and end with a colon. – Example: else:
– Code Structure: – Indentation is essential in Python to define code blocks.
– Key Takeaways: – Conditional statements allow for decision-making in code. – Use if
and else
to control program flow based on conditions. – Choose appropriate comparison operators for different scenarios. – Proper indentation ensures code clarity and execution.
Welcome to the World of Conditional Logic in Python!
In this tutorial, you’ll learn how to make your Python code think for itself, deciding what actions to take based on different conditions.
Here’s what we’ll cover:
- Introducing Automation and Conditional Statements
- Mastering the
if
Statement - Understanding Comparison Operators
- Checking for Equality with
==
- Handling “Not Equal” with
!=
- Introducing the
else
Statement - Indentation: Python’s Way of Organizing Code
- Practice Examples and Challenges
Get ready to:
- Write code that makes decisions based on certain criteria.
- Control the flow of your programs for more dynamic behavior.
- Practice conditional statements with hands-on examples.
- Build a solid foundation for writing more complex and intelligent Python code!
Let’s dive in and explore the power of conditional statements!
Which operator can be used in a condition to evaluate whether the value contained in a login_attempts variable matches a value of 5?
==
The == operator evaluates whether two objects match and can be used in a condition to evaluate whether the value contained in a login_attempts variable matches a value of 5. This condition can be placed in an if statement header as if login_attempts == 5.
Previously, we discussed how to store
different data types in variables. Now we’ll begin to move into
the concept of automation, so we can create exciting actions with code. Automation is the use of
technology to reduce human and manual effort to perform common and
repetitive tasks. It allows computers to do these
tasks for us so that we may get back more time in
our lives to do other activities. Conditional statements are important for
automation. A conditional statement is
a statement that evaluates code to determine if it meets
a specified set of conditions. The keyword if is important
in conditional statements. if starts a conditional statement.
After this keyword, we then specify the condition that must
be met and what will happen if it is. We use if statements every day.
For example, if it’s cold outside, then we’ll wear a jacket. Or
if it’s raining, we’ll bring an umbrella. if statements are structured with
the condition we want to evaluate and the action that Python will
perform if this condition is met. Python always evaluates if
the condition is True or False, and if it’s True,
it performs the specific action. Let’s explore an example of this.
We’ll instruct Python to print an “account locked” message anytime the failed log-in
attempts are greater than five. Our keyword if tells Python to start
a conditional statement. After this, we indicate the condition
we want to check for. In this case, we’re checking if the user
has more than five failed log-in attempts. Notice how we’re using a variable
called failed_attempts. In our complete code, we will have assigned a value to
failed_attempts prior to this if a statement. After this condition,
we always place a colon. This signals that what follows is what we
want to happen when the condition is met. In this case, when the user has more
than five failed log-in attempts, it prints a message that
the account is locked. In Python,
this message should always be indented at least one space in order to execute
only when the condition is true. It’s common to call this first line
the “header” and to call the actions that happen when
the condition is met the “body.” This condition was based on a variable
being greater than a specific number, but we can define our condition
using a variety of operators. For example, we can also check
if something is “less than” a specified value, or
we can check if it’s “greater than” or “equal to” or “less than or
equal to” the value. We can also compare if
something is equal to a value. When we do this inside a conditional,
we need to use a special syntax. It’s not just the equals sign,
but a double equals. The double equals sign is an important
operator often used in conditional statements. A double equals evaluates
whether two objects match. It assigns a Boolean value of True when
they match and False when they don’t. There’s one more operator we should
discuss. An exclamation mark followed by an equals sign represents
the condition of “not equal.” This operator for “not equal” evaluates
whether two objects are different. It assigns a Boolean value of True when they don’t match and
False when they match. Let’s more closely investigate an example
that uses the double equals sign. We’ll focus on an example that prints an “updates needed” message when a particular
operating system is running. Here, we’ve created a condition
that checks if a device’s operating system matches a specific string that
identifies this operating system. To do this, we’ll need to use
the double equals sign in our condition. When it matches, our program will print
a message that there are updates needed. The operating_system variable is on
the left of the double equals sign. The string “OS 2” is on the right. If the condition evaluates to True, it performs the action that is
indented in the next line of code. Here, if the operating_system is OS 2,
it will print “updates needed.” If it’s False, the message will not print. Notice how this line is indented.
This tells Python that the task depends on the if
statement evaluating to True. Now let’s write code that incorporates
this conditional and get the results. Before we write the conditional statement, we need to assign a value to
our operating system variable. We’ll make this value the same as
the operating system that we’ll check for in the conditional. Next, we’ll write the condition for
our if statement and use the double equals sign to check if the
operating_system variable is equivalent to OS 2. Now we’ll type the action that we’ll
execute if the condition on the previous line evaluates to True. We’ll tell Python to print
an “updates needed” message. Since we set our operating_system variable
to OS 2, the print statement will execute. Okay, let’s run this. As expected, it printed
“updates needed” because the value assigned to the operating_system
variable was equal to OS 2. Sometimes, we want our conditional
statements to execute another set of instructions in the event
our first condition isn’t True. In our example, not being True means that the device is running
an operating system other than OS 2. This is when we need to incorporate the else keyword into our
conditional statements. else precedes a code section that only
evaluates when all conditions that precede it within the conditional
statement evaluate to False. else statements always follow
an if statement and end in a colon. Let’s use our previous conditional and
add an else statement to it. We’ve included the same if statement, but this time,
we set the operating system variable to contain a different operating system,
OS 3. Because this doesn’t match
the value in the condition of the if statement,
the “updates needed” message won’t print. But we can add an else statement and
tell it to do something else instead. We type the else keyword followed by
a colon.Then we indent the next line and tell it to print a “no
updates needed” message. When we’d run this code, it processes
the else statement after the if statement. Since our if statement
will evaluate to False, it then moves on to the “else” instruction. Let’s try it. As expected, it only prints the message
“no updates needed.” Great work! Now we’ve covered how
to use if and how to use else. Using conditional statements allows you
to incorporate logic into your code.
Reading: More on conditionals in Python
Reading
Previously, you explored conditional statements and how they’re useful in automating tasks in Python. So far, you’ve focused on the if and else keywords. In this reading, you’ll review these and learn another keyword, elif. You’ll also learn how you can apply the and, or, and not operators to your conditions.
How conditional statements work
A conditional statement is a statement that evaluates code to determine whether it meets a specific set of conditions. When a condition is met, it evaluates to a Boolean value of True and performs specified actions. When the condition isn’t met, it evaluates a Boolean value of False and doesn’t perform the specified actions.
In conditional statements, the condition is often based on a comparison of two values. This table summarizes common comparison operators used to compare numerical values.
operator | use |
---|---|
> | greater than |
< | less than |
>= | greater than or equal to |
<= | less than or equal to |
== | equal to |
!= | not equal to |
Note: The equal to (==) and not equal to (!=) operators are also commonly used to compare string data.
if statements
The keyword if starts a conditional statement. It’s a necessary component of any conditional statement. In the following example, if begins a statement that tells Python to print an “OK” message when the HTTP response status code equals 200:
if status == 200:
print("OK")
This code consists of a header and a body.
The header of an if statement
The first line of this code is the header. In the header of an if statement, the keyword if is followed by the condition. Here, the condition is that the status variable is equal to a value of 200. The condition can be placed in parentheses:
if (status == 200):
print("OK")
In cases like this one, placing parentheses around conditions in Python is optional. You might want to include them if it helps you with code readability. However, this condition will be processed the same way if written without parentheses.
In other situations, because Python evaluates the conditions in parentheses first, parentheses can affect how Python processes conditions. You will read more about one of these in the section of this reading on not.
Note: You must always place a colon (:) at the end of the header. Without this syntax, the code will produce an error.
The body of an if statement
After the header of an if statement comes the body of the if statement. This tells Python what action or actions to perform when the condition evaluates to True. In this example, there is just one action, printing “OK” to the screen. In other cases, there might be more lines of code with additional actions.
Note: For the body of the if statement to execute as intended, it must be indented further than the header. Additionally, if there are multiple lines of code within the body, they must all be indented consistently.
Continuing conditionals with else and elif
In the previous example, if the HTTP status response code was not equal to 200, the condition would evaluate to False and Python would continue with the rest of the program. However, it’s also possible to specify alternative actions with else and elif.
else statements
The keyword else precedes a code section that only evaluates when all conditions that precede it within the conditional statement evaluate to False.
In the following example, when the HTTP response status code is not equal to 200, it prints an alternative message of “check other status”:
if status == 200:
print("OK")
else:
print("check other status")
Note: Like with if, a colon (:) is required after else, and the body that follows the else header is indented.
elif statements
In some cases, you might have multiple alternative actions that depend on new conditions. In that case, you can use elif. The elif keyword precedes a condition that is only evaluated when previous conditions evaluate to False. Unlike with else, there can be multiple elif statements following if.
For example, you might want to print one message if the HTTP response status code is 200, one message if it is 400, and one if it is 500. The following code demonstrates how you can use elif for this:
if status == 200:
print("OK")
elif status == 400:
print("Bad Request")
elif status == 500:
print("Internal Server Error")
Python will first check if the value of status is 200, and if this evaluates to False, it will go onto the first elif statement. There, it will check whether the value of status is 400. If that evaluates to True, it will print “Bad Request”, but if it evaluates to False, it will go on to the next elif statement.
If you want the code to print another message when all conditions evaluate to False, then you can incorporate else after the last elif. In this example, if it reaches the else statement, it prints a message to check the status:
if status == 200:
print("OK")
elif status == 400:
print("Bad Request")
elif status == 500:
print("Internal Server Error")
else:
print("check other status")
Just like with if and else, it’s important to place a colon (:) after the elif header and indent the code that follows this header.
Note: Python processes multiple elif statements differently than multiple if statements. When it reaches an elif statement that evaluates to True, it won’t check the following elif statements. On the other hand, Python will run all if statements.
Logical operators for multiple conditions
In some cases, you might want Python to perform an action based on a more complex condition. You might require two conditions to evaluate to True. Or, you might require only one of two conditions to evaluate to True. Or, you might want Python to perform an action when a condition evaluates to False. The operators and, or, and not can be used in these cases.
and
The and operator requires both conditions on either side of the operator to evaluate to True. For example, all HTTP status response codes between 200 and 226 relate to successful responses. You can use and to join a condition of being greater than or equal to 200 with another condition of being less than or equal to 226:
if status >= 200 and status <= 226:
print("successful response")
When both conditions are True, then the “successful response” message will print.
or
The or operator requires only one of the conditions on either side of the operator to evaluate to True. For example, both a status code of 100 and a status code of 102 are informational responses. Using or, you could ask Python to print an “informational response” message when the code is either 100 or 102:
if status == 100 or status == 102:
print("informational response")
Only one of these conditions needs to be met for Python to print the message.
not
The not operator negates a given condition so that it evaluates to False if the condition is True and to True if it is False. For example, if you want to indicate that Python should check the status code when it’s something outside of the successful range, you can use not:
if not(status >= 200 and status <= 226):
print("check status")
Python first checks whether the value of status is greater than or equal to 200 and less than or equal to 226, and then because of the operator not, it inverts this. This means it will print the message if status is less than 200 or greater than 226.
Note: In this case, the parentheses are necessary for the code to apply not to both conditions. Python will evaluate the conditions within the parentheses first. This means it will first evaluate the conditions on either side of the and operator and then apply not to both of them.
Key takeaways
It’s important for security analysts to be familiar with conditional statements. Conditional statements require the if keyword. You can also use else and elif when working with conditionals to specify additional actions to take. The logical operators and, or, and not are also useful when writing conditionals.
Lab: Activity: Create a conditional statement
Lab: Exemplar: Create a conditional statement
Video: For loops
Summary of Iterative Statements (Loops) in Python:
Key Points:
- Automation and Loops: Computers outperform humans in repetitive tasks, where focus and energy can be lost. Loops automate such tasks by repeating code blocks.
- Types of Loops: We explored
for
loops in this video, and will coverwhile
loops later. for
Loop Syntax:- Starts with
for
keyword. - Has two main parts:
- Loop header: Contains
for
keyword, loop variable, and sequence to iterate through, ending with a colon. - Loop body: Indented lines with code to be repeated, representing the actions within the loop.
- Loop header: Contains
- Starts with
- Loop Variable:
- Controls loop iterations; often named
i
but can be any relevant name. - Exists only within the loop, not affecting code outside.
- Controls loop iterations; often named
- Sequence Iteration:
- Loop executes for each element in the specified sequence (e.g., a list).
- Repeating a Specific Number of Times:
range
function generates a sequence of numbers.range(start, stop)
defines a sequence (excludingstop
).- Combine
for
andrange
to repeat code a specific number of times.
- Example:
for i in range(10): print("Cannot connect to destination")
prints the message 10 times.
Overall:
- Loops automate repetitive tasks, saving time and effort.
for
loops iterate through sequences, executing code for each element.- Combining
for
andrange
allows precise control over repetition count.
Welcome to the Looping Playground!
In this tutorial, you’ll discover how to make your Python code repeat tasks efficiently, saving you time and effort.
Get ready to:
- Unleash the power of loops to automate repetitive processes.
- Master the
for
loop and its syntax to iterate through sequences. - Explore the
range
function to control the number of repetitions. - Practice with hands-on examples to solidify your understanding.
- Lay the groundwork for creating more complex and efficient Python programs!
Let’s dive into the world of loops!
1. Automation and Loops: Why Bother with Repetition?
- Understand why loops are essential for automating repetitive tasks.
- Discover how computers excel at handling tasks that would be tedious for humans.
- Appreciate the time and effort saved through efficient looping techniques.
2. Introducing the for
Loop: Your First Looping Tool
- Learn the basic structure of a
for
loop, including the loop header and body. - Grasp the concept of a loop variable and how it controls iterations.
- Practice iterating through sequences like lists and strings using
for
loops.
3. The range
Function: Counting and Repeating with Ease
- Generate sequences of numbers using the
range
function. - Understand how to specify start and stop values for precise control.
- Combine
for
loops withrange
to repeat code a specific number of times.
4. Hands-On Examples: Time to Get Loopy!
- Practice writing
for
loops to accomplish various tasks, such as:- Printing elements of a list or string
- Performing calculations multiple times
- Creating patterns or sequences
- Building simple games or simulations
5. Troubleshooting and Tips: Looping with Confidence
- Learn common pitfalls to avoid when working with loops.
- Develop debugging strategies to identify and fix loop errors.
- Explore tips for writing clear, concise, and efficient loop code.
6. Next Steps: Expanding Your Looping Horizons
- Preview upcoming topics like
while
loops and nested loops. - Discover how to break out of loops with
break
statements. - Explore conditional statements within loops for more complex control flow.
We just learned about conditional statements
and how they can be developed to allow computers
to make decisions. But sometimes we need
our programs to simply count or perform a task
over and over again. When it comes to tasks
that are tedious, it’s normal for humans to
lose focus and energy. It’s in situations
like these where computers can be
especially helpful. In this video, we’ll
examine how computers can perform repetitive tasks
using iterative statements. An iterative statement is code that repeatedly executes
a set of instructions. Iterative statements are
also referred to as “loops.” Setting up a loop allows
us to repeatedly use a line of code without having
to type it multiple times. Before discussing the syntax, let’s run a loop so you can
experience what happens. Notice how this code printed
all the numbers in the list with only one print
statement. That’s a loop. There are two types of
loops we’ll explore: for loops and while loops. We just ran a for loop, and we’ll continue to focus on
them in this video. Later, we’ll explore
while loops. for loops repeat code for
a specified sequence. An example of this
would be using a for loop to print
every item in a list. For loops begin with
the keyword for. for signals the
beginning of a for loop. Similar to conditional
statements, iterative statements
consist of two main parts. The parts of a loop are the loop header
and the loop body. Let’s examine the
for loop we just ran and use that to
explore these parts. The loop header is the
line that contains the for keyword and
ends with a colon. It tells Python to start a loop. It consists of the for keyword, a loop variable, and the sequence the loop
will iterate through. The loop variable is
a variable that is used to control the
iterations of a loop. The loop variable comes
directly after for. A common name for
it is the letter i, but you can give it any
other name you want. In for loops, this
temporary variable is only used within the loop and not outside of it in the
rest of the code. The loop variable is followed by the in operator and the sequence the loop
will iterate through. In this example,
this sequence is a list containing numbers
from one through four. It runs each of these numbers
through a specified action. We need to remember
to put a colon at the end of the loop header
to introduce this code. The loop body refers to the indented lines
after the loop header. This represent the actions that are repeated while
the loop iterates. In this case, it will print
each number in the list: first one, and then
two, and so on. Another important use of for loops is to repeat
a specific process a set number of times. This is done through combining it with the range function. The range function generates
a sequence of numbers. As an example, range from zero to 10 sets a sequence
that goes from zero, one, two all the way up
until the number nine. When we use range, we start counting at the
number in the first position; in this case, zero. Then when we reach the number
in the second position, it tells us where to stop. That number is excluded. In this case, where
the number is 10, the sequence only
goes up until nine. An important detail
about the range function is that if we don’t
provide a start point, it automatically
starts from zero. 10 represents the stop point. Since the stop
point is excluded, the numbers included in
the sequence start at zero and end at nine. A sequence that starts
at zero and ends at nine will iterate 10 times. Let’s run a for loop that incorporates the range function. We’ll use range to ask Python to repeat an action 10 times. Then we’ll indicate the
action we want to repeat. This action is printing
an error message that indicates “cannot connect
to the destination.” Let’s run this. Using
a for loop with the range function
allowed us to repeat the same error message 10 times, instead of typing it over
and over again ourselves. In this video, we learned about the syntax
and structure of iterative statements and worked with for loops as an example. In the next video, we’ll
cover another type of iterative statement:
the while loop.
Video: While loops
– While Loops: Repetition Based on Conditions: – Execute code repeatedly as long as a specified condition remains True. – Provide more flexible control over the number of iterations than for
loops.
– Structure of a While Loop: – Header: – while
keyword. – Condition that evaluates to True or False. – Colon. – Body: – Indented block of code to be executed repeatedly.
– Loop Variable: – Controls the number of iterations. – Must be defined and initialized before the while
loop.
– Condition: – Contains the loop variable. – Loop continues if True, stops if False.
– Example: python time = 0 while time <= 10: # Condition: time is less than or equal to 10 print(time) time += 2 # Increment time by 2 each iteration
– Practical Example: – Limiting device connections using a while
loop.
– Key Points: – While loops are essential for tasks that require repetition based on conditions. – Carefully define and update the loop variable to avoid infinite loops. – Ensure the condition eventually becomes False to terminate the loop. – Combine while
loops with conditional statements for more complex logic.
– Remember: – Choose for
loops for iterating through sequences. – Choose while
loops for repetition based on conditions.
Welcome to the World of While Loops!
In this tutorial, you’ll learn how to create loops that keep going as long as a condition is true, giving you flexible control over your code’s execution.
Get ready to:
- Master the structure and syntax of while loops.
- Understand the role of loop variables and conditions.
- Write while loops to handle various tasks.
- Avoid common pitfalls like infinite loops.
- Combine while loops with other elements for more complex logic.
Here’s what we’ll cover:
- Introducing While Loops: Repetition with a Twist
- Anatomy of a While Loop: Breaking It Down
- Loop Variables: Controlling the Iterations
- Conditions: The Heart of the Loop
- Hands-On Examples: Putting While Loops to Work
- Best Practices and Avoiding Pitfalls
- Combining While Loops with Conditional Statements
- When to Use While Loops vs. For Loops
Let’s dive in and explore the power of while loops!
Previously, we introduced
iterative statements in Python and focused
on for loops. An iterative statement is code that repeatedly executes a
set of instructions. In this video, we’ll explore another type of iterative
statement: the while loop. When we used for loops, the code repeatedly executed based on a specified sequence. While loops still
repeatedly execute, but this repetition is
based on a condition. As long as the
condition is true, the loop continues to execute. But when it becomes false, the while loop stops. This while loop, for example, sets a condition where
the variable time must be less than
or equal to 10. This means it will keep running until the variable time
is greater than 10. Similar to the for loop, a while loop has a header. It consists of the keyword while, the condition,
and a colon. The while loop starts
with the keyword while. The keyword while signals the
beginning of a while loop and is followed by the
condition that evaluates to a Boolean value of
either True or False. The condition contains
the loop variable. This variable is used to control the number
of loop iterations. However, there is an
important distinction in the variables used in
for and while loops. With while loops,
the variable isn’t created within the
loop statement itself. Before writing the while loop, you need to assign the variable. Then you’ll be able to
reference it in the loop. When the condition
containing the loop variable evaluates to True,
the loop iterates. If it does not, then the loop stops. This condition will
evaluate to True while the variable time is less
than or equal to 10. Finally, the loop header
ends with a colon. Just like a for loop, a while loop has an
indented body that consists of the actions to
take while the loop iterates. The intention of this code is to print the value of a
variable that represents the time and increase
its value by two, until it becomes
greater than 10. This means the first
action in this while loop is to simply print the current value of
the time variable. Since while loops do not include a sequence
to iterate through, we have to explicitly define how the loop variable changes in the body of the while loop. For example, in this while loop, we increase the loop variable time by two every iteration. This is because we only want to print the time
every two minutes, so this while loop
prints out all even numbers less
than or equal to 10. Now that we know the
basics of while loops, let’s explore a
practical example. Imagine we have a limitation on how many devices a
user can connect to. We can use a while loop to
print a message when the user has reached their maximum
number of connected devices. Let’s create a while
loop for this. Before we start our while loop, we need to assign values
to two variables. First, we’ll set the maximum value of
connected devices to five. Then, we’ll set our
loop variable. We’ll use i for this and
set it to a value of one. Unlike with for loops, with while loops, we set this variable
outside of the loop. Next, we’ll create the
header of our while loop. In this case, the
condition is that the first variable is less
than the second variable. Those variables are the loop
variable “i” and max_devices. Since we know the value
of max_devices is five, we can understand that
this loop will run as long as the current value
of “i” is less than five. Then we indicate what we
want our while loop to do. Because this loop runs as long as the user can still
connect to devices, we’ll first have it print a “user can still connect to
additional devices” message. After this, with each iteration,
we’ll increment i by one. When the loop repeats, it will use the new
value of the i variable. Python will exit the loop when i is no longer less than five. Let’s also print a message
when this happens. We stop indenting because this next action occurs
outside of the loop. Then we’ll print “user has reached maximum number
of connected devices.” We’re ready to run this. Because of the loop, the first message prints
a total of four times. The loop stops when the value
of i increments to five. At this point, it exits the loop and prints
the second message. When you combine this new
understanding of for and while loops with
what you already know about conditional
statements and variables, you have a lot of options
in Python. Great work!
Reading: More on loops in Python
Reading
Previously, you explored iterative statements. An iterative statement is code that repeatedly executes a set of instructions. Depending on the criteria, iterative statements execute zero or more times. We iterated through code using both for loops and while loops. In this reading, you’ll recap the syntax of loops. Then, you’ll learn how to use the break and continue keywords to control the execution of loops.
for loops
If you need to iterate through a specified sequence, you should use a for loop.
The following for loop iterates through a sequence of usernames. You can run it to observe the output:
for i in ["elarson", "bmoreno", "tshah", "sgilmore"]:
print(i)
elarson
bmoreno
tshah
sgilmore
The first line of this code is the loop header. In the loop header, the keyword for signals the beginning of a for loop. Directly after for, the loop variable appears. The loop variable is a variable that is used to control the iterations of a loop. In for loops, the loop variable is part of the header. In this example, the loop variable is i.
The rest of the loop header indicates the sequence to iterate through. The in operator appears before the sequence to tell Python to run the loop for every item in the sequence. In this example, the sequence is the list of usernames. The loop header must end with a colon (:).
The second line of this example for loop is the loop body. The body of the for loop might consist of multiple lines of code. In the body, you indicate what the loop should do with each iteration. In this case, it’s to print(i), or in other words, to display the current value of the loop variable during that iteration of the loop. For Python to execute the code properly, the loop body must be indented further than the loop header.
Note: When used in a for loop, the in operator precedes the sequence that the for loop will iterate through. When used in a conditional statement, the in operator is used to evaluate whether an object is part of a sequence. The example if “elarson” in [“tshah”, “bmoreno”, “elarson”] evaluates to True because “elarson” is part of the sequence following in.
Looping through a list
Using for loops in Python allows you to easily iterate through lists, such as a list of computer assets. In the following for loop, asset is the loop variable and another variable, computer_assets, is the sequence. The computer_assets variable stores a list. This means that on the first iteration the value of asset will be the first element in that list, and on the second iteration, the value of asset will be the second element in that list. You can run the code to observe what it outputs:
computer_assets = ["laptop1", "desktop20", "smartphone03"]
for asset in computer_assets:
print(asset)
laptop1
desktop20
smartphone03
Note: It is also possible to loop through a string. This will return every character one by one. You can observe this by running the following code block that iterates through the string “security”:
string = "security"
for character in string:
print(character)
s
e
c
u
r
i
t
y
Using range()
Another way to iterate through a for loop is based on a sequence of numbers, and this can be done with range(). The range() function generates a sequence of numbers. It accepts inputs for the start point, stop point, and increment in parentheses. For example, the following code indicates to start the sequence of numbers at 0, stop at 5, and increment each time by 1:
range(0, 5, 1)
Note: The start point is inclusive, meaning that 0 will be included in the sequence of numbers, but the stop point is exclusive, meaning that 5 will be excluded from the sequence. It will conclude one integer before the stopping point.
When you run this code, you can observe how 5 is excluded from the sequence:
for i in range(0, 5, 1):
print(i)
0
1
2
3
4
You should be aware that it’s always necessary to include the stop point, but if the start point is the default value of 0 and the increment is the default value of 1, they don’t have to be specified in the code. If you run this code, you will get the same results:
for i in range(5):
print(i)
0
1
2
3
4
Note: If the start point is anything other than 0 or the increment is anything other than 1, they should be specified.
while loops
If you want a loop to iterate based on a condition, you should use a while loop. As long as the condition is True, the loop continues, but when it evaluates to False, the while loop exits. The following while loop continues as long as the condition that i < 5 is True:
i = 1
while i < 5:
print(i)
i = i + 1
1
2
3
4
In this while loop, the loop header is the line while i < 5:. Unlike with for loops, the value of a loop variable used to control the iterations is not assigned within the loop header in a while loop. Instead, it is assigned outside of the loop. In this example, i is assigned a starting value of 1 in a line preceding the loop.
The keyword while signals the beginning of a while loop. After this, the loop header indicates the condition that determines when the loop terminates. This condition uses the same comparison operators as conditional statements. Like in a for loop, the header of a while loop must end with a colon (:).
The body of a while loop indicates the actions to take with each iteration. In this example, it is to display the value of i and to increment the value of i by 1. In order for the value of i to change with each iteration, it’s necessary to indicate this in the body of the while loop. In this example, the loop iterates four times until it reaches a value of 5.
Integers in the loop condition
Often, as just demonstrated, the loop condition is based on integer values. For example, you might want to allow a user to log in as long as they’ve logged in less than five times. Then, your loop variable, login_attempts, can be initialized to 0, incremented by 1 in the loop, and the loop condition can specify to iterate only when the variable is less than 5. You can run the code below and review the count of each login attempt:
login_attempts = 0
while login_attempts < 5:
print("Login attempts:", login_attempts)
login_attempts = login_attempts + 1
Login attempts: 0
Login attempts: 1
Login attempts: 2
Login attempts: 3
Login attempts: 4
The value of login_attempts went from 0 to 4 before the loop condition evaluated to False. Therefore, the values of 0 through 4 print, and the value 5 does not print.
Boolean values in the loop condition
Conditions in while loops can also depend on other data types, including comparisons of Boolean data. In Boolean data comparisons, your loop condition can check whether a loop variable equals a value like True or False. The loop iterates an indeterminate number of times until the Boolean condition is no longer True.
In the example below, a Boolean value is used to exit a loop when a user has made five login attempts. A variable called count keeps track of each login attempt and changes the login_status variable to False when the count equals 4. (Incrementing count from 0 to 4 represents five login attempts.) Because the while condition only iterates when login_status is True, it will exit the loop. You can run this to explore this output:
count = 0
login_status = True
while login_status == True:
print("Try again.")
count = count + 1
if count == 4:
login_status = False
Try again.
Try again.
Try again.
Try again.
The code prints a message to try again four times, but exits the loop once login_status is set to False.
Managing loops
You can use the break and continue keywords to further control your loop iterations. Both are incorporated into a conditional statement within the body of the loop. They can be inserted to execute when the condition in an if statement is True. The break keyword is used to break out of a loop. The continue keyword is used to skip an iteration and continue with the next one.
break
When you want to exit a for or while loop based on a particular condition in an if statement being True, you can write a conditional statement in the body of the loop and write the keyword break in the body of the conditional.
The following example demonstrates this. The conditional statement with break instructs Python to exit the for loop if the value of the loop variable asset is equal to “desktop20”. On the second iteration, this condition evaluates to True. You can run this code to observe this in the output:
computer_assets = ["laptop1", "desktop20", "smartphone03"]
for asset in computer_assets:
if asset == "desktop20":
break
print(asset)
laptop1
As expected, the values of “desktop20” and “smartphone03” don’t print because the loop breaks on the second iteration.
continue
When you want to skip an iteration based on a certain condition in an if statement being True, you can add the keyword continue in the body of a conditional statement within the loop. In this example, continue will execute when the loop variable of asset is equal to “desktop20”. You can run this code to observe how this output differs from the previous example with break:
computer_assets = ["laptop1", "desktop20", "smartphone03"]
for asset in computer_assets:
if asset == "desktop20":
continue
print(asset)
laptop1
smartphone03
The value “desktop20” in the second iteration doesn’t print. However, in this case, the loop continues to the next iteration, and “smartphone03” is printed.
Infinite loops
If you create a loop that doesn’t exit, this is called an infinite loop. In these cases, you should press CTRL-C or CTRL-Z on your keyboard to stop the infinite loop. You might need to do this when running a service that constantly processes data, such as a web server.
Key takeaways
Security analysts need to be familiar with iterative statements. They can use for loops to perform tasks that involve iterating through lists a predetermined number of times. They can also use while loops to perform tasks based on certain conditions evaluating to True. The break and continue keywords are used in iterative statements to control the flow of loops based on additional conditions.
Exemplar: Create loops
Practice Quiz: Test your knowledge: Conditional and iterative statements
What will the following code display?
ip_address = "192.168.183.51"
if ip_address == "192.168.183.51":
print("You're logged in.")
else:
print("Login failed, try again.")
1 / 1 point
“You’re logged in.”
The code will display “You’re logged in.” The condition in the if statement requires the ip_address variable to contain a value of “192.168.183.51”. Because this condition evaluates to True, Python will perform the action specified in the body of the if statement. In this case, it displays the message “You’re logged in.” The action specified in the body of the else statement will only execute when the condition in the if statement evaluates to False, so it will not print “Login failed, try again.”
Which conditional statement prints the message “account locked” when the value of failed_logins is 3 or higher?
if failed_logins >= 3:
print("account locked")
The following conditional statement prints the message “account locked” when the value of failed_logins is 3 or higher:
if failed_logins >= 3:
print(“account locked”)
This condition checks if failed_logins is assigned a value that is greater than or equal to 3. The operator >= represents greater than or equal to. When this condition is met, the body prints the “account locked” message.
Which code prints all numbers from 3 to 7?
for i in range(3, 8):
print(i)
The following code prints all numbers from 3 to 7:
for i in range(3, 8):
print(i)
The range() function generates a sequence of numbers. With range(3, 8), the sequence will start at 3 and end at 7. This is because the number in the first position, 3, is included in the sequence, but the number in the second position, 8, is excluded.
How many times does the following code print the “security alert” message?
count = 0
while count < 10:
print("security alert")
count = count + 1
10
This code will print “security alert” ten times. This is because the count variable is assigned an initial value of 0. It then increments by 1 with each iteration of the loop until the condition instructs it to stop at 10.
Review: Introduction to Python
Video: Wrap-up
Review of Basic Python for Security Analysts
You’ve accomplished a lot! Here’s a quick recap:
- Programming Basics: Understanding why it’s crucial for security analysts and how languages like Python work.
- Data Types: Recognizing and working with strings, integers, floats, Booleans, and lists.
- Variables: Storing and manipulating data by assigning names and values.
- Conditional Statements: Making decisions based on conditions using
if
,else
, andelif
statements. - Iterative Statements: Repeating tasks efficiently with
for
andwhile
loops.
This strong foundation prepares you for the next steps in your Python journey for security analysis, including exploring essential components like functions!
Well done! You’ve learned about why
security analysts use Python and the basic structure of a program. You’ve even written some
lines of Python code. Let’s review what you learned so far. You first learned about
the basics of programming and why it’s a very important tool for
security analysts. You also learned some of the basic
concepts of how programming languages work. You then learned to recognize
data types in Python. We focused on string, integer,
float, Boolean, and list data. Next, we focused on
working with variables. You then learned all about conditional
statements, and how to check for logical conditions using
Python statements. Lastly, we worked with
iterative statements and discussed the two types of loops:
for and while loops. You’ll use this knowledge as you
progress through this course and in your career as a security analyst. In the next section, we’ll explore
other important components of Python, including functions.
Reading: Reference guide: Python concepts from module 1
Reading: Glossary terms from module 1
Terms and definitions from Course 7, Module 1
Automation: The use of technology to reduce human and manual effort to perform common and repetitive tasks
Boolean data: Data that can only be one of two values: either True or False
Command-line interface: A text-based user interface that uses commands to interact with the computer
Comment: A note programmers make about the intention behind their code
Conditional statement: A statement that evaluates code to determine if it meets a specified set of conditions
Data type: A category for a particular type of data item
Dictionary data: Data that consists of one or more key-value pairs
Float data: Data consisting of a number with a decimal point
Integer data: Data consisting of a number that does not include a decimal point
Integrated development environment (IDE): A software application for writing code that provides editing assistance and error correction tools
Interpreter: A computer program that translates Python code into runnable instructions line by line
Iterative statement: Code that repeatedly executes a set of instructions
List data: Data structure that consists of a collection of data in sequential form
Loop variable: A variable that is used to control the iterations of a loop
Notebook: An online interface for writing, storing, and running code
Programming: A process that can be used to create a specific set of instructions for a computer to execute tasks
Set data: Data that consists of an unordered collection of unique values
String data: Data consisting of an ordered sequence of characters
Syntax: The rules that determine what is correctly structured in a computing language
Tuple data: Data structure that consists of a collection of data that cannot be changed
Type error: An error that results from using the wrong data type
Variable: A container that stores data
Quiz: Module 1 challenge
Fill in the blank: If you use Python code to reduce the manual effort needed to manage an access control list, this is an example of _____.
automation
What is wrong with the following code?
for username in failed_login:
print(username)
The line with print(username) is not indented.
Which of these are string data? Select all that apply.
“100”, “user1”
Which line of Python code would create a Boolean value of True?
print(10<100)
What are the variables in the following code? Select all that apply.
username = “kcarter”
attempts = 5
print(username)
print(attempts)
print(“locked”)
username, attempts
Fill in the blank: If you ran the following code, the output would _____.
var1 = 9.5
var1_type = type(var1)
print(var1_type)
indicate that var1 contains float data
You are checking whether the string stored in a device_id variable matches to the correct device ID, the string “15hgu3769”. When it matches, you want to print, “Login successful!”. Which conditional statement has the correct syntax needed to do this?
if device_id == “15hgu3769”:
print(“Login successful!”)
You wrote the following code:
if attempts >= 5:
print(“locked”)
else:
print(“try again”)
If the value in the attempts variable is 3, what will Python do?
Output the message “try again”
What will this iterative statement do?
for i in [0, 5]:
print(i)
Output the integers 0 and 5
You want to print all even numbers between 0 and 10 (in other words, 0, 2, 4, 6, 8, and 10). What should your next line of code be?
count = 0
while count <= 10:
print(count)
count = count + 2