Code icon

The App is Under a Quick Maintenance

We apologize for the inconvenience. Please come back later

Menu iconMenu iconPython Desbloqueado para Principiantes
Python Desbloqueado para Principiantes

Chapter 4: Control Structures

4.2: Loops (for, while)

Loops are an essential control structure in Python as they provide the ability to repeat a block of code multiple times, based on certain conditions or a specified range. By using loops, you can perform repetitive tasks, such as iterating through a list or executing a block of code a specific number of times.

In this topic, we will explore two types of loops available in Python: for loops and while loops. A for loop is used to iterate over a sequence, such as a list, tuple, or string. The for loop executes the block of code inside it for each item in the sequence. On the other hand, a while loop is used to execute a block of code repeatedly as long as a certain condition is met. 

for loops and while loops can be nested within each other, which means that you can have a loop inside another loop. This can be useful when you need to iterate over multiple sequences or perform a repetitive task with a changing condition.

Loops are an essential component of Python programming as they provide a way to perform repetitive tasks efficiently. By understanding the different types of loops and their syntax, you can write more complex programs that perform a variety of tasks.

4.2.1 for  Loop:

for loop is used to iterate over a sequence, such as a list, tuple, string, or any other iterable object. It executes the block of code for each item in the sequence. The general syntax of a for loop is as follows: 

for variable in sequence:
    # Code to be executed for each item in the sequence

For example, let's say we want to iterate through a list of numbers and print each number:

numbers = [1, 2, 3, 4, 5]

for number in numbers:
    print(number)

Output:

1
2
3
4

4.2.2 range() Function:

The range() function is commonly used with for loops when you want to iterate over a range of numbers. The function generates a sequence of numbers starting from 0 (by default) and up to (but not including) the specified number. The syntax for the range() function is:

range(stop)

You can also specify a starting number and a step value as optional arguments:

range(start, stop[, step])

For example, let's say we want to print the numbers from 0 to 4:

for i in range(5):
    print(i)

Output:

0
1
2
3
4

4.2.3 while Loop:

while loop is used to repeatedly execute a block of code as long as a given condition is true. The general syntax of a while loop is as follows:

while condition:
    # Code to be executed while the condition is true

For example, let's say we want to print the numbers from 1 to 5 using a while loop:

number = 1

while number <= 5:
    print(number)
    number += 1

Output:

1
2
3
4
5

In summary, loops are an essential aspect of Python because they allow you to execute a block of code multiple times based on specific conditions or ranges. This makes it easier to automate repetitive tasks and code with fewer lines. Using for loops, you can iterate over sequences, such as lists or tuples, and perform operations on each element. This is useful for tasks such as summing or filtering items in a list. On the other hand, while loops enable you to execute code as long as a given condition is true. This is useful for repetitive tasks or situations where you don't know how many times you need to execute the code.

In the following topics, we will delve deeper into the use of break and continue statements in loops. A break statement allows you to exit a loop prematurely, while a continue statement skips over the current iteration and jumps to the next one. These statements can be used to control the behavior of loops and make them more efficient. We will also discuss nested loops, which involve using one loop inside another. Nested loops are commonly used in tasks such as matrix multiplication or searching through a list of lists. Finally, we will cover loop control techniques, such as using counters or flags to control the flow of execution in a loop. These techniques can make your code more readable and easier to maintain.

Exercise 4.2.1: Sum of Numbers

In this exercise, you will write a Python program that calculates the sum of all numbers from 1 to a given number (inclusive) using a for loop.

Instructions:

  1. Create a new Python file or open a Python interpreter.
  2. Assign an integer value to a variable named n.
  3. Use a for loop and the range() function to iterate through the numbers from 1 to n (inclusive).
  4. Calculate the sum of the numbers and store it in a variable named total.
  5. Print the value of total after the loop is complete.

Your final code should look something like this:

n = 10
total = 0

for i in range(1, n + 1):
    total += i

print(total)

Output:

55

Exercise 4.2.2: Reverse a String

In this exercise, you will write a Python program that reverses a given string using a for loop.

