Skip to content
Home » Google Career Certificates » Google Advanced Data Analytics Professional Certificate » Get Started with Python » Week 2: Functions and conditional statements

Week 2: Functions and conditional statements

Next, you’ll discover how to call functions to perform useful actions on your data. You’ll also learn how to write conditional statements to tell the computer how to make decisions based on your instructions. And you’ll practice writing clean code that can be easily understood and reused by other data professionals.

Learning Objectives

  • Explain the purpose and logic of conditional statements such as if, else, and elif
  • Use comparators and logical operators to compare values
  • List the benefits of commenting on code
  • Identify best practices for writing clean code such as reusability, modularity, and refactoring
  • Describe how to define Python functions using the def and return keywords
  • Compare values using quality operators and logical operators
  • Write comments and break code into blocks to reduce complexity
  • Refactor code to enhance code readability and reuse
  • Define and call functions utilizing parameters and return data
  • Use data type conversions
  • Differentiate and convert between different data types using variable expressions and built-in functions
  • Define variables, expressions, operators
  • Introduce basic python syntax

Functions


Video: Welcome to module 2

This course will teach you how to write Python code to perform multi-step operations on your data and write clean, readable code that can be easily understood and reused by other data professionals.

Key takeaways:

  • Functions are reusable chunks of code that let you perform specific tasks.
  • Reusability and modularity are important elements of writing clean code.
  • Commenting is a useful practice that helps you document your workflow for teammates.
  • Operators are used to compare values and make decisions about data.
  • Conditional statements tell the computer how to make decisions based on instructions.

Benefits of taking the course:

  • You will learn how to write Python code to perform complex operations on your data.
  • You will learn how to write clean, readable code that can be easily understood and reused by other data professionals.
  • You will learn about important concepts such as reusability, modularity, commenting, operators, and conditional statements.

Call to action:

Enroll in the course today and learn how to write Python code that is powerful, efficient, and easy to collaborate with others.

Welcome back! I’m excited to continue our
learning journey together. I really enjoyed exploring the basics of Python programming with you. You learned that Python is a powerful tool for data professionals,
and lets you analyze data with speed, accuracy, and efficiency. You now know how to use
variables in data types to store and organize your data, and have already started
writing your own Python code and this course will continue to build on your foundation of Python knowledge. By the end of the course, you’ll be able to write
statements in Python code to perform multi-step
operations on your data. You’ll also learn how to
write clean, readable code that can be easily understood and reused by other data professionals. Being able to collaborate with teammates is one of the most important
skills for a data professional. And, writing clean code is
a great way to collaborate with your teammates and help
your team achieve its goals. Working with clean code
helps your team work faster, communicate more effectively,
and produce better results. We’ll start with functions,
or reusable chunks of code, that let you perform specific tasks. Functions are like the verbs or action words of a programming language. You can call on a function at any time to help you perform useful
actions on your data, such as sorting, classifying,
summarizing, and much more. Then we’ll discuss how to write clean code that can be easily understood by your teammates and collaborators. You’ll learn about two important elements of writing clean code:
reusability and modularity. Both of these practices
speed up project development and help data professionals
focus on core business needs and avoid spending time doing rework. After that, we’ll examine
another key aspect of writing clean code: commenting. Commenting is a useful practice, because it helps you
consider your thought process while documenting your
workflow for teammates. Using comments to describe
the component parts of a problem helps you solve
it in clear, simple steps. Next, we’ll discuss how to use
operators to compare values. We’ll review two types of operators: comparators and logical operators. Comparators such as
greater than or less than allow you to compare two values. Logical operators such as AND and OR let you connect multiple
statements together and perform more complex comparisons. Data professionals use
operators to analyze and make decisions about their data. Lastly, we’ll consider
conditional statements, which tell the computer
how to make decisions based on your instructions. You’ll learn how to write if,
else, and else-if statements. Data professionals use
conditional statements to structure complex operations, and to perform all kinds
of practical tasks, such as binning data and organizing files. Conditional statements
make your Python code more flexible and powerful. When you’re ready, I’ll
meet you in the next video.

Video: Lateefat: Tips to address challenges when learning to code

Lateefat is a customer engineer at Google Cloud, specializing in data analytics. She learned to code Python to help her customers translate their data to Google’s cloud platform. She shares her tips for learning to code:

  1. Commit to just starting and don’t be afraid to make mistakes.
  2. Learn to read Stack Overflow and understand what it’s saying.
  3. Compartmentalize your learning into what you absolutely need to know and what are nice-to-knows.

Key takeaways:

  • It’s important to just start coding, even if you don’t know everything yet.
  • Stack Overflow is a great resource for learning to code, but it’s important to understand what you’re reading.
  • Focus on learning the essential skills at first, and don’t worry too much about the nice-to-knows.

Call to action:

If you’re interested in learning to code, start by watching videos and reading tutorials. Once you have a basic understanding of the concepts, start coding and don’t be afraid to make mistakes. Use Stack Overflow to find help when you need it, and focus on learning the essential skills at first.

