Skip to content

Here, you’ll learn how to use iterative statements, or loops, to automate repetitive tasks. You’ll also learn how to manipulate strings using slicing, indexing, and formatting. 

Learning Objectives

  • Describe how to manipulate strings using techniques such as concatenating, indexing, slicing, and formatting
  • Summarize the syntax of the range() function
  • Explain the purpose and logic of iterative statements such as for loops and while loops
  • Format strings
  • Manipulate strings using indexing, slicing, and formatting
  • Introduce strings
  • Know when to use for and when to use while loops
  • Analyze nested for loops
  • Use the range() function to control for loops
  • Utilize for loops to iterate over sets of data, integers, strings and more
  • Use loops within functions
  • Identify common errors in loops
  • Initialize variables
  • Implement logical operators in while loops
  • Define loops
  • Define iteration

While loops


Video: Welcome to module 3

  • In this section of the course, you will learn how to use Python code to automate repetitive tasks using loops.
  • There are two types of loops in Python: while loops and for loops.
  • Loops can be used to iterate over many different data types, including strings, lists, sets, and dictionaries.
  • In this section of the course, you will focus on using loops to iterate over strings.
  • Operations like indexing and slicing allow you to select, filter, and edit data quickly and efficiently.
  • These are valuable Python skills for any data professional.

Welcome back! Wow, you’ve learned a
lot of new Python skills! You can use variables to
store and label your data, and convert and combine
different data types, such as integers and floats. You can call functions
to perform useful actions on your data, and use
operators to compare values. You also know how to write clean code that can be easily understood and reused by other data professionals. Finally, you can write
conditional statements to tell the computer how to make decisions based on your instructions. Your knowledge of
fundamental coding concepts is the first stage of a journey that leads to more advanced
methods of data analysis. And this learning journey will continue throughout your future career
as a data professional. To me, that’s one of the most
exciting parts of the job! I’m always learning new ways to use Python for data analysis, whether
from teammates at work, or from the super
supportive online community. Learning new Python skills helps me become a more effective data professional. In this section of the course, you’ll learn how to use Python code to automate repetitive tasks. Often data professionals need programs to perform an action repeatedly. For example, if you’re
analyzing sales data, you may want to perform
the same calculation on hundreds of price values. Rather than write new code each time you want to make the calculation, you can instead write an
iterative statement, or loop. Loops automatically
repeat a portion of code until a process is complete. We’ll discuss two types of
loops: while loops and for loops. Using Python to automate repetitive tasks saves me tons of time and effort, and reduces the risk of human error. It also reduces my overall workload and increases my productivity. I have more free time to focus on the main goal of any
data analysis project: to generate insights for stakeholders. You can iterate over many
different data types in Python, such as strings, lists,
sets, and dictionaries. In this section of the course,
we’ll focus on strings. Later on, we’ll discuss the
other data types in detail. As a data professional, you’ll often work with
strings when analyzing data. For example, you might
examine textual data related to a company’s products, services, customer feedback, and more. Operations like indexing and
slicing allow you to select, filter, and edit data
quickly and efficiently. These are valuable Python skills
for any data professional. When you’re ready to learn more, I’ll meet you in the next video.

Video: Michelle: Approach problems with an analytical mindset

  • Michelle is a Data Engineer at Google, even though she started her career as a documentation specialist.
  • She was worried that people would judge her for not having a degree in analytics, but she found that everyone was welcoming and accepting.
  • She experienced imposter syndrome, but she realized that data analytics is about developing the skills to approach problems in an analytical mindset.
  • She shares a story about how she automated an analytics workflow by breaking it down into smaller, more manageable chunks.
  • She encourages others to break down their goals into smaller pieces and to not be discouraged by the mountain of work in front of them.

Overall, Michelle’s message is that it is possible to break into data analytics and data science without a traditional background. It is all about developing the skills to approach problems analytically and being willing to learn and grow.

My name is Michelle and I’m a Data Engineer here at Google. I actually started as a documentation specialists
right out of college. But being surrounded by so many technical
people working within analytics really made me
interested in the field and made me want to join the
team and work in that world. I anticipated that I would face judgment or people
looking down on the fact that I didn’t have a
degree in analytics when I was breaking into
the field and I am happy to report from my experience that
did not happen. It was only my own negative
self-talk in my head. Everyone around me
was welcoming and accepting and really
happy to have someone who took a
non-traditional path into engineering and analytics on the team because of the unique
viewpoints that I brought. Imposter syndrome is
a very real thing. I think everybody
experiences it and so did I. There were so many times
where I would stop and think, maybe I’m not meant to be here. I don’t have an
advanced degree in analytics or
information science. Is there really anything
that I could even contribute being in
this room right here, right now and the way
I got through it was realizing that
having a career in data analytics and data
science is not about memorizing every possible answer for every possible scenario. That’s not it at all. The purpose is, you’re
supposed to develop the skills to be
able to approach a problem in an
analytical mindset. There was a project earlier
in my career where I really wanted to automate part
of an analytics workflow. I knew what I needed to do, but I didn’t know
exactly how to do it. The way I approached this
problem was to first write down what I wanted to do in plain English without
any computer code, any programming,
nothing like that. Then I had to do a lot
of searching on Google. I was looking on various
forums for how to do XYZ and Python, how to use a for-loop, how to use Python
for data science and automate analytics and I slowly made my way over to completely automating the workflow
that I wanted to automate one piece at a time. Being able to automate
that workflow has left me with a sense of
accomplishment that has remained with
me to this day. Sometimes it can seem really discouraging when you
have a mountain of work in front of you or somewhere
that you want to get to and you’re thinking this
is going to be impossible, but it’s really not. If you just break
things down into smaller, more manageable chunks, you absolutely will get there and then you’ll get to a point where you
look back and think, my gosh, I did it. I’ve made it all the way here.

Lab: Annotated follow-along guide: Loops and strings

Video: Introduction to while loops

What is a While loop?

A While loop is a loop that instructs your computer to continuously execute your code based on the value of a condition.

How does a While loop work?

A While loop starts by evaluating the condition. If the condition is true, the loop body is executed. After the loop body is executed, the condition is evaluated again. If the condition is still true, the loop body is executed again. This process continues until the condition is false.

When to use a While loop

While loops are useful when you need to execute a block of code repeatedly until a certain condition is met. For example, you could use a While loop to read a file line by line until you reach the end of the file, or to search for a specific element in a list until you find it.