Instructions:

  1. Create a new Python file or open a Python interpreter.
  2. Assign a string value to a variable named text.
  3. Use a for loop to iterate through the characters in the string in reverse order.
  4. Append each character to a new string named reversed_text.
  5. Print the value of reversed_text after the loop is complete.

Your final code should look something like this:

text = "Python"
reversed_text = ""

for char in reversed(text):
    reversed_text += char

print(reversed_text)

Output:

nohtyP

Exercise 4.2.3: Countdown Timer

In this exercise, you will write a Python program that acts as a countdown timer using a while loop.

Instructions:

  1. Create a new Python file or open a Python interpreter.
  2. Assign an integer value to a variable named countdown.
  3. Use a while loop to count down from the given number to 0 (inclusive).
  4. Print the current value of the countdown in each iteration.
  5. Use the time.sleep() function from the time module to pause the program for 1 second between each countdown step.

Your final code should look something like this:

import time

countdown = 5

while countdown >= 0:
    print(countdown)
    time.sleep(1)
    countdown -= 1

print("Time's up!")

Output:

5
4
3
2
1
0
Time's up!

These exercises help you practice using for and while loops in Python to control the flow of your programs and accomplish various tasks.

4.2: Loops (for, while)

Loops are an essential control structure in Python as they provide the ability to repeat a block of code multiple times, based on certain conditions or a specified range. By using loops, you can perform repetitive tasks, such as iterating through a list or executing a block of code a specific number of times.

In this topic, we will explore two types of loops available in Python: for loops and while loops. A for loop is used to iterate over a sequence, such as a list, tuple, or string. The for loop executes the block of code inside it for each item in the sequence. On the other hand, a while loop is used to execute a block of code repeatedly as long as a certain condition is met. 

for loops and while loops can be nested within each other, which means that you can have a loop inside another loop. This can be useful when you need to iterate over multiple sequences or perform a repetitive task with a changing condition.

Loops are an essential component of Python programming as they provide a way to perform repetitive tasks efficiently. By understanding the different types of loops and their syntax, you can write more complex programs that perform a variety of tasks.

4.2.1 for  Loop:

for loop is used to iterate over a sequence, such as a list, tuple, string, or any other iterable object. It executes the block of code for each item in the sequence. The general syntax of a for loop is as follows: 

for variable in sequence:
    # Code to be executed for each item in the sequence

For example, let's say we want to iterate through a list of numbers and print each number:

numbers = [1, 2, 3, 4, 5]

for number in numbers:
    print(number)

Output:

1
2
3
4

4.2.2 range() Function:

The range() function is commonly used with for loops when you want to iterate over a range of numbers. The function generates a sequence of numbers starting from 0 (by default) and up to (but not including) the specified number. The syntax for the range() function is:

range(stop)

You can also specify a starting number and a step value as optional arguments:

range(start, stop[, step])

For example, let's say we want to print the numbers from 0 to 4:

for i in range(5):
    print(i)

Output:

0
1
2
3
4

4.2.3 while Loop:

while loop is used to repeatedly execute a block of code as long as a given condition is true. The general syntax of a while loop is as follows:

while condition:
    # Code to be executed while the condition is true

For example, let's say we want to print the numbers from 1 to 5 using a while loop:

number = 1

while number <= 5:
    print(number)
    number += 1

Output:

1
2
3
4
5

In summary, loops are an essential aspect of Python because they allow you to execute a block of code multiple times based on specific conditions or ranges. This makes it easier to automate repetitive tasks and code with fewer lines. Using for loops, you can iterate over sequences, such as lists or tuples, and perform operations on each element. This is useful for tasks such as summing or filtering items in a list. On the other hand, while loops enable you to execute code as long as a given condition is true. This is useful for repetitive tasks or situations where you don't know how many times you need to execute the code.

In the following topics, we will delve deeper into the use of break and continue statements in loops. A break statement allows you to exit a loop prematurely, while a continue statement skips over the current iteration and jumps to the next one. These statements can be used to control the behavior of loops and make them more efficient. We will also discuss nested loops, which involve using one loop inside another. Nested loops are commonly used in tasks such as matrix multiplication or searching through a list of lists. Finally, we will cover loop control techniques, such as using counters or flags to control the flow of execution in a loop. These techniques can make your code more readable and easier to maintain.