[MUSIC] Hi, my name’s Lateefat. I’m a customer engineer
here at Google Cloud. My specialty is data analytics. Essentially, I’m taking what a customer
already has on another cloud provider or in their data centers and figuring out how
to translate that onto our cloud platform. When I was a kid, I had two dream jobs. One was to be a secretary, and
the other one was to be a waitress. I did both of those things. I enjoyed them immensely. One of the biggest lessons I took away
from my time waitressing is to just face the issue head on. I was a very timid person when I started
waitressing, and so if something was wrong with somebody’s order, I would just hide
in the kitchen until they could make a new one and then pretend like
everything was fine the whole time. That didn’t always go my way,
as you can imagine. It actually would just make people madder. And so from that, I took away just
learning to admit your mistakes, facing it head on, and not being afraid
to talk it through with somebody. Learning Python was a little difficult. A lot of the first issues I had was with
setting up Python in the environment and picking IDEs. I don’t know if you’ve ever played
a video game, but you can spend so much time on that initial screen, just
like character selecting, or there’s so much time you can just get bogged down, picking these small minute things before
you get to the meat and potatoes. The way I overcame those challenges
was one committing to just starting. I realized it’s really powerful to just
say, you’re going to spend X amount of time doing this, and even if you made no
progress, you can at least go home or go to bed that night saying, I did what I
could, and [LAUGH] if that wasn’t enough, it just wasn’t enough. I really took the time to understand
how to read stack overflow, right. I was super frustrated with it
when I first started coding, but that was because I just wanted to copy
paste the code into the console and just magically have it work for me. Or I was trying to blame everything on
the version of Python I was running, or the package version I was running,
and that just wasn’t the case. So just learning to slow down and
actually understand what it’s saying and how this translates to
the error I’m running into or the issue I’m running into,
versus just trying to brute force my way almost to the next topic or
the next question was really helpful. On my first team,
which was a purely sales team, we were tasked with creating these
business intelligence reports for like 2300 different customers or
potential customers. I think my manager at the time calculated
it out, and we would have all had to put in 50 hours a week for the next
three weeks to complete that task. That’s not ideal, right? [LAUGH] Nobody wants
to spend like 8 hours, eight to 10 hours a day
making intelligence reports. But with my coding knowledge, I was able
to automate the creation of those business reports and
create the 2300 within an hour and a half. And it just felt good to know
like I was capable of it. The number one tip I can give people
looking to start coding you are going to watch a ton of videos,
hear a ton of information, somebody’s going to talk to you about
optimization, how to write the best code. But until you’ve actually done it, you
just won’t understand all the rigmarole involved in coding and debugging. Which brings me to my other tip. I would say learn to debug and then if I could give a third tip it would
be to learn to just deal with the noise. If you can start
compartmentalizing into like this is what I absolutely have to know to
get started and to move forward and these would be like nice to knows you’ll
really accelerate your learning journey.

Lab: Annotated follow-along guide: Functions and conditional statements

Video: Define functions and returning values

A function in Python is a block of reusable code that performs specific processes or tasks. To define a function, we use the keyword def at the start of the function block, followed by the name of the function and its arguments (if any). The body of the function is where we write the code that we want the function to actually do.

To get values out of a function, we can use the return keyword. This tells Python that we want to save the result of the function for later use.

Functions can be used to perform a variety of tasks, such as calculating the area of a triangle or converting a string to uppercase. They can also be used to reuse code, which can save us time and effort.

Here are some of the key takeaways from the video:

  • Functions are reusable blocks of code that can be used to perform specific tasks.
  • To define a function, we use the def keyword, followed by the name of the function and its arguments.
  • The body of the function is where we write the code that we want the function to actually do.
  • To get values out of a function, we can use the return keyword.
  • Functions can be used to perform a variety of tasks and to reuse code.

Define functions in Python

To define a function in Python, you use the def keyword, followed by the name of the function and its arguments (if any). The body of the function is where you write the code that you want the function to actually do.

For example, here is a simple function that takes a name and prints a greeting:

Python

def greet(name):
  """Prints a greeting to the given name.

  Args:
    name: The name to greet.
  """
  print(f"Hello, {name}!")

To call the function, you simply type its name followed by parentheses and any arguments that it requires. For example, to call the greet() function and greet the user named “Alice”, you would type the following code:

Python

greet("Alice")

This would print the following output to the console:

” Hello, Alice! “

Returning values from functions

Functions can also return values. To do this, you use the return keyword. For example, here is a function that calculates the area of a triangle:

Python

def calculate_triangle_area(base, height):
  """Calculates the area of a triangle.

  Args:
    base: The base of the triangle.
    height: The height of the triangle.

  Returns:
    The area of the triangle.
  """
  area = base * height / 2
  return area

This function takes two arguments, the base and height of the triangle, and returns the area of the triangle. To call the function and get the area of a triangle with a base of 5 and a height of 10, you would type the following code:

Python

area = calculate_triangle_area(5, 10)

This would assign the value 25.0 to the variable area. You could then use the value of the area variable in other code, such as printing it to the console or storing it in a database.

Tips for defining functions

Here are a few tips for defining functions:

  • Give your functions descriptive names. This will make your code more readable and easier to maintain.
  • Document your functions using comments. This will help you and others understand what the function does and how to use it.
  • Break down large tasks into smaller functions. This will make your code more modular and reusable.
  • Use return values to get values out of your functions. This will allow you to use the results of your functions in other code.

Conclusion

Defining functions is a powerful way to organize your code and make it reusable. By following the tips above, you can write functions that are clear, concise, and efficient.

Fill in the blank: A _____ is a body of reusable code for performing specific processes or tasks.

function

A function is a body of reusable code for performing specific processes or tasks.