Example of a While loop

The following code shows a simple example of a While loop:

Python

number = 5
while number > 0:
    print(number)
    number -= 1

This code will print the numbers 5, 4, 3, 2, and 1 to the console.

Tips for using While loops

  • Make sure that the condition of your While loop will eventually evaluate to false, otherwise your loop will run forever.
  • Use a break statement to exit a While loop early if necessary.
  • Use nested While loops to create more complex logic.

Conclusion

While loops are a powerful tool that can be used to automate repetitive tasks and create complex logic. By understanding how While loops work, you can write more efficient and effective Python code.

Introduction to While loops in Python

While loops are one of the most important programming constructs in Python. They allow you to execute a block of code repeatedly until a certain condition is met. This can be very useful for tasks such as iterating over a list, reading a file, or waiting for user input.

Syntax

The syntax for a while loop in Python is as follows:

Python

while condition:
    code block

The condition is a Boolean expression that is evaluated before the code block is executed. If the condition evaluates to True, the code block is executed and then the condition is evaluated again. This process continues until the condition evaluates to False, at which point the loop terminates.

Example

Here is a simple example of a while loop:

Python

i = 0
while i < 10:
    print(i)
    i += 1

This code will print the numbers 0 through 9 to the console.

Break statement

The break statement can be used to exit a while loop early. If a break statement is encountered inside a while loop, the loop will terminate immediately and the code execution will continue at the next line after the while loop.

Example

Here is an example of a while loop that uses the break statement:

Python

i = 0
while True:
    if i == 5:
        break
    print(i)
    i += 1

This code will print the numbers 0 through 4 to the console and then exit the loop.

Continue statement

The continue statement can be used to skip the remaining code in the current iteration of a while loop and start the next iteration.

Example

Here is an example of a while loop that uses the continue statement:

Python

i = 0
while i < 10:
    if i % 2 == 0:
        continue
    print(i)
    i += 1

This code will print the odd numbers 1 through 9 to the console.

Nested while loops

While loops can be nested inside other while loops to create more complex logic. For example, you could use nested while loops to iterate over a list of lists or to search for a specific element in a tree.

Example

Here is an example of nested while loops:

Python

list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
i = 0
while i < len(list1):
    j = 0
    while j < len(list1[i]):
        print(list1[i][j])
        j += 1
    i += 1

This code will print the elements of the list list1 to the console in row-major order.

Conclusion

While loops are a powerful tool that can be used to automate repetitive tasks and create complex logic. By understanding how while loops work, you can write more efficient and effective Python code.

Fill in the blank: A loop is a block of code used to carry out _____.

iterations

A loop is a block of code used to carry out iterations. Data professionals use loops to automate repetitive tasks.

If you had to do the same thing over and over and over again… well, you might get a bit loopy. And you’d probably think to yourself, “I wish I could spend my time
on something more meaningful.” Well, that’s where computers can help. They do the looping for you. As a refresher, a loop is a block of code used to carry out iterations. An iteration is the repeated execution of a set of statements, where one iteration is
the single execution of a block of code. And an iterable is an
object that’s looped, or iterated, over. Typically, data
professionals use for loops and While loops to work with iterables. In this video, we’ll focus on While loops. A While loop is a loop that
instructs your computer to continuously execute your code based on the value of a condition. Magali and Fido are
here to help me explain. Notice that Fido is eating treats while the treat bag is in Magali’s lap. Fido stays until Magali
puts the treat bag away. Then Fido leaves. This is a While statement in action. While Magali has the
treats, Fido is there. Once the condition of Magali holding the treat bag is no
longer met, Fido exits. After all, there are no more treats. While loops work in a similar way to branching IF statements. The difference is that, in While loops, the body of the block can
be executed multiple times instead of just once. This is great for avoiding
redundancy in code. Let’s review an example. Assign the value of
zero to the variable x. As you’ve learned, we call
this action initializing to give an initial value to a variable. Next, start the While loop. Set a condition for this loop that x needs to be less than five. The prior line just initialized it, so this condition is currently true. Then, end the while
loop line with a colon. On the next two lines,
you may notice a block that’s indented to the right. This is the while loop’s body. There are two lines in
the body of the loop. In the first line, print a message followed by the current value of x. In the second line,
increment the value of x by adding one to its current value and assigning it back to x. In the body of the while loop, we told the computer to print
the results of each iteration. Notice how each iteration
changed the value of x. Our while loop started at x equals zero, then printed the message… and increments the value of x to one. But because this is a loop, the computer doesn’t
just continue executing with the next line in the script. Instead, it loops back
around to re-evaluate the condition for the While loop. This is the second iteration. And because one here is
still less than five, it executes the body of the loop again. The third iteration increments x by one. Now the value of x is two. The computer will keep doing this until the condition isn’t true anymore. Let’s add a print
statement outside the body of the while loop to let us
know the final value of x. When the loop finishes, the
next line of code is executed. So, now that x has reached the value five, the loop statement ends. The computer prints the last line of output as x equals five. We can also use the logical operators and, or, and not, that
we worked with earlier. Similar to IF statements,
using these operators allows us to combine the values
of several expressions to get the result we want. The important thing to remember
is that the condition used by the while loop needs to
evaluate to true or false. It doesn’t matter if this is done by using comparison operators or calling additional functions. I think you’re ready for an example that uses several different concepts that you’ve learned so far, and even a couple that you haven’t. To help you explore the example, I’ll guide you as we go, and I’ll explain the concepts to you. You’ll probably find that as you continue on your journey learning Python, you’ll encounter new concepts that can be understood in context. It’s the same way with spoken language. If I say “the elephant was so gargantuan that it crushed the car by stepping on it,” the word “gargantuan” may or
may not be in your vocabulary, but the context helps us understand that it has something to
do with being “big” or “heavy.” It’s the same with coding. Pause the video and try to figure out what this code is doing. When you’re ready, continue
and I’ll lead you through it. In this example, we’re going
to write a short program that generates a random number and then gives the user
five chances to guess it. We begin by importing a
package called “random.” This package has many uses, but the one we want is its ability to generate a random number. Now instantiate a variable called “number,” and use the “random int” function
from the “random” package to assign it a value. The value is a random number
between 1 and 25, inclusive. Next, we instantiate another variable called “number of guesses” and
assign it a value of zero. This variable is important, because it will behave as a counter that controls the logic of our program. Now comes our While loop. We write “While the number
of guesses is less than five”… and below it we give the instructions for what should happen at
each iteration of the loop. First, the script will print a message telling the user to guess
a number from 1 to 25. Then we instantiate a new
variable called “guess,” which will capture a string
of whatever the user inputs. The input function used
here will create a prompt that allows the user to type their guess. The next line converts
the guess to an integer. This is important because without it, the input function would
capture the number as a string, and it would be impossible
to win the game, because even if they
guess the right number, the string of the number
will never evaluate as being equal to the
interger of the number. Now, we increase the “number
of guesses” variable by one. This is an important step because, remember, the While loop
will continue to iterate for as long as the “number
of guesses” variable is less than five. If we left this out, the
loop would never stop running and the user would have infinite guesses until they got it right. By the way, this syntax
is a helpful shortcut. Instead of writing “number of guesses equals number of guesses plus one,” we can simply write “number
of guesses plus-equals one.” They mean the same thing,
but one way is shorter. Now we’re going to have
our branching logic that determines what the program does. We want the behavior to
be different depending on how many guesses the user has made and whether their guess
was correct or not. This code is still within
the body of the While loop, so it will execute on every iteration. The first line checks
if the guess is correct. If it is, the While loop breaks. This word “break” is a
keyword that lets you escape a loop without triggering
any ELSE statement that follows it in the loop. In this case, if the user
guesses the correct number, the While loop would break
and the code would continue at the IF statement below. Because the guess is correct, we print a message telling
the user that they’re correct and include how many tries
it took them in the message. But let’s go back up to the While loop and go through what happens
if the guess is not correct. We use the ELIF statement to check if the guess was their fifth guess. If it was, we break the While loop. Evaluation would continue below, and because the guess was incorrect, it would trigger the
very last ELSE statement that outputs a message telling the user they were unsuccessful and revealing the correct number. Without this ELIF statement the code would still work… kinda. The user would get a message
saying “Nope! Try again,” and then immediately get
another message telling them they were unsuccessful
and revealing the number. But, if the guess was
not their fifth guess, the code would proceed
to the else statement, which prints “Nope, Try again.” Let’s run the program and
try to guess the number. Congratulations, you just
integrated a bunch of concepts into a single script of
code and worked on a problem that incorporated some complex logic. These skills are invaluable
to data professionals.