Exercise 4.2.1: Sum of Numbers

In this exercise, you will write a Python program that calculates the sum of all numbers from 1 to a given number (inclusive) using a for loop.

Instructions:

  1. Create a new Python file or open a Python interpreter.
  2. Assign an integer value to a variable named n.
  3. Use a for loop and the range() function to iterate through the numbers from 1 to n (inclusive).
  4. Calculate the sum of the numbers and store it in a variable named total.
  5. Print the value of total after the loop is complete.

Your final code should look something like this:

n = 10
total = 0

for i in range(1, n + 1):
    total += i

print(total)

Output:

55

Exercise 4.2.2: Reverse a String

In this exercise, you will write a Python program that reverses a given string using a for loop.

Instructions:

  1. Create a new Python file or open a Python interpreter.
  2. Assign a string value to a variable named text.
  3. Use a for loop to iterate through the characters in the string in reverse order.
  4. Append each character to a new string named reversed_text.
  5. Print the value of reversed_text after the loop is complete.

Your final code should look something like this:

text = "Python"
reversed_text = ""

for char in reversed(text):
    reversed_text += char

print(reversed_text)

Output:

nohtyP

Exercise 4.2.3: Countdown Timer

In this exercise, you will write a Python program that acts as a countdown timer using a while loop.

Instructions:

  1. Create a new Python file or open a Python interpreter.
  2. Assign an integer value to a variable named countdown.
  3. Use a while loop to count down from the given number to 0 (inclusive).
  4. Print the current value of the countdown in each iteration.
  5. Use the time.sleep() function from the time module to pause the program for 1 second between each countdown step.

Your final code should look something like this:

import time

countdown = 5

while countdown >= 0:
    print(countdown)
    time.sleep(1)
    countdown -= 1

print("Time's up!")

Output:

5
4
3
2
1
0
Time's up!

These exercises help you practice using for and while loops in Python to control the flow of your programs and accomplish various tasks.

4.2: Loops (for, while)

Loops are an essential control structure in Python as they provide the ability to repeat a block of code multiple times, based on certain conditions or a specified range. By using loops, you can perform repetitive tasks, such as iterating through a list or executing a block of code a specific number of times.

In this topic, we will explore two types of loops available in Python: for loops and while loops. A for loop is used to iterate over a sequence, such as a list, tuple, or string. The for loop executes the block of code inside it for each item in the sequence. On the other hand, a while loop is used to execute a block of code repeatedly as long as a certain condition is met. 

for loops and while loops can be nested within each other, which means that you can have a loop inside another loop. This can be useful when you need to iterate over multiple sequences or perform a repetitive task with a changing condition.

Loops are an essential component of Python programming as they provide a way to perform repetitive tasks efficiently. By understanding the different types of loops and their syntax, you can write more complex programs that perform a variety of tasks.

4.2.1 for  Loop:

for loop is used to iterate over a sequence, such as a list, tuple, string, or any other iterable object. It executes the block of code for each item in the sequence. The general syntax of a for loop is as follows: 

for variable in sequence:
    # Code to be executed for each item in the sequence

For example, let's say we want to iterate through a list of numbers and print each number:

numbers = [1, 2, 3, 4, 5]

for number in numbers:
    print(number)

Output:

1
2
3
4

4.2.2 range() Function:

The range() function is commonly used with for loops when you want to iterate over a range of numbers. The function generates a sequence of numbers starting from 0 (by default) and up to (but not including) the specified number. The syntax for the range() function is:

range(stop)

You can also specify a starting number and a step value as optional arguments:

range(start, stop[, step])

For example, let's say we want to print the numbers from 0 to 4:

for i in range(5):
    print(i)

Output:

0
1
2
3
4

4.2.3 while Loop:

while loop is used to repeatedly execute a block of code as long as a given condition is true. The general syntax of a while loop is as follows:

while condition:
    # Code to be executed while the condition is true

For example, let's say we want to print the numbers from 1 to 5 using a while loop:

number = 1

while number <= 5:
    print(number)
    number += 1

Output:

1
2
3
4
5

In summary, loops are an essential aspect of Python because they allow you to execute a block of code multiple times based on specific conditions or ranges. This makes it easier to automate repetitive tasks and code with fewer lines. Using for loops, you can iterate over sequences, such as lists or tuples, and perform operations on each element. This is useful for tasks such as summing or filtering items in a list. On the other hand, while loops enable you to execute code as long as a given condition is true. This is useful for repetitive tasks or situations where you don't know how many times you need to execute the code.

In the following topics, we will delve deeper into the use of break and continue statements in loops. A break statement allows you to exit a loop prematurely, while a continue statement skips over the current iteration and jumps to the next one. These statements can be used to control the behavior of loops and make them more efficient. We will also discuss nested loops, which involve using one loop inside another. Nested loops are commonly used in tasks such as matrix multiplication or searching through a list of lists. Finally, we will cover loop control techniques, such as using counters or flags to control the flow of execution in a loop. These techniques can make your code more readable and easier to maintain.

Exercise 4.2.1: Sum of Numbers

In this exercise, you will write a Python program that calculates the sum of all numbers from 1 to a given number (inclusive) using a for loop.

Instructions:

  1. Create a new Python file or open a Python interpreter.
  2. Assign an integer value to a variable named n.
  3. Use a for loop and the range() function to iterate through the numbers from 1 to n (inclusive).
  4. Calculate the sum of the numbers and store it in a variable named total.
  5. Print the value of total after the loop is complete.

Your final code should look something like this:

n = 10
total = 0

for i in range(1, n + 1):
    total += i

print(total)

Output:

55

Exercise 4.2.2: Reverse a String

In this exercise, you will write a Python program that reverses a given string using a for loop.

Instructions:

  1. Create a new Python file or open a Python interpreter.
  2. Assign a string value to a variable named text.
  3. Use a for loop to iterate through the characters in the string in reverse order.
  4. Append each character to a new string named reversed_text.
  5. Print the value of reversed_text after the loop is complete.

Your final code should look something like this:

text = "Python"
reversed_text = ""

for char in reversed(text):
    reversed_text += char

print(reversed_text)

Output:

nohtyP

Exercise 4.2.3: Countdown Timer

In this exercise, you will write a Python program that acts as a countdown timer using a while loop.

Instructions:

  1. Create a new Python file or open a Python interpreter.
  2. Assign an integer value to a variable named countdown.
  3. Use a while loop to count down from the given number to 0 (inclusive).
  4. Print the current value of the countdown in each iteration.
  5. Use the time.sleep() function from the time module to pause the program for 1 second between each countdown step.

Your final code should look something like this:

import time

countdown = 5

while countdown >= 0:
    print(countdown)
    time.sleep(1)
    countdown -= 1

print("Time's up!")

Output:

5
4
3
2
1
0
Time's up!

These exercises help you practice using for and while loops in Python to control the flow of your programs and accomplish various tasks.

4.2: Loops (for, while)

Loops are an essential control structure in Python as they provide the ability to repeat a block of code multiple times, based on certain conditions or a specified range. By using loops, you can perform repetitive tasks, such as iterating through a list or executing a block of code a specific number of times.

In this topic, we will explore two types of loops available in Python: for loops and while loops. A for loop is used to iterate over a sequence, such as a list, tuple, or string. The for loop executes the block of code inside it for each item in the sequence. On the other hand, a while loop is used to execute a block of code repeatedly as long as a certain condition is met. 

for loops and while loops can be nested within each other, which means that you can have a loop inside another loop. This can be useful when you need to iterate over multiple sequences or perform a repetitive task with a changing condition.

Loops are an essential component of Python programming as they provide a way to perform repetitive tasks efficiently. By understanding the different types of loops and their syntax, you can write more complex programs that perform a variety of tasks.

4.2.1 for  Loop:

for loop is used to iterate over a sequence, such as a list, tuple, string, or any other iterable object. It executes the block of code for each item in the sequence. The general syntax of a for loop is as follows: 

for variable in sequence:
    # Code to be executed for each item in the sequence

For example, let's say we want to iterate through a list of numbers and print each number:

numbers = [1, 2, 3, 4, 5]

for number in numbers:
    print(number)

Output:

1
2
3
4

4.2.2 range() Function:

The range() function is commonly used with for loops when you want to iterate over a range of numbers. The function generates a sequence of numbers starting from 0 (by default) and up to (but not including) the specified number. The syntax for the range() function is:

range(stop)

You can also specify a starting number and a step value as optional arguments:

range(start, stop[, step])

For example, let's say we want to print the numbers from 0 to 4:

for i in range(5):
    print(i)

Output:

0
1
2
3
4

4.2.3 while Loop:

while loop is used to repeatedly execute a block of code as long as a given condition is true. The general syntax of a while loop is as follows:

while condition:
    # Code to be executed while the condition is true

For example, let's say we want to print the numbers from 1 to 5 using a while loop:

number = 1

while number <= 5:
    print(number)
    number += 1

Output:

1
2
3
4
5

In summary, loops are an essential aspect of Python because they allow you to execute a block of code multiple times based on specific conditions or ranges. This makes it easier to automate repetitive tasks and code with fewer lines. Using for loops, you can iterate over sequences, such as lists or tuples, and perform operations on each element. This is useful for tasks such as summing or filtering items in a list. On the other hand, while loops enable you to execute code as long as a given condition is true. This is useful for repetitive tasks or situations where you don't know how many times you need to execute the code.

In the following topics, we will delve deeper into the use of break and continue statements in loops. A break statement allows you to exit a loop prematurely, while a continue statement skips over the current iteration and jumps to the next one. These statements can be used to control the behavior of loops and make them more efficient. We will also discuss nested loops, which involve using one loop inside another. Nested loops are commonly used in tasks such as matrix multiplication or searching through a list of lists. Finally, we will cover loop control techniques, such as using counters or flags to control the flow of execution in a loop. These techniques can make your code more readable and easier to maintain.

Exercise 4.2.1: Sum of Numbers

In this exercise, you will write a Python program that calculates the sum of all numbers from 1 to a given number (inclusive) using a for loop.

Instructions:

  1. Create a new Python file or open a Python interpreter.
  2. Assign an integer value to a variable named n.
  3. Use a for loop and the range() function to iterate through the numbers from 1 to n (inclusive).
  4. Calculate the sum of the numbers and store it in a variable named total.
  5. Print the value of total after the loop is complete.

Your final code should look something like this:

n = 10
total = 0

for i in range(1, n + 1):
    total += i

print(total)

Output:

55

Exercise 4.2.2: Reverse a String

In this exercise, you will write a Python program that reverses a given string using a for loop.

Instructions:

  1. Create a new Python file or open a Python interpreter.
  2. Assign a string value to a variable named text.
  3. Use a for loop to iterate through the characters in the string in reverse order.
  4. Append each character to a new string named reversed_text.
  5. Print the value of reversed_text after the loop is complete.

Your final code should look something like this:

text = "Python"
reversed_text = ""

for char in reversed(text):
    reversed_text += char

print(reversed_text)

Output:

nohtyP

Exercise 4.2.3: Countdown Timer

In this exercise, you will write a Python program that acts as a countdown timer using a while loop.

Instructions:

  1. Create a new Python file or open a Python interpreter.
  2. Assign an integer value to a variable named countdown.
  3. Use a while loop to count down from the given number to 0 (inclusive).
  4. Print the current value of the countdown in each iteration.
  5. Use the time.sleep() function from the time module to pause the program for 1 second between each countdown step.

Your final code should look something like this:

import time

countdown = 5

while countdown >= 0:
    print(countdown)
    time.sleep(1)
    countdown -= 1

print("Time's up!")

Output:

5
4
3
2
1
0
Time's up!

These exercises help you practice using for and while loops in Python to control the flow of your programs and accomplish various tasks.