Recently, we’ve been
exploring variables, expressions, and data types. In this video, we’ll consider
another important component of programming in Python: functions. A function is a body of reusable code for performing specific
processes or tasks. We’ve come across a few built-in
Python functions so far. For instance, the print function
writes text on the screen, the type function tells us the data type contained within a variable, and the S-T-R function converts
an object into a string. Note that in previous version of Python, print was handled as a statement and did not use parentheses. But, for Python 3, the
print syntax is a function and requires parentheses, even when there are no arguments used and the parentheses are empty. Okay, so we know that Python
has many built-in functions, but if we want to tell a
computer to do other things particular to our own use cases, it’s important to know how
to define our own functions. To define a function, we
use the keyword word def at the start of the function block. You’ve encountered the
define function once before in a previous video, but let’s
consider another example. When defining a new function, always begin with the def keyword. The name of the function comes
next. Let’s call it “greeting.” After that, we have
the function arguments, also known as parameters. A function’s arguments are
always written in parentheses. The arguments are the things
you give to the function to modify in some way. You can call them anything you want. Whatever we call them here
when we define the function is how we’ll have to refer to them below in the function’s body. In this example, our function will have
just one parameter: “name.” When we’re done defining the arguments, close the parentheses,
put a colon at the end, and hit Enter to get to a new line. Now we can write the body of the function. This is where we say what we want the function to actually do. Note how the body is automatically
indented to the right. In Python, lines of code or hierarchical. Any line that is indented pertains specifically to
the less-indented code that precedes it. We can add as many lines as we’d like to the body of the function, but each line must be
indented to the right. Here, it’s indented four spaces. You can use however many spaces you like, as long as you’re consistent. However, four spaces is
usually the preferred way because it makes code more readable. Our “greeting” function will take a name and output a greeting using that name. We’ll have the function print “Welcome,” the person’s name, and then on a new line, print
“You are part of the team.” To finish defining the function, simply unindent the next line of code. Now we can call the function
using the word “greeting.” Inside the parentheses,
we’ll type the name “Rebecca.” Then we’ll run the cell. Of course, functions can do a
lot more than print messages. This is just one simple example of defining your own function. Next, let’s consider how to
get values out of a function. This is where return values can be used. Return is a reserved keyword in Python that makes a function do
work to produce new results. But instead of printing the results, the function saves them for later use. Let’s define a new function
that accepts two arguments, the base and height of a triangle, and returns the area of the triangle. The area is calculated as base
times height divided by two. We use the keyword “return” to tell Python that this is the value that we want to come out of the function. Instead of printing, return lets us store
this value in a variable. So, suppose we have two triangles and want to add the sum of both areas. Here’s what we would do: First, calculate the two areas separately, storing each value in
its own named variable. Then add the two areas together, assigning the results to a
variable called “total_area.” If we call this variable, the Jupyter Notebook returns its value, but we don’t have to call it. We could continue writing code if we want. This demonstrates the power
of the return statement. It enables us to combine function calls with other operations, which
makes the code reusable. Reusability involves defining code once and using it many times
without having to rewrite it. There’s more information
on reusability soon, but for now, just understand
that reusing something takes a lot less time and effort than recreating it every time. Let’s do one more. Here’s a function called “get_seconds.” This function takes hours,
minutes, and seconds as inputs and returns the total number of seconds those inputs represent. In the first line, we begin
with the keyword word “def” and name the function “get_seconds.” In the parentheses, we
give it three parameters: hours, minutes, and seconds. The next line performs a computation that calculates the
total number of seconds and assigns that value to a
variable called “total_seconds.” The third and final line
is the return statement that returns the value of “total_seconds.” When we call the function, we have to give it three arguments: hours, minutes, and seconds. We’ll use 16 hours, 45
minutes, and 20 seconds. And there’s our result, 60,320 seconds. Now you understand more about functions and how to use the return keyword to save the results of a
function for later output. Code reuse is a key element of Python that you will continue to appreciate as a data analytics professional. Your data toolbox is growing and growing, and there’s more on the way.

Video: Write clean code

Code reuse is the practice of using code that has already been written and tested, instead of rewriting it from scratch. This can save time and effort, and help to reduce errors.

Modular code is code that is broken down into smaller, independent modules. This makes the code easier to read, understand, and maintain. It also makes it easier to reuse code, as modules can be combined and reused in different ways.

Refactoring is the process of restructuring code without changing its functionality. This can be done to make the code more readable, maintainable, and reusable.

Self-documenting code is code that is written in a way that makes its purpose clear and easy to understand. This can be done by using descriptive variable names, writing clear and concise expressions, and adding comments.

Benefits of code reuse and modularity:

  • Saves time and effort
  • Reduces errors
  • Enhances teamwork and builds trust
  • Makes code easier to read, understand, and maintain
  • Makes code more reusable

Tips for writing reusable code:

  • Give your functions and variables descriptive names.
  • Document your code using comments.
  • Break down large tasks into smaller functions.
  • Use return values to get values out of your functions.
  • Use modular code, which is code that is broken down into smaller, independent modules.

Tips for writing self-documenting code:

  • Use descriptive variable names.
  • Write clear and concise expressions.
  • Add comments to explain your code.
  • Refactor your code regularly to make it more readable and maintainable.

Write clean code in Python

Clean code is code that is easy to read, understand, and maintain. It is also code that is efficient, error-free, and reusable.

Here are some tips for writing clean code in Python:

  • Use descriptive names for variables, functions, and classes. This will make your code more readable and easier to understand.
  • Organize your code into logical blocks. This will make your code easier to read and understand, and it will also make it easier to maintain.
  • Use consistent indentation and style. This will make your code more readable and easier to understand.
  • Document your code. This will help you and others understand what your code does and how to use it.
  • Test your code. This will help you to identify and fix any errors in your code.

Here are some additional tips that can help you to write clean code in Python:

  • Avoid magic numbers. Magic numbers are numbers that appear in your code without any explanation. Instead of using magic numbers, use named variables to represent your values. This will make your code more readable and easier to understand.
  • Use functions to break down your code into smaller, more manageable pieces. Functions can also help you to reuse code and to make your code more modular.
  • Use exception handling to gracefully handle errors in your code. Exception handling can help you to prevent your code from crashing and to make your code more robust.
  • Use type hinting to specify the types of data that your variables and functions accept and return. Type hinting can help you to identify and fix type errors in your code.

Here is an example of clean Python code:

Python

def calculate_area(base, height):
  """Calculates the area of a triangle.

  Args:
    base: The base of the triangle.
    height: The height of the triangle.

  Returns:
    The area of the triangle.
  """

  area = base * height / 2
  return area


if __name__ == "__main__":
  base = 5
  height = 10

  area = calculate_area(base, height)

  print(f"The area of the triangle is {area}")

This code is easy to read and understand. It is also well-organized and documented. The code uses functions to break down the task of calculating the area of a triangle into smaller, more manageable pieces. The code also uses type hinting to specify the types of data that the calculate_area() function accepts and returns.

By following these tips, you can write clean Python code that is easy to read, understand, maintain, and reuse.

Which Python feature enables data professionals to define code once, then use it many times without having to rewrite it?

Reusability

Python’s reusability feature enables data professionals to define code once, then use it many times without having to rewrite it.