Reading: Loops, break, and continue statements

Reading

Lab: Activity: While loops

Lab: Exemplar: While loops

Practice Quiz: Test your knowledge: While loops

Fill in the blank: A while loop instructs your computer to continuously execute your code based on the value of a _____.

A data professional wants to set up a while loop that will iterate as long as the variable x is less than 7. They assign the value 0 to the variable x. What code should they write next?

In Python, the keyword break lets you escape a loop without triggering any else statement that follows it in the loop.

For loops


Video: Introduction to for loops

  • A for loop iterates over a sequence of values.
  • The syntax of a for loop is similar to the syntax of a typical Python statement.
  • The body of the for loop is indented to the right.
  • The range function is a Python function that returns a sequence of numbers.
  • A for loop can be used to read in a file and iterate over the file line by line.
  • A for loop can be nested inside another for loop.
  • Data professionals use for loops in Python and other programming languages all the time.
  • For loops are one of the fundamental tools of coding.
  • For loops are great for performing a repeated procedure on an object with a fixed length to create something new.

Introduction to for loops in Python

What are for loops?

For loops are a fundamental control flow construct in programming languages. They allow you to execute a block of code repeatedly, a specified number of times or until a certain condition is met.

Syntax of a for loop in Python

The syntax of a for loop in Python is as follows:

Python

for variable in sequence:
  code block

Where:

  • for is the keyword that indicates the start of the for loop.
  • variable is a variable that will hold each value from the sequence.
  • sequence is a sequence of values, such as a list, range, or tuple.
  • code block is the block of code that will be executed repeatedly for each value in the sequence.

Example of a for loop

The following code snippet demonstrates how to use a for loop to print the numbers from 1 to 5:

Python

for number in range(1, 6):
  print(number)

This will output the following:

1
2
3
4
5

Using for loops to iterate over lists

You can also use for loops to iterate over lists. For example, the following code snippet prints each item in a list of fruits:

Python

fruits = ["apple", "banana", "orange", "grape"]
for fruit in fruits:
  print(fruit)

This will output the following:

apple
banana
orange
grape

Using for loops with conditions

You can also use for loops with conditions to control how many times the loop iterates. For example, the following code snippet prints the numbers from 1 to 10, but stops after the number 5:

Python

for number in range(1, 11):
  if number == 6:
    break
  print(number)

This will output the following:

1
2
3
4
5

Using for loops with else clauses

You can also use an else clause with a for loop. The else clause will be executed only if the loop exits normally, without reaching the break statement. For example, the following code snippet prints the numbers from 1 to 10, and then prints a message saying that the loop has finished:

Python

for number in range(1, 11):
  print(number)
else:
  print("The loop has finished")

This will output the following:

1
2
3
4
5
6
7
8
9
10
The loop has finished

Conclusion

For loops are a powerful tool for repeating code blocks. They are essential for writing efficient and maintainable Python programs.

