Skip to content
Home » Google Career Certificates » Google Cybersecurity Professional Certificate » Automate Cybersecurity Tasks with Python » Module 1: Introduction to Python

Module 1: Introduction to Python

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


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

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: Pythonprint("Hello, world!")
    • The print() function displays output in the console.

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:

  1. Open a terminal or command prompt.
  2. Navigate to the directory where you saved the script using the cd command (e.g., cd Desktop/my_scripts).
  3. 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

Reading: Lab tips and troubleshooting steps

Reading

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.

What are some benefits of using Python in security? Select all that apply.

Which of the following code blocks contains a valid Python comment?

Which line of code outputs the string u003cvaru003eu0022invalid usernameu0022u003c/varu003e to the screen?

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:

  1. Strings:
    • Represent text data, enclosed in single or double quotes.
    • Examples: “Hello, world!”, ‘Python is awesome’, “123” (as text, not a number for calculation)
  2. Integers:
    • Represent whole numbers without decimals.
    • Examples: 42, -10, 0
    • Used for mathematical operations and counting.
  3. Floats:
    • Represent numbers with decimal points.
    • Examples: 3.14159, -2.5, 10.0
    • Used for real-world values like measurements and calculations involving decimals.
  4. Booleans:
    • Represent logical values, either True or False.
    • Used for decision-making and conditional logic in code.
  5. 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

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

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.

What code displays the data type of the variable username?

In the following code, what is the data type of login_success?
login_success = [“success”, “success”, “fail”, “success”]

What is the output of the following code?
failed_attempts = 3
failed_attempts = 4
print(failed_attempts)

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:

  1. Introducing Automation and Conditional Statements
  2. Mastering the if Statement
  3. Understanding Comparison Operators
  4. Checking for Equality with ==
  5. Handling “Not Equal” with !=
  6. Introducing the else Statement
  7. Indentation: Python’s Way of Organizing Code
  8. 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

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 cover while 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 Variable:
    • Controls loop iterations; often named i but can be any relevant name.
    • Exists only within the loop, not affecting code outside.
  • 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 (excluding stop).
    • Combine for and range 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 and range 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 with range 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:

  1. Introducing While Loops: Repetition with a Twist
  2. Anatomy of a While Loop: Breaking It Down
  3. Loop Variables: Controlling the Iterations
  4. Conditions: The Heart of the Loop
  5. Hands-On Examples: Putting While Loops to Work
  6. Best Practices and Avoiding Pitfalls
  7. Combining While Loops with Conditional Statements
  8. 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

Exemplar: Create loops

Practice Quiz: Test your knowledge: Conditional and iterative statements

What will the following code display?

Which conditional statement prints the message “account locked” when the value of failed_logins is 3 or higher?

Which code prints all numbers from 3 to 7?

How many times does the following code print the “security alert” message? 

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, and elif statements.
  • Iterative Statements: Repeating tasks efficiently with for and while 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

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 _____.

What is wrong with the following code?
for username in failed_login:
print(username)

Which of these are string data? Select all that apply.

Which line of Python code would create a Boolean value of True?

What are the variables in the following code? Select all that apply.
username = “kcarter”
attempts = 5
print(username)
print(attempts)
print(“locked”)

Fill in the blank: If you ran the following code, the output would _____.
var1 = 9.5
var1_type = type(var1)
print(var1_type)

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?

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?

What will this iterative statement do?
for i in [0, 5]:
print(i)

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)