In the early years of
software development, it was common for developers to write each bit of code themselves. Now we know it’s much more efficient to reuse code that others have written and put in online code repositories. Or, we can develop modular code, which you’ll learn about in this video. Both of these practices
speed up development and help data professionals
focus on using code logic to meet business needs, instead of doing rework. As we’ve discussed, reusability
involves defining code once and using it many times
without having to rewrite it. Consider this example. This script uses the length function, which returns the length of an object, in this case, it’s the number
of characters in the string. Then, it uses that length
to calculate a number, which we’re calling the “lucky number.” Finally, it prints a message
with the name and the number. Each time we want to
perform the calculation, we change the values of the
variables and write the formula. Notice how there are exactly
two lines that are the same in the first and second part of the code. When you find code
duplication in your scripts, it’s a good idea to check
if you can clean things up by using a function. Let’s rewrite this code
creating a function to group all the duplicated
code into just one line. This updated script gives
us the exact same results as the original one, but it’s cleaner and easier to understand. Best of all, it’s now reusable. We can execute the code inside
the lucky number function as many times as we need to by just calling it with a different name. Because of its modular nature, Python is well-suited
to making code reusable. Modularity is the ability to write code in separate
components that work together and that can be reused for other programs. Modularity is closely
related to reusability because it lets you reuse
blocks and sections of code. Reusing code blocks can help you more effectively collaborate
with data engineers on larger projects so that they don’t have
to start their code from the beginning. Here’s an example: These variable names don’t really tell us anything about what this
code is trying to do. We can run it, and yes, it does something. But it was pretty difficult to read and understand that code. So, let’s try to make this
code clearer for other users. Refactoring is the process
of restructuring code while maintaining its
original functionality. This is a part of creating
self-documenting code. Self-documenting code
is code written in a way that is readable and
makes its purpose clear. This involves everything from
selecting your variable names to writing clear, concise expressions. Comments are a helpful supplemental
explanation of the code. When your computer registers
the hashtag character in front of the comment line, it knows to ignore everything that comes after that
character on that line. So, let’s refactor this code
to make it self-documenting. Now the intent and construction
of our code is more clear. It’s also broken up into
functions and commented sections. Commenting is a useful practice because it helps you
think about your process while documenting your workflow
for other collaborators. Although messy code doesn’t necessarily
cause a script to fail, the cleaner the code, the more useful it is for
the rest of your team. Your colleagues will appreciate clean code because they can understand and reuse it to save themselves both time and effort. Plus, code reuse and
modularity reduces errors, enhances teamwork, and builds trust.

Video: Use comments to scaffold your code

  • Comments are important for writing good code. They help you and others understand the code and how it works.
  • Algorithms are sets of instructions for solving a problem or accomplishing a task.
  • To write a new function, it is best to break it into small, simple pieces, beginning with the comments. Outlining the comments in steps, before you even write the code, helps you to better understand the problem.
  • A docstring is a string at the beginning of a function’s body, that summarizes the function’s behavior, and explains its arguments and return values.
  • Comments and docstrings are important for writing well-documented code. Well-documented code is easier to understand, use, and maintain.

Example:

Python

def seed_calculator(fountain_side, grass_width):
  """Calculates the amount of grass seed needed for a border around a square fountain.

  Args:
    fountain_side: The length of one side of the fountain in meters.
    grass_width: The width of the grass border in meters.

  Returns:
    The amount of grass seed needed in kilograms.
  """

  # Calculate the total area.
  total_area = (fountain_side + 2 * grass_width) ** 2

  # Calculate the area of the grass border.
  grass_border_area = total_area - fountain_side ** 2

  # Calculate the amount of seed needed.
  seed_needed = grass_border_area * 35 / 1000

  return seed_needed

This function is well-documented because it has comments and a docstring. The comments break down the function into small, simple pieces, and the docstring summarizes the function’s behavior and explains its arguments and return values.

Conclusion:

It is important for data professionals to get into the habit of writing well-documented code. It is a little more work upfront, but it will save you and your colleagues time and effort in the long run.

Use comments to scaffold your code in Python

Scaffolding your code with comments is a great way to break down a complex problem into smaller, more manageable pieces. It can also help you to better understand the problem and to write more efficient code.

To scaffold your code with comments, simply start by writing a comment that describes the problem that you are trying to solve. Then, break the problem down into smaller steps and write comments to describe each step.

For example, suppose that you are trying to write a function to calculate the area of a triangle. You could start by writing the following comment:

Python

# Calculates the area of a triangle.

Then, you could break down the problem into the following steps:

  1. Get the base and height of the triangle.
  2. Calculate the area of the triangle using the formula area = (base * height) / 2.
  3. Return the area of the triangle.

You could then write a comment to describe each step:

Python

# Get the base and height of the triangle.
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))

# Calculate the area of the triangle.
area = (base * height) / 2

# Return the area of the triangle.
return area

By scaffolding your code with comments, you have made it much easier to write and understand the code. You have also made the code more reusable and maintainable.

Here are some additional tips for scaffolding your code with comments:

  • Use descriptive comments. Your comments should be clear and concise, and they should accurately describe the code that they are next to.
  • Use nested comments to organize your comments. If you have a complex step, you can break it down into smaller steps and use nested comments to describe each step.
  • Use comments to document your code. In addition to describing the code, you can also use comments to document the purpose of the code, any assumptions that the code makes, and any special instructions for using the code.

Scaffolding your code with comments is a valuable skill for any Python programmer. By following the tips above, you can write more efficient, reusable, and maintainable code.

Fill in the blank: Lines of code that begin with a _____ serve as comments and don’t get executed.

hashtag

Lines of code that begin with a hashtag serve as comments and don’t get executed.