Have you ever tried to withdraw money from your bank’s ATM, but keyed in your password incorrectly? As you probably experienced, you only have a certain number of tries before the system will lock you out. Sure, it’s frustrating if you’re just typing too quickly or temporarily forget your PIN, but it’s a great safeguard that helps protect your bank accounts. Well, the software in many cash machines runs using a for loop. This detects how many
attempts have been made on a single transaction
before blocking the user. And in this video, we’re
going to learn how that works. A FOR loop iterates over
a sequence of values. A simple example of a
for loop is to iterate over a sequence of numbers. For x in range five… print x. Notice how the structure of a for loop is similar to the syntax of
a typical Python statement. The first line indicates
the distinguishing keyword. In this case, for. And, like functions and other expressions that start a distinct code
block, it ends with a colon. The body of the for loop
is indented to the right. What’s different in this case is that we have the keyword in. Also, between the keywords for and in, we have the name of a variable, x. This variable will take each of the values in the sequence the loop iterates through. In this example, x takes the values zero, one,
two, three, and four. We don’t have to use x. We
could use any term we want: n, number, monkey. It doesn’t matter, as long as we maintain consistency between what we name it here
and how we refer to it below. Ok, now let’s examine the range function. The range function is a python function that returns a sequence of
numbers starting from zero, increments by one by default, and stops before the given number. It can be used in while or for loops. In Python and many other
programming languages, a range of numbers will start with the value zero by default. The list of numbers generated will be one less than the given value. Check it out: By default, our range
function starts with zero. After the first iteration,
the value will be one, the second iteration
outputs two, and so forth. Whatever code we put in the body of the loop will be executed
on each of the values, one value at a time. You can also use a for
loop to read in a file and iterate over the file line by line. The “with open” statement uses the file path to read in the file. In this case, it’s a text file
containing The Zen of Python, a famous poem written by software engineer Tim Peters in 1999. For easier notation,
assign it the value of f. Otherwise, we’d have to
write the file path again. In the next line, start
the for loop for each line. Inside, you indent, and on the next line, tell the computer to print each line. After the loop is complete,
tell the computer to print, “I’m done.” I once had to locate all the unique words in a 2D array of text. I used a FOR loop inside
of another for loop. The outer loop ran over each column, and the inner loop iterated
over each cell for the column. That’s just one example. Let’s check in on Magali
and Fido for another. Magali doesn’t want Fido
to eat too many treats, so she only gives him five treats per day. Fido wags his tail each
time he gets a treat. Once he has all five, he
stops wagging his tail. Good dog, Fido. Data professionals use for loops in Python and other programming
languages all the time. They’re one of the
fundamental tools of coding. They’re great for performing
a repeated procedure on an object with a fixed
length to create something new. Next, we’ll explore
more ways to use loops.

In Python, what type of loop iterates over a sequence of values?

For loop

In Python, a for loop is a piece of code that iterates over a sequence of values.

Video: Loops with multiple range() parameters

This video discusses the range function in Python and how to use its three parameters: start value, stop value, and step value. The range function generates a sequence of numbers, and the parameters can be used to specify which elements of a variable or dataset to include in the sequence.

Here are the key points from the video:

  • The range function can be used to generate a sequence of numbers, starting with zero by default.
  • The range function takes three parameters: start value, stop value, and step value.
  • The start value specifies the first number in the sequence.
  • The stop value specifies the number that the sequence should stop at, but it is not included in the sequence.
  • The step value specifies the size of each step in the sequence.
  • The range function can be used with a for loop to iterate over a sequence of numbers.
  • For loops should be used when there is a sequence of elements that you want to iterate over, such as a variable or a dataset.
  • While loops should be used when you want to repeat an action until a boolean condition changes.

Loops with Multiple range() Parameters in Python

The range() function is a versatile tool in Python that allows you to generate sequences of numbers. While the basic syntax of range() is straightforward, it also offers flexibility by accepting multiple parameters to control the sequence generation. In this tutorial, we’ll explore how to utilize multiple parameters with range() to create more complex loops and perform various tasks.

Understanding Multiple Parameters

The range() function can take up to three parameters:

  1. Start Value: The starting number of the sequence. By default, this is 0.
  2. Stop Value: The number that marks the end of the sequence. However, this value is not included in the sequence.
  3. Step Value: The increment or decrement between consecutive numbers in the sequence. By default, this is 1, indicating an increment of 1.

Examples with Multiple Parameters

Let’s examine some examples to illustrate the usage of multiple parameters:

Example 1: Printing a Sequence from 5 to 15

Python

for num in range(5, 16):
    print(num)

This code snippet generates a sequence from 5 to 15 (inclusive) using the range() function with the start value of 5 and the stop value of 16.

Example 2: Counting Down from 10 to 1

Python

for num in range(10, 0, -1):
    print(num)

In this example, the range() function is used to generate a sequence from 10 to 1 (inclusive) in descending order by specifying a negative step value of -1.

Example 3: Generating a Table of Squares

Python

for num in range(1, 11):
    square = num * num
    print(num, square)

This code demonstrates how to use multiple parameters with range() to generate a table of squares. It iterates from 1 to 10 (inclusive) and calculates the square of each number.

Benefits of Using Multiple Parameters

Utilizing multiple parameters with range() offers several advantages:

  1. Precision: You can control the exact sequence of numbers generated, including start, stop, and step values.
  2. Flexibility: It allows you to create sequences with different starting points, end points, and increments.
  3. Efficiency: It enables you to perform tasks like counting, generating specific number patterns, and iterating over various ranges effectively.

Conclusion

Mastering the use of multiple parameters with the range() function is an essential skill for Python programmers. It empowers you to create customized sequences, perform efficient data manipulation, and enhance the flexibility of your code. By understanding the syntax and applications of multiple parameters, you can tackle a wider range of programming tasks with greater precision and control.

Earlier, you learned
about the range function and how it generates a sequence of numbers starting with zero. However, your work as a data professional, won’t always need to start with zero. Instead, you might want
to use a step parameter in the range function. This makes it possible to specify which elements of a variable or dataset we want to start and end with. In this video, you’ll learn how to use the three parameters
of the range function: start value, stop value, and step value. Here’s a for loop that
calculates the factorial of nine. Let’s explore how it works. We begin by assigning a
variable called “product” with the number one. Next we have a range
function that starts at one and stops at 10. Since the stop value is not
included in the calculation, this means the code
multiplies the variable by every whole number in the
sequence beginning with one and ending with nine. So, for n in range one to 10, we multiply our “product” variable by one and reassign the
result back to itself. Then, we multiply the
“product” variable by two and reassign the result back
to itself, then by three… all the way up to nine. This produces the factorial of nine. The factorial of nine equals 362,880. Note that we started with
one and not with zero. If we multiplied by zero,
the product would be zero. The RANGE function also lets
us specify a third parameter to change the size of
each step in our range. In other words, instead
of going one by one, you can have a larger difference between each of the values in your range. Let’s explore an example. First, define a function that converts a temperature value from Fahrenheit to Celsius. Use the standard conversion formula. The temperature in Fahrenheit that needs to be converted is identified by x, 32 is subtracted from x,
times 5, divided by 9. Next we have a for loop
that will print a table of temperature conversions
every 10 degrees from 0 to 100 degrees Fahrenheit. Notice that the for loop starts at zero and goes up to 100 in steps of 10. Remember that the range
excludes the final value in a sequence, so to
include 100 in our sequence, we put the end value as 101. The body of the for loop
prints the value in Fahrenheit and the value in Celsius to
create a conversion table. For every 10 degrees Fahrenheit, the code prints the corresponding value in Celsius on each line. So, now you know more
about setting parameters for the range function when
you’re working with for loops. As a quick reminder, use for loops when there’s a sequence of elements that you want to iterate over. For example, to loop over a variable, such as a record in a dataset, it’s always better to use for loops. This also improves the
readability of your code. Use while loops when you
want to repeat an action until a boolean condition changes, without having to write
the same code repeatedly. Remember, booleans are a data type that represents one of
two possible states: usually True or False. And, if whatever you’re trying to do can be done with either a
for loop or a while loop, just use whatever you prefer. I happen to love them both and am really glad I have both
tools in my Python toolbox!