Previously, you learned
about writing clean code. In that video, I mentioned
that lines of code that began with a hashtag
don’t get executed, and instead, serve as comments for the human reading the code. In this video, you’ll learn
more about commenting, and why it’s such an important
part of writing good code. Building good coding habits
will enable you to use Python effectively when using data to inform
solutions to business problems. Let’s begin with algorithms, which will help you learn
to think like a programmer, and translate instructions
into Python code. In programming languages, an algorithm is a set of instructions for solving a problem,
or accomplishing a task. One everyday example of an algorithm is a recipe consisting
of specific instructions for baking bread. First, you preheat the oven
to 425 degrees Fahrenheit. Then, you mix two cups
of flour, three eggs, two cups of water, and a
teaspoon of yeast in a bowl, using an electric hand mixer. Then, you let the dough rise for an hour. After that, you transfer
the dough from the bowl to the baking pan. Finally, you insert the
baking pan in the oven. In a similar way, every
computerized device is given instructions in
the form of algorithms as hardware, or software-based routines, to perform its functions. That’s why it’s important to know how to explain things
logically to the computer. This is what it means to
think algorithmically. You’ve already started to think this way, because you’ve learned about functions, and functions are algorithms. As your coding skills develop, you’ll be able to write longer
and more complex functions. The best way to approach
writing a new function is to break it into small, simple pieces, beginning with the comments. Outlining the comments in steps, before you even write the code, helps you to better
understand the problem. Let’s review an example. Suppose we have a square fountain, and we want to plant grass and
a border around that square. Let’s write a function to
calculate the amount of grass seed we’ll need if we know
the length of the side of the fountain, and the
width of the grass border. As always, begin with the def key word. We’ll name the function “seed calculator.” It’s parameters will be
the two things we know: the fountain side length, and
the width of the grass border. Now, we’ll write the body of the function, breaking it into small steps that we’ll outline with comments. First, we’ll find the
area of the fountain. Next, we’ll calculate the
total area of the square, and the grass border combined. From these, we can derive the
area of just the grass border by subtracting one from the other. Then, we’ll calculate the
amount of seed we’ll need, which is 35 grams per square meter. We’ll have to convert that to kilograms, because that’s what we set
the function would output. And finally, we have the return statement. So, let’s review what we’ve done. We used comments to create
a logical scaffolding before writing any code in
the body of this function. In other words, we used
comments to break down the thought process that
outlines each segment of code that we’ll need in order to meet our goal. The only thing left for us to
do is fill it in with code, step-by-step. We can get the total area by
finding the length of one side of the larger outer
square, and squaring it. The length of the large square is equal to the width
of the border times two. Plus, the length of the
side of the fountain. So we’ll code that as “total
area equals fountain side plus two times the grass width.” And we’ll take that whole
expression and square it. The area of the grass border is equal to the total area
minus the fountain area. Then, the amount of seed
we’ll need is the grass area times 35 grams per square meter. Next, we convert grams per square meter to kilograms per square
meter by dividing by 1,000. And return our seed variable. We’re almost done! There’s another important
part of writing functions that are user-friendly
and easy to understand. It’s called a document
string, or docstring, as it’s most commonly referred to. The docstring is a string at the beginning of a function’s body, that summarizes the function’s behavior, and explains its arguments
and return values. A function’s docstring begins and ends with three quotation marks. They can be single
quotes or double quotes. First, we write what the function does. It takes the form of a
command, and ends in a period. Like, “Calculate the number of
kilograms of grass seed needed for a border around a square fountain.” Next, we’ll describe the
function’s parameters. Ours has two. We have “fountain side,”
which is numerical data that represents the length of one side of the fountain in meters. Then, we have “grass width,” which is also numerical data, and it represents the width
of the grass border in meters. Lastly, we’ll describe
what the function returns. This function returns the “seed” variable, which is a float that indicates the amount of grass seed needed
for the border, in kilograms. Great! We have a function
that performs a complex task and can be used as many times as we need. Using comments to break up
the parts of the problem, allowed us to solve it
in clear, simple steps. Best of all, other
people can use this code and understand exactly what it’s doing, because, we’ve written a
docstring in concise comments. So how much seed do we need
if our fountain is a square that’s 12 meters long on a side, and we want a two meter
border of grass around it? 3.92 kilograms. To recap, comments act as a scaffolding that breaks up your code
into manageable pieces. Along with the function’s docstring, they help you and others
understand and use your code. It’s important for data professionals to get into the habit of
writing well-documented code. It’s a little more work upfront, but you’ll thank yourself later, and so will your colleagues.

Reading: Reference guide: Functions

Reading

Lab: Activity: Functions

Lab: Exemplar: Functions

Practice Quiz: Test your knowledge: Functions

A data professional wants to define their own Python function. What keyword should they use at the start of the function block?

Modularity is the ability to write code in separate components that work together.

Why do data professionals use comments for their Python code? Select all that apply.

Conditional statements


Video: Make comparisons using operators

  • Comparators are operators that compare two values and produce Boolean values.
  • There are six comparators in Python:
    • Greater than (>)
    • Greater than or equal to (>=)
    • Less than (<)
    • Less than or equal to (<=)
    • Equal to (==)
    • Not equal to (!=)
  • Logical operators are operators that connect multiple statements together and perform more complex comparisons.
  • Examples of logical operators include:
    • And (and)
    • Or (or)
    • Not (not)

Here is a table that summarizes the different Python comparators and operators:

OperatorDescription
>Greater than
>=Greater than or equal to
<Less than
<=Less than or equal to
==Equal to
!=Not equal to
andReturns True if both statements are true, False otherwise
orReturns True if either statement is true, False only when both statements are false
notInverts the value of the expression that follows it

Comparators and logical operators are very useful in Python because they make it possible to write much more complex code. For example, you can use them to:

  • Create conditional statements, such as if/else statements and for loops.
  • Perform data cleaning and manipulation tasks.
  • Develop machine learning algorithms.

Here are some examples of how to use comparators and logical operators in Python:

Python

# Check if 10 is greater than 1.
10 > 1

# Check if "cat" is equal to "dog".
"cat" == "dog"

# Check if 1 is not equal to 2.
1 != 2

# Check if 25 is greater than 50 or 1 is not equal to 2.
(25 > 50) or (1 != 2)

# Check if 42 is not equal to the string "Answer".
not (42 == "Answer")

Reading: Reference guide: Python operators

Reading

Make comparisons using operators in Python

Python comparators are operators that compare two values and return a Boolean value, which is either True or False. There are six comparators in Python:

  • Greater than (>): Returns True if the first value is greater than the second value, False otherwise.
  • Greater than or equal to (>=): Returns True if the first value is greater than or equal to the second value, False otherwise.
  • Less than (<): Returns True if the first value is less than the second value, False otherwise.
  • Less than or equal to (<=): Returns True if the first value is less than or equal to the second value, False otherwise.
  • Equal to (==): Returns True if the first value is equal to the second value, False otherwise.
  • Not equal to (!=): Returns True if the first value is not equal to the second value, False otherwise.

Python logical operators are operators that connect two or more Boolean expressions and return a single Boolean value. There are three logical operators in Python:

  • And (and): Returns True if both expressions are True, False otherwise.
  • Or (or): Returns True if either expression is True, False only when both expressions are False.
  • Not (not): Inverts the value of the expression that follows it. If it’s True, it becomes False. If it’s False, it becomes True.

Examples

Here are some examples of how to use comparators and logical operators in Python:

Python

# Check if 10 is greater than 1.
10 > 1

# Check if "cat" is equal to "dog".
"cat" == "dog"

# Check if 1 is not equal to 2.
1 != 2

# Check if 25 is greater than 50 or 1 is not equal to 2.
(25 > 50) or (1 != 2)

# Check if 42 is not equal to the string "Answer".
not (42 == "Answer")

Conditional statements

Conditional statements allow you to execute code based on the outcome of a comparison. For example, you can use an if statement to check if a value is greater than another value, and then execute a block of code if it is.

Python

# Check if 10 is greater than 1.
if 10 > 1:
    print("10 is greater than 1.")

# Check if "cat" is equal to "dog".
if "cat" == "dog":
    print("cat is equal to dog.")
else:
    print("cat is not equal to dog.")

Data cleaning and manipulation

Comparators and logical operators can also be used to perform data cleaning and manipulation tasks. For example, you can use them to:

  • Remove duplicate values from a list
  • Select a subset of data from a DataFrame
  • Replace values in a DataFrame based on certain conditions

Machine learning

Comparators and logical operators are also used in machine learning algorithms. For example, you can use them to:

  • Split a dataset into training and testing sets
  • Calculate the accuracy of a model
  • Implement decision trees and other machine learning algorithms

Conclusion

Comparators and logical operators are essential tools for any Python programmer. They can be used for a variety of tasks, including conditional statements, data cleaning and manipulation, and machine learning.

Which of the following words are examples of logical operators? Select all that apply.

or, and, not

Logical operators include the words and, or, and not. Logical operators allow you to connect multiple statements together and perform more complex comparisons.

You’ve learned about data types, like integer, string, and float. Another data type is Boolean data. This is data that has
only two possible values, usually true or false. The word “Boolean” comes from George Boole, a 19th-century English mathematician. Every time you compare things in Python, the result is Boolean type data. Data professionals use
Boolean data every day to control logical flows in their code. In previous lessons, you discovered how Python
can be used like a calculator for basic arithmetic. Now we’ll find out how to
use the power of Python to compare values with
comparators and operators. Comparators are operators
that compare two values and produce Boolean values. All right, now let’s consider an example. If we print 10 is greater than 1, a comparator produces the result, a Boolean value, True. There are six comparators in Python. They let us confirm whether
something is: greater than, greater than or equal to, less than, less than or equal to, equal to, or not equal to something else. Data professionals take the results of comparator expressions and use them to make decisions about data assigned to these descriptions. Here’s an example. Cat is not, in fact, equal to dog. So it produces the Boolean value False. Now, let’s pair an exclamation
mark and an equal sign, which is the not equals comparator. So, the comparator checks
that 1 isn’t equal to 2 and produces the Boolean value of True. As we’ve learned, the plus operator doesn’t work
between integers and strings. So, let’s consider what will happen if we try to compare an
integer and a string. Yep, another TypeError. The good news is that Python also has a
set of logical operators. Logical operators are operators that connect multiple statements together and perform more complex comparisons. Examples of these are the
words and, or, and not. These operators allow you to connect multiple statements together and perform more complex comparisons. The and operator needs
both expressions to be true to return a True result. Here we’re comparing strings. When used on strings of text, comparators evaluate the
first letter of each string, with A being least and Z being greatest. If two strings have the same first letter, the second letter will be compared. In this case, the Y in “yellow” is greater
than the C in “cyan,” but the B in “brown” doesn’t
come after the M in “magenta.” So this means that the
first statement is true, but the second one isn’t true. So, if only part of an expression is true, the result of the whole
and statement is false. Or statements are the opposite. If we use the or operator,
the expression will be True if either of the expressions are true, and False only when both
expressions are false. Try it out. Print this code: Open parenthesis, 25, the greater than comparator, 50, the or operator, 1, the not equal comparator, 2, close parenthesis. 25 is definitely not greater than 50, but 1 is not equal to 2. So, in the end, the whole
expression is true. Now, the not operator inverts the value of the
expression that follows it. If it’s true, it becomes false. If it’s false, it becomes true. Because there is a not statement in front of 42 equals the string “Answer,” the result is true. Comparators and logical
operators are very useful in the data field because they make it possible to write much more complex code. Later, I’ll be back to demonstrate some examples
of these expressions. Keep practicing and reviewing
comparators and operators. I’ll be with you again soon.

Video: Use if, elif, else statements to make decisions

Branching is the ability of a program to alter its execution sequence based on certain conditions. It is a key component to writing useful scripts.

IF statements are used to create branching in Python. They allow you to execute a block of code only if the condition is met. If the condition is not met, the code is skipped.

ELSE statements are used to execute a block of code when the IF condition is not met.

ELIF statements (short for ELSE-IF) are used to create nested IF statements. They allow you to check multiple conditions and execute different blocks of code depending on the outcome.

Branching can be used to:

  • Perform conditional statements, such as if/else statements and for loops.
  • Perform data cleaning and manipulation tasks.
  • Develop machine learning algorithms.
  • Control the flow of your scripts and make them more flexible and efficient.

Here is an example of a simple branching statement in Python:

Python