Python’s range() function includes which of the following parameters? Select all that apply.  

Stop value, Step value, Start value

Python’s range() function includes the following parameters: start value, stop value, and step value. The range() function returns a sequence of numbers starting from zero; then increments by one, by default; then stops before the given number.

Reading: For loops

Reading

Lab: Exemplar: For loops

Practice Quiz: Test your knowledge: For loops

A data professional can use a for loop to perform which of the following tasks?

A data professional wants to set up a for loop. They write the following code: for x in range(3): . What values will the variable x take?

What parameter of Python’s range() function specifies the size of the increments in a sequence of numbers?

Strings


Video: Work with strings

This section of the Python course teaches students about strings, which are a sequence of characters and punctuation that contain textual information. Strings are immutable, meaning that their values cannot be changed.

Students learn how to concatenate strings, which means to join or link them together to make a single longer string. This is done using the addition operator. For example, to concatenate the strings “Hello” and “world,” you would simply add them together.

Students also learn how to multiply strings, which is done using the multiplication operator. For example, “Danger” times three equals “Danger! Danger! Danger!”

Students learn that strings cannot be divided or subtracted.

Students also learn about reserved characters in strings, such as quotation marks. To include quotation marks in a string, you can either use single quotes to begin and end the string, or you can use the backslash character as an escape character.

Finally, students learn how to iterate over strings with loops. For example, you can use a for loop to iterate over each letter of a word and print it.

The text concludes by stating that strings are commonly used in data analysis, and that students will learn more about useful string operations in future lessons.

Key takeaways:

  • Strings are immutable data types in Python.
  • Strings can be concatenated using the addition operator.
  • Strings can be multiplied using the multiplication operator.
  • Strings cannot be divided or subtracted.
  • Reserved characters in strings can be included using single quotes, double quotes, or the backslash escape character.
  • Strings can be iterated over with loops.

What are strings?