def is_even(number):
  """Returns True if the number is even, False otherwise."""

  if number % 2 == 0:
    return True
  else:
    return False


print(is_even(10))  # True
print(is_even(19))  # False

This function uses an IF statement to check if the number is even. If it is, the function returns True. Otherwise, the function returns False.

Branching is a powerful tool that can be used to write more complex and useful Python scripts.

Use if, elif, else statements to make decisions in Python

If statements allow you to execute code only if a certain condition is met. If the condition is not met, the code is skipped.

Elif statements (short for ELSE-IF) are used to create nested IF statements. They allow you to check multiple conditions and execute different blocks of code depending on the outcome.

Else statements are used to execute code when all of the previous conditions are not met.

Syntax:

Python

if condition:
  # code to execute if condition is True
elif condition2:
  # code to execute if condition2 is True
else:
  # code to execute if all previous conditions are False

Examples:

Python

# Check if a number is even
number = 10
if number % 2 == 0:
  print("The number is even.")
else:
  print("The number is odd.")

# Check if a grade is an A, B, C, D, or F
grade = "A"
if grade == "A":
  print("You got an A!")
elif grade == "B":
  print("You got a B.")
elif grade == "C":
  print("You got a C.")
elif grade == "D":
  print("You got a D.")
else:
  print("You got an F.")

# Check if a user is logged in
is_logged_in = True
if is_logged_in:
  print("You are logged in.")
else:
  print("You are not logged in.")

Tips:

  • You can use nested if, elif, and else statements to create complex branching logic.
  • You can use Boolean operators (and, or, not) to combine conditions.
  • You can use comparison operators (==, !=, <, >, <=, >=) to compare values.
  • You can use parentheses to group conditions together.
  • Use indentation to make your code more readable.

Conclusion

If, elif, and else statements are powerful tools that can be used to make decisions in Python. By understanding how to use these statements, you can write more complex and useful Python scripts.

Fill in the blank: _____ describes the ability of a program to alter its execution sequence.

Branching

Branching describes the ability of a program to alter its execution sequence.

Now that we know about variables, expressions, functions,
data types, comparators, and logical operators, we can perform exciting actions in our scripts based on
their values using branching. Which is exactly what we’ll
learn about in this video! Branching describes the
ability of a program to alter its execution sequence. This is a key component
to writing useful scripts. Branching uses IF statements based on certain conditions. IF is a reserved keyword that sets up a condition in Python. IF statements, also known
as conditional statements, are just like using the word “if” in everyday life. For example, if it’s before noon, you’ll greet someone
by saying good morning rather than good
afternoon or good evening. If it’s raining outside, you might choose to carry an umbrella. And if it’s snowing, you’ll probably wear a jacket. Here’s an example of this concept in a business context. At a company, new employees can choose their usernames. However, the usernames need to fit a given set of guidelines. Maybe a valid username requires
at least eight characters. As the data professional at this business, you’re tasked with writing a program that will tell the user if their choices are valid or not. To accomplish this task, we’ll write a function. The goal is to define the function so that it generates a username
hint using an IF statement. As a reminder, the built-in len() function will return the length of an object, and that can be paired with
the less-than comparator to identify usernames that
don’t meet the criteria. Great, now your function checks whether the length of the username
is less than eight. If it is, the function prints a message saying that the username is invalid. Let’s review our IF statement. We write the keyword IF
followed by the condition that we want to check for, followed by a colon. After that, we have the
body of the IF block, which is indented further to the right. Here’s a very important point – The body of the IF block will only execute when the condition evaluates to True; otherwise, it does not execute. What this means is – if you run an IF block and
the argument conditions are not met, the indented
code beneath it gets ignored. The IF statement is a useful
construct in Python syntax. But what if we could extend it to make it even more powerful? What if we want the computer
to do something… ELSE? ELSE is a reserved keyword that executes when preceding conditions
evaluate as False. The ELSE statement lets
us set a piece of code to run only when the condition
of the IF statement is False. Here’s an everyday example: IF you’re hungry, you eat. But if you’re not hungry, if that concept is FALSE, then you’ll do something ELSE. Maybe you’ll make another
choice and take a nap. Think about our company username example. Maybe now we want to print a message when a username is valid. The function can now go in different directions depending on
the length of the username. If the username is not long enough, a message indicates that it’s invalid. But if the function
verifies that the username is long enough, it will print a message
saying that it’s valid, which is dictated by the ELSE statement. Notice the structure of
the function right now. The IF statement is indented
in the body of the function, and the action we want to happen if that statement is True
is indented beneath it. We could write as many
lines as we want here, and as long as they’re
all indented beneath the IF statement, they’ll all execute when
that IF statement is True. Then we have the ELSE statement. Note that it’s unindented to the same level as the IF statement. An IF statement and its corresponding ELSE statement are always written at the same level. Beneath the ELSE statement, we indent once more to indicate that this is what must execute when the IF statement is NOT True. Sometimes, you don’t need to add an ELSE statement because that logic is already built into the code. Let’s explore a new operator
that will help with this. We’re going to use a new
operator, the modulo. Represented by the percentage sign, the Modulo is an operator that returns the remainder when one
number is divided by another. The division between
integers yields two results which are both integers: the quotient and the remainder. So, for an integer division
between five and two, the quotient is two, and the remainder is one. For an integer division
between eleven and three, the quotient is three, and the remainder is two. Even numbers are all multiples of two, which means the remainder of the integer division between an even number and two is always going to be zero. So, the modular division
of ten by two is zero. Let’s review an example. This function checks whether a number is even by dividing it by two and checking that the remainder is zero, using the modulo operator. If the remainder is zero, the function will return True. Now here’s the interesting part. You can put an ELSE statement here. That would work. But it’s not strictly necessary, because of the way IF statements work. Remember, when the IF
statement evaluates to True, the code indented beneath it will execute. But when the IF statement
evaluates to False, nothing indented beneath it will execute. The code will then continue running until it gets to the end of the function. Let’s try entering the odd number 19 using the is-even function we defined. The function returned False, because 19 modulo two
does not evaluate to True, so the code indented
beneath the IF statement doesn’t execute, and then the function continues running. In this case, the only remaining code in the
function is “return False.” So that’s what it does. It returns False. At first, you might prefer
to include the ELSE statement in such instances, and that’s okay. It’s important to know
that both ways are correct. But, keep in mind this technique can only be used when returning a
value inside the IF statement. To recap, an IF statement
branches the execution based on a specific condition being True, and the ELSE statement
sets a piece of code to run only when the condition of the IF statement is False. For situations where there are
more conditions to consider, the ELIF statement, short for ELSE-IF, is useful. The ELIF keyword is a reserved keyword that executes subsequent conditions when the previous conditions are not True. It’s Python’s way of saying “if the previous conditions were not True, then try this condition.” Let’s consider an example
to better understand ELIF. It is likely the case that the weather might influence what you choose to do with your afternoon. If the weather is nice, you might go to the park. If it’s raining, you might go to the movies instead. Depending on which of these activities you choose to do, you also need to decide how to get there. And, the activity may determine your mode of transportation! So, the choices you make
depend on different conditions at each point. These are IF, ELSE-IF statements you may
encounter in daily life. Let’s return to the
username validation example. Perhaps now we want to limit how long the username can be. Maybe our business has
a rule that usernames longer than 15 characters aren’t allowed. Let’s type our first condition: usernames of less than eight
characters are invalid. Now we want to add
another condition to this, limiting the username to a
maximum of 15 characters. Notice there are two ELSE statements. The first ELSE is the
second course of action if the first condition is not met and the length of the
username is greater than or equal to eight. In other words, if the first IF statement is False, then the code executes
the first ELSE statement. This ELSE statement has
two more nested conditions: IF and an ELSE. The indentations make the relationships between the different branching
statements easier to read, but the nesting adds some complexity. Remember, you can choose to use as many or as few spaces as you
want for the indentation, but generally it’s best to use four spaces for readability. And, it’s important to be consistent. To avoid unnecessary nesting and to make the code clearer, Python’s ELIF keyword lets us handle more than two comparison cases. In fact, the ELIF keyword allows us to handle an unlimited
number of comparison cases! The ELIF statement is
similar to the IF statement. The abbreviation for ELSE-IF prevents a lot of nested
IF and ELSE statements. If all the above conditions are False, then the final ELSE statement executes. Now let’s run our function
on a really long username. This script works just the same as the one with nested IF-ELSE comparison I just demonstrated, but is much easier to understand. Let’s examine it. The function first checks whether the username is less than
eight characters long. If that’s the case, it prints a message. Next, if the username has
at least eight characters, the function then checks if it’s longer than 15 characters and prints a message if that’s True. If neither of the above
conditions are met, the function prints a message indicating that the username is valid. Now you know how to use IF,
ELIF, and ELSE statements inside functions! This kind of branching is super-helpful when determining the flow of your scripts. Use branching to pick between different pieces of code to execute, making your script pretty
flexible and efficient. Branching also helps with all
kinds of practical things, such as bin data based on its value, backup files, or to only allow login access to a server during certain times of day. Any time your program
needs to make a decision, you can specify its behavior
with a branching statement. Now you have a strong foundation
to build branches in code, which is going to enable you to do a lot of useful work in Python as a data professional. You’ve learned so much already, and I hope you’re enjoying
the discovery as much as I am!

Reading: Reference guide: Conditional statements

Reading

Lab: Activity: Conditional statements

Lab: Exemplar: Conditional statements

Practice Quiz: Test your knowledge: Conditional statements

Fill in the blank: Comparators are operators that compare two values and produce _____ values.

When comparing two expressions, what logical operator requires both expressions to be true to return a True result?

Which of the following is a reserved keyword that sets up a condition in Python?

The elif keyword only works when there are exactly two possible conditions in the code.

Review: Functions and conditional statements


Video: Wrap-up

  • You have learned how to write Python code to perform complex operations on data quickly.
  • You have learned how to write clean, readable code that can be easily understood and reused by other data professionals.
  • You have learned about functions, reusability, modularity, commenting, comparators, logical operators, and conditional statements.
  • You have a graded assessment coming up. To prepare, review the reading that lists all the new terms you’ve learned, and revisit videos, readings, and other resources that cover key concepts.

Overall, you have made significant progress in your Python journey. Congratulations!

You’ve come to the end
of the second section of the Python course. You’ve added a lot of new
Python skills to your skillset, and gained valuable practice
working with data… Well done! Along the way, we’ve explored
how Python code can help you quickly perform complex
operations on your data. You’ve also learned how to
write clean, readable code that can be easily understood, and reused by other data professionals. This is an important part of collaborating with teammates on any data project. Writing clean code will help
your team reduce errors, work faster, communicate more effectively, and deliver better results. We begin by exploring functions,
or reusable chunks of code that let you perform specific tasks. Next, we discussed two important elements of writing clean code:
reusability, and modularity. We also discussed another best practice for writing clean code: commenting. After that, we reviewed two
types of Python operators, comparators and logical operators. And finally you learn how to
write conditional statements such as if, else, and else-if statements. Coming up, you have a graded assessment. To prepare, review the reading that lists all the new
terms you’ve learned. And feel free to revisit videos, readings, and other resources
that cover key concepts. Congratulations on your progress! Let’s keep it going.


Reading: Glossary terms from module 2

Terms and definitions from Course 2, Module 2

Quiz: Module 2 challenge

A data professional wants to define a function to calculate the area of a rectangle. What code should they begin with?

Fill in the blank: A data professional can use the _____ keyword to make a Python function produce new results and save the results for later use.

What are the benefits of using clean code for data work? Select all that apply.

In Python, what is the process of restructuring code while maintaining its original functionality?

A data professional adds a docstring to the beginning of a function’s body. What is the purpose of the docstring?

What is the Python comparator for equal to?

A data professional writes the following code: print(23 > 32 and 7 != 5). What result will Python display when they run the code?

In Python, when does an if statement execute a piece of code?

Fill in the blank: In Python, the _____ statement sets a piece of code to run only when the condition of the if statement is false.