Strings are a sequence of characters surrounded by single quotes (') or double quotes ("). They can contain letters, numbers, symbols, and spaces. Strings are immutable, which means that once they are created, they cannot be changed.

Creating strings

To create a string, simply surround the desired sequence of characters with single or double quotes. For example:

Python

"Hello, world!"
'This is a string'

Concatenating strings

To concatenate strings, use the plus sign (+). For example:

Python

greeting1 = "Hello"
greeting2 = "world!"

# Concatenate the two strings
print(greeting1 + greeting2)

Output:

Hello world!

Accessing string characters

To access individual characters in a string, use square brackets ([]). The index of the first character in a string is 0. For example:

Python

my_string = "This is a string"

# Access the first character in the string
print(my_string[0])

# Access the last character in the string
print(my_string[-1])

Output:

T
g

Slicing strings

To slice a string, use the colon (:). The slicing syntax is string[start:end]. The start index is the index of the first character to include in the slice, and the end index is the index of the first character to exclude from the slice. For example:

Python

my_string = "This is a string"

# Slice the string from the 5th character to the 10th character
print(my_string[5:10])

Output:

is a s

Searching strings

To search for a substring in a string, use the find() method. The find() method returns the index of the first occurrence of the substring in the string, or -1 if the substring is not found. For example:

Python

my_string = "This is a string"

# Search for the substring "is" in the string
index = my_string.find("is")

# Print the index of the substring
print(index)

Output:

5

Replacing string characters

To replace characters in a string, use the replace() method. The replace() method takes two arguments: the old character(s) to replace and the new character(s) to replace them with. For example:

Python

my_string = "This is a string"

# Replace the space character in the string with a hyphen character
print(my_string.replace(" ", "-"))

Output:

This-is-a-string

Splitting strings

To split a string into a list of strings, use the split() method. The split() method takes an optional argument, which is the delimiter to use to split the string. If no delimiter is specified, the split() method will split the string on whitespace. For example:

Python

my_string = "This is a string"

# Split the string on whitespace
print(my_string.split())

# Split the string on the comma character
print(my_string.split(","))

Output:

['This', 'is', 'a', 'string']
['This is a string']

Conclusion

This is just a basic overview of how to work with strings in Python. There are many other string operations that you can learn about, such as formatting strings, converting strings to other data types, and validating strings.

I hope this tutorial has been helpful!

Fill in the blank: _____ strings makes a single longer string from two or more shorter ones. 

Concatenating

Concatenating strings makes a single longer string from two or more shorter ones. To concatenate means to link or join together.

We have covered a
lot of material so far. You learned about functions
and conditional statements, and loops. Now, we’ll learn more about
different data types in Python, beginning with strings. Recall that a string is
a sequence of characters and punctuation that
contains textual information. This is an immutable data type, which means the values can
never be altered or updated. Even though strings are immutable, we can still do a lot with them. For instance, we can concatenate them. To concatenate, means to
link or join together, so concatenating strings is
making a single longer string from two or more shorter ones. To concatenate strings in Python, we simply use the addition operator. If we have two strings, “Hello” and “world,” we can join them by adding them together. The result is a single string, but it’s also a single word. This is because blank
spaces, or white spaces, as they’re known in computer programming, count as their own characters. If you want a whitespace between
your concatenated strings, one of the strings must
contain a white space. Or, you must add a third
string between them that contains just a whitespace. The same rules apply when using variables that point to strings. If “Hello” is assigned to “greeting one,” and “world” is assigned to “greeting two,” we can concatenate the strings
by adding the two variables. We can also multiple strings using the multiplication operator. “Danger” times three, equals
“Danger! Danger! Danger!” However, we cannot divide,
or subtract strings, in trying to do so, will throw an error. As you know, some characters are reserved for specific purposes
when working with strings. For example, quotation
marks are used to indicate the beginning and end of strings. But what if we want our string
to contain quotation marks? There are two ways we can approach this. The first way takes advantage of the fact that strings can be written
with either single quotes or double quotes. If you want to include
double quotation marks in your string, use single quotation marks
to begin and end your string, and vice-versa. The second way is to use the backslash, which functions as an escape character. An escape character changes
the typical behavior of the characters that follow it. In this case, the typical
behavior of quotation marks is to begin or end the string, but if we proceed each with a backslash, they’ll behave as regular
punctuation marks in the string. The backslash character is
useful as an escape character for other special
characters in strings, too. For example, backslash-N is a
special character combination that used to indicate a new
line when printing a string. But if you want to include backslash-N as characters in your
string when you print it, you must precede the combination
with an initial backslash. Moving on, we can also iterate
over strings with loops. In this example, we use a for loop to iterate over each
letter of the word Python, and print the letter,
plus the letters U-T. These are just a few of the
ways to work with strings. As a data professional, you’ll often work with
strings when analyzing data. Coming up, we’ll cover
more useful operations that we can perform over strings.

Video: String slicing

  • Indexing in Python: Python uses zero-based indexing, which means that the first element of a sequence is indexed at zero.
  • Slicing strings: Slicing strings allows us to create smaller strings, or substrings.
  • The index method: The index method returns the index number of a character or substring in a string.
  • Negative indices: We can use negative indices to access the last characters of a string.
  • String slices: A string slice is a portion of a string, also known as a substring.
  • Checking for substrings: We can use the keyword in to check whether or not a substring is contained in a string.

Examples:

  • To slice the string “orange” from index one up to index four, we would use the following code:

Python

orange = "orange"
orange_slice = orange[1:4]
print(orange_slice)

Output:

RAN
  • To check if the substring “apple” is contained in the string “pineapple”, we would use the following code:

Python

pineapple = "pineapple"
is_apple_in_pineapple = "apple" in pineapple
print(is_apple_in_pineapple)

Output:

True

Conclusion:

String slicing is a powerful tool for working with strings in Python. By understanding the basics of indexing and slicing, you can easily extract substrings, check for substrings, and manipulate strings in other ways.

Recently you learned
the basics of strings. In this video, you’ll
add to your knowledge by exploring a new way to
work with strings: slicing. But before you learn about slicing, you’ll need some background information about how Python works. As a reminder, an object is iterable if you can sequence through
all of its values or items. Indexing is Python’s way of letting us refer to individual items within an iterable by
their relative position. Indexing is a very
important part of Python ’cause it allows us to
select, filter, edit and manipulate data, and it
opens up many possibilities to the data professional. By the way, indexing
isn’t just for strings. It also works on many other data types, like lists, tuples, and others, as long as they’re iterable. You’ll learn about these
other data types soon. Python uses zero-based indexing. That means that the first element of a sequence is indexed at zero. With strings, indexing works
by interpreting a string as a sequence of characters,
where each character has a numbered slot. If you’re reading from left to right, the first character is
located at slot zero. The second character
is located at slot one. And the third at slot two, and so on. Indexing lets us slice strings to create smaller strings, or substrings. Here’s an example that
many data professionals have experience with: A column in a data set contains
employee salary information. In the same field, there will
be both strings and integers: the currency symbol and the salary amount. In this case, Python would
automatically interpret the mix of data types
as a string data type. This is often a problem
because we usually want values that represent money
to behave like numbers, so we can perform mathematical
operations on them. If they’re strings, we can’t do that. So, to fix the problem,
slicing helps us remove the non-numeric characters,
like the dollar sign, from the string. In this case, we could drop the character at the zero index of each
value in the salary column. This gives us salary information without the currency prefix. Let’s explore some ways
of working with indices. One useful tool is the index method. Index is a string method
that outputs the index number of a character in a string. Remember, a method is a function
that applies to a variable. We can call it by following
the variable with a dot. We use the index method
to identify the location of a character or substring in a string. Here we have a variable called “pets,” which has been assigned
the string “cats and dogs.” We use the index method by attaching it to the “pets” variable with a dot. In its parentheses, we enter the character we want the index of. Let’s find S. When we run the cell, the
computer returns the number three. This means that index three of our string contains the letter S. What if there’s more than one of the same character or substring? Here we know that there
are two Ss in “cats and dogs,” but only one index returns to us: three. That’s because the index
method just returns the first position that matches. And, if you search for a
substring that is not there, say Z, you’ll get a ValueError, because the substring is not found. Additionally, we can
also use an index number to find a specific
character in that position. For example, we’ll
assign the string “Jolene” to a variable called “name.” By placing the index
number in brackets after the variable, we can access the
character at that position. “Name” at index zero is J,
And “name” at index five is E. What happens if we put six instead? We’d get an IndexError, indicating that the string
index is out of range. You can access the last
character of a string even when you don’t know
how long the string is by using negative indices. Let’s consider an example. We don’t know the length of this string, but it doesn’t matter. Since it isn’t super efficient
to count each character out, we can reference it by starting from the last position
with a negative index. By using the index negative
one, we get the last character, an exclamation point. And if
we use the index negative two, we get the second to last character, A. Now that we’ve gone over the
fundamentals of indexing, let’s do some slicing. A string slice is a portion of a string. It’s also known as a substring. String slices can contain
more than one character. Here’s an example of how we slice a string of the word “orange.” Let’s start by putting some index numbers inside square brackets and separating the numbers by a colon. This defines the range of
characters in the new slice. We’ll go from index one up to index four. The closing index is not included in the range that’s returned to us, so this would capture
indices one, two and three. And we’ve extracted a slice that contains the characters that correspond
to these indices, R-A-N. We can also use slice notation with just one of the two indices. Omitting the first number
in the range implies that the range begins at zero. So if the string is “pineapple,” and we indicate our slice using “colon, four,” we’ll capture the first
four letters: “pine.” Similarly, if we slice using “four, colon”, we’ll capture everything beginning with index four all the
way to the end: “apple.” Great! We have one more thing to learn. Sometimes data professionals
want to check whether or not a substring is
contained in a string. To check whether or not
a substring is contained in a string, use the keyword in. Let’s find out if “banana”
is in the string contained in our “fruit” variable. It’s false. There is no banana in our
pineapple, but is there “apple?” Let’s check. Yes, “apple” is a substring of “pineapple.” So the computer returns a value of True. Confirming whether a
substring is contained in a string is a common practice in all kinds of data careers. I encourage you to take some time to go through the steps again on your own. The more you apply what you learn, the more comfortable you will become.

Python uses one-based indexing.

False

Python uses zero-based indexing. This means that the first element of a sequence is indexed as zero. With strings, indexing works by interpreting a string as a sequence of characters, where each character has a numbered slot.

Reading: String indexing and slicing

Reading

Video: Format strings

Summary of the video on formatting strings in Python using the format() method:

What is string formatting? String formatting is the process of inserting values into a string at specific locations. This can be done using the format() method in Python.

How to use the format() method The format() method takes a string as input and returns a new string with the values inserted at the specified locations. The values to be inserted are passed as arguments to the format() method.

Inserting values into a string using curly braces To insert a value into a string using curly braces, you can use the following syntax:

Python

"{variable_name}"

The variable name will be replaced with the value of the variable.

Inserting values into a string using keywords You can also insert values into a string using keywords. To do this, you can use the following syntax:

Python

"{{keyword}:{variable_name}}"

The keyword will be replaced with the value of the variable.

Formatting values when inserting them into a string You can also use the format() method to format the values that are inserted into a string. To do this, you can use the following syntax:

Python

"{{keyword}:{format_specifier}:{variable_name}}"

The format specifier can be used to control the formatting of the value, such as the number of decimal places.

Examples

The following examples show how to use the format() method to insert and format values in strings:

Python

# Inserting a value into a string using curly braces:
name = "Alice"
print("Hello, {}!".format(name))

# Inserting a value into a string using a keyword:
price = 7.75
print("The price of the item is ${:.2f}.".format(price))

# Formatting values when inserting them into a string:
def convert_fahrenheit_to_celsius(fahrenheit):
  """Converts a Fahrenheit temperature to Celsius."""
  celsius = (fahrenheit - 32) * 5 / 9
  return celsius

fahrenheit = 77
celsius = convert_fahrenheit_to_celsius(fahrenheit)

print("Fahrenheit: {:<3} Celsius: {:<6}".format(fahrenheit, celsius))

Output:

Hello, Alice!
The price of the item is $7.75.
Fahrenheit: 77 Celsius: 25.0

Conclusion

The format() method is a powerful tool for formatting strings in Python. It can be used to insert values into a string, format the values when inserting them, and align the output.

Tutorial on String Formatting in Python

Python provides a number of ways to format strings. One of the most common methods is to use the format() method. The format() method takes a string as input and returns a new string with the values inserted at the specified locations.

To use the format() method, you can use the following syntax:

Python

"{} {} {}".format(value1, value2, value3)

The curly braces ({}) will be replaced with the values passed to the format() method.

You can also use keywords to specify where the values should be inserted. To do this, you can use the following syntax:

Python

"{{keyword1}} {{keyword2}} {{keyword3}}".format(keyword1=value1, keyword2=value2, keyword3=value3)

The keywords will be replaced with the corresponding values.

You can also use format specifiers to control the formatting of the values that are inserted into a string. To do this, you can use the following syntax:

Python

"{{keyword}:{format_specifier}}".format(keyword=value)

The format specifier can be used to control the number of decimal places, the alignment of the text, and other formatting options.

Here are some examples of how to use the format() method to format strings in Python:

Python

# Inserting values into a string using curly braces:
name = "Alice"
print("Hello, {}!".format(name))

# Inserting values into a string using keywords:
price = 7.75
print("The price of the item is ${:.2f}.".format(price=price))

# Formatting values when inserting them into a string:
def convert_fahrenheit_to_celsius(fahrenheit):
  """Converts a Fahrenheit temperature to Celsius."""
  celsius = (fahrenheit - 32) * 5 / 9
  return celsius

fahrenheit = 77
celsius = convert_fahrenheit_to_celsius(fahrenheit)

print("Fahrenheit: {:<3} Celsius: {:<6}".format(fahrenheit=fahrenheit, celsius=celsius))

Output:

Hello, Alice!
The price of the item is $7.75.
Fahrenheit: 77 Celsius: 25.0

Another way to format strings in Python is to use f-strings. F-strings are a newer way to format strings, and they are often considered to be more readable and concise than the format() method.

To use f-strings, you can use the following syntax:

Python

f"{value1} {value2} {value3}"

The f-string will evaluate the expressions inside the curly braces and insert the results into the string.

Here are some examples of how to use f-strings to format strings in Python:

Python

# Inserting values into a string using f-strings:
name = "Alice"
print(f"Hello, {name}!")

# Inserting values into a string using keywords:
price = 7.75
print(f"The price of the item is ${price:.2f}.")

# Formatting values when inserting them into a string:
def convert_fahrenheit_to_celsius(fahrenheit):
  """Converts a Fahrenheit temperature to Celsius."""
  celsius = (fahrenheit - 32) * 5 / 9
  return celsius

fahrenheit = 77
celsius = convert_fahrenheit_to_celsius(fahrenheit)

print(f"Fahrenheit: {fahrenheit:<3} Celsius: {celsius:<6}")

Output:

Hello, Alice!
The price of the item is $7.75.
Fahrenheit: 77 Celsius: 25.0

Which method you choose to format strings in Python is up to you. However, f-strings are generally considered to be the more modern and preferred way to format strings.

As you’re discovering,
understanding strings is a big part of Python and programming success. Now that you have a foundational
understanding of strings, let’s learn some new
approaches to save time when creating and manipulating strings. In this video, we’ll focus on formatting strings
using the format method. The format method formats and
inserts specific substrings into designated places
within a larger string. Let’s examine how this appears in code. We have two variables: name and number. The format method uses the curly braces to designate where the variables should be inserted into the string. If we pass the variable
names as parameters to the format method, we
find that it doesn’t matter that the name is a string
and the number is an integer. The format method will insert strings of the values represented
by these variables. The order that they’re inserted in is the order that they’re entered as parameters into the format method. In this case, “name” corresponds
to the first set of braces, and “number” corresponds to the second set. You can also be more explicit with how you designate
what substring goes where. You can name your own keywords and insert them into the braces. In this case, we’ll use “name” and “num.” Now, we explicitly assign our variables to those keywords in
the method parameters. When we run the cell,
the values represented by the variables get inserted into the printed string
according to their keywords. Notice that when we do
it this way the order that we enter the method
arguments doesn’t matter. “Name” will be inserted into
the “name” field in the string, and “number” will be inserted into the “num” field of the string. This approach is very
helpful, for example, in cases where an output message needs to be translated into another language. Many languages change the order of words to communicate the same message. This method makes rearranging
strings fast and easy. And yet another way to insert values into strings is to use integer values in the braces to indicate the order in which to insert the arguments. Notice how in this example, we can enter the variables number and name in the argument
field in a different order than they get inserted
into the printed string. As a data professional,
these different ways to insert values into
strings offer you a lot of flexibility in how you choose
to work and solve problems. Here’s an example that not
only inserts substrings into a larger string,
but also formats them. Imagine you want to print the price of an item with and without tax. Depending on the tax rate,
the number might extend more than two places beyond the decimal. We can use string
formatting to set a limit on the number of decimal
places in the output, which makes it more readable. In this case, our item
costs $7 and 75 cents without tax, and the tax rate is 7%. So the price with tax would be $8.2925. To limit the output to two places beyond the decimal point, we use special syntax. Start with a colon to
separate the expression from the keyword name,
if you decide to use one. After the colon, write dot two F. “Dot two” refers to two
places beyond the decimal, and F stands for float. Now let’s check what happens
when we run this cell. Nice, the price with tax
has two decimals now. You can replace the two in the expression to any number of places
beyond the decimal you want. If you put zero, only a
whole number will print. We’re not done yet. There are even more ways to use the format function to
improve expressions. Let’s explore our conversion
of temperature values from Fahrenheit to Celsius from earlier. At the top is the function we wrote to calculate the
conversion. But now instead of just printing the results,
we’ll format them too. Again, begin with a colon, then use the “greater then” operator
to align the text to the right so that the
output is neatly formatted. “Greater than three” will align the output three spaces to the right. For the converted Celsius value, we’ll use “greater than
six,” which will align the Celsius temperatures
six spaces to the right. Notice how clean the output is. Our decimals are cut at
the hundredths place, and the values output in a nice table. Everything you’ve been
learning about strings will help you work more
effectively, streamline processes, and save your company lots
of time and resources. Using Python is all about
maximizing productivity while minimizing effort,
making it the perfect tool to help you achieve these goals.

Reading: String formatting and regular expressions

Reading

Lab: Exemplar: Strings

Practice Quiz: Test your knowledge: Strings

In Python, what is the term for the portion of a string that can contain more than one character? Select all that apply.

If you’re reading from left to right, what is the index of the first character in a string?

A data professional wants to insert specific substrings in a larger string. What method can they use to do so?

Review: Loops and strings


Video: Wrap-up

The speaker congratulates the learners on their progress in the course and summarizes the key takeaways from the third section:

  • Using Python code to automate repetitive tasks using iterative statements (loops).
  • Two different approaches to automating repetitive tasks: while loops and for loops.
  • Strings manipulation using slicing, indexing, and formatting. The speaker encourages learners to review the reading material and revisit videos, readings, and other resources to prepare for the upcoming graded assessment.

This is the end of the third section of the Python course. You’ve come a long way since the beginning of the course, congratulations on all your progress! In this section of the course, we focused on using Python code to automate repetitive tasks. Rather than write new code each time you want the computer to repeat an action, you can instead write an iterative statement, or loop. Loops automatically repeat
a portion of the code until a process is complete. Using Python to automate repetitive tasks will help you work more effectively, streamline processes, and save tons of time and effort. As a data professional, you’ll have more time available for your most important task: analyzing data to generate useful insights for stakeholders. We discussed two different approaches to automating repetitive tasks: while loops and for loops. You learned how to write code for both while and for loops, and when to use each approach. We also discussed strings, or sequences of characters like letters and punctuation marks. You learned how to manipulate strings by slicing, indexing, and formatting them. As a data professional, you’ll often work with textual data such as product information or customer feedback. Operations like slicing and indexing enable you to select, filter, and edit data quickly and efficiently. Learning Python is an exciting journey that will continue throughout
your future career. Each data project that I work on has its own specific challenges. I’m always exploring online or chatting with teammates to learn new Python skills on the job. This helps me solve problems and work more efficiently. As you continue learning and practicing Python, your data analytic skill
set will continue to grow. 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. You’re doing great. Keep it up!

Reading: Glossary terms from module 3

Terms and definitions from Course 2, Module 3

break: A keyword that lets a user escape a loop without triggering any ELSE statement that follows it in the loop

Concatenate: To link or join together

Escape character: A character that changes the typical behavior of the characters that follow it

For loop: A piece of code that iterates over a sequence of values

format(): A string method that formats and inserts specific substrings into designated places within a larger string

index(): A string method that outputs the index number of a character in a string

Indexing: A way to refer to the individual items within an iterable by their relative position

Iterable: An object that’s looped, or iterated, over

Iteration: The repeated execution of a set of statements, where one iteration is the single execution of a block of code

Loop: A block of code used to carry out iterations 

range(): A Python function that returns a sequence of numbers starting from zero, increments by 1 by default, and stops before the given number 

String slice: A portion of a string that can contain more than one character; also referred to as a substring 

While loop: A loop that instructs the computer to continuously execute the code based on the value of a condition

Quiz: Module 3 challenge

A data professional can use a while loop to perform which of the following tasks?

To repeat a specific block of code until a condition is no longer met

Fill in the blank: The Python range() function returns a sequence of numbers starting from zero; then increments by _____, by default; then stops before the given number.

one

What Python code instructs the computer to loop through values from 20 to 90?

for x in range(20, 91):

A data professional wants to set up a for loop. They write the following code: for x in range(5, 101, 10): . What is the step value of the range() function?

10

What Python code can a data professional use to concatenate the strings ‘brain’ and ‘storm’?

‘brain’ + ‘storm’

In Python, what method works by interpreting a string as a sequence of characters, where each character has a numbered slot?

index()

A data professional assigns the string ‘palm and pine’ to the variable trees. What Python code can they use to find the index of the character ‘m’?

trees.index(‘m’)

A data professional assigns the string ‘penguin’ to the variable animal. What Python code will return the slice ‘pen’?

animal[ :3]

Fill in the blank: A data professional can use the format() method to _____ specific substrings in a larger string.

insert