Python break and continue
Topic Outline:
• Break statement
• Continue statement
• Pass statement
Intended Learning Outcomes:
• Explain the roles of break, continue, and pass statements in Python
programming.
• Distinguish between the break, continue, and pass statements in
terms of their functionalities within loops.
Introduction
Using loops in Python automates and repeats the tasks in an efficient
manner. But sometimes, there may arise a condition where you want to
exit the loop completely, skip an iteration or ignore that condition.
These can be done by loop control statements. Loop control
statements change execution from their normal sequence. When
execution leaves a scope, all automatic objects that were created in
that scope are destroyed.
Python supports the following control statements:
• Break statement
• Continue statement
• Pass statement
Break Statement
• The break statement in Python is used to terminate the loop or
statement in which it is present.
• After that, the control will pass to the statements that are present
after the break statement, if available. If the break statement is
present in the nested loop, then it terminates only those loops
which contain the break statement.
Syntax of Break Statement
for loop:
# Loop body statements
if condition:
break
# statement(s)
# loop end
Break statement in for loop example #1:
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number > 3:
break
print(number)
Break Statement in for loop example #2:
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)
num_sum = 0
count = 0
for x in numbers:
num_sum = num_sum + x
count = count + 1
if count == 5:
break
print("Sum of first ",count,"integers is: ", num_sum)
Break Statement in while loop example #1:
num_sum = 0
count = 0
while(count<10):
num_sum = num_sum + count
count = count + 1
if count== 3:
break
print("Sum of first ",count,"integers is: ", num_sum)
Continue statement
• The continue statement is used in a while or for loop to take the
control to the top of the loop without executing the rest
statements inside the loop.
• Continue is also a loop control statement just like the break
statement. Continue statement is opposite to that of the break
statement, instead of terminating the loop, it forces to execute the
next iteration of the loop.
• As the name suggests the continue statement forces the loop to
continue or execute the next iteration. When the continue
statement is executed in the loop, the code inside the loop
following the continue statement will be skipped and the next
iteration of the loop will begin.
Continue statement
The continue statement in Python has the following syntax:
for loop:
# statement(s)
if condition:
continue
# statement(s)
Continue with for loop example #1.
In this code prints each character of the string "Elephant", except for
the letter "e".
for var in “Fish":
if var == “s":
continue
print(var)
Continue with for loop example #2.
In this program prints the elements of a list skipping None values
my_list = [1, None, 3, 4, None, 6, None, 8]
for element in my_list:
if element is None:
continue # Skip None values and move to the
next iteration
print("Current element:", element)
Continue with while loop example #1.
In this example, we are using a while loop which traverses till 9 if i = 5
then skip the printing of numbers.
i = 0
while i < 10:
if i == 5:
i += 1
continue
print(i)
i += 1
Continue with while loop example #2.
In this program prints the first 10 positive integers, skipping odd numbers
count = 0
number = 1
while count < 10:
if number % 2 != 0:
number += 1
continue # Skip odd numbers and move to the next
iteration
print("Current number:", number)
count += 1
number += 1
Using break and continue in for loop example:
In this program finds the first 4 prime numbers between 1 and 20
prime_count = 0
for num in range(2, 21):
for i in range(2, num): # Loop through numbers from 2 to num - 1
if num % i == 0: # If num is divisible by any number other than 1 and itself,
break
else: # If the inner loop completes without finding a divisor,
prime_count += 1
print("Prime number found:", num)
if prime_count == 4: # If we've found 4 prime numbers, break out of the outer loop
break
else: # If we've found only one prime number, continue searching
continue
print("Search complete.")
Using break and continue in for loop example:
# This program simulates a game where a player needs to guess a number between 1 and 10
import random
# Generate a random number between 1 and 10
secret_number = random.randint(1, 10)
print("Welcome to the Number Guessing Game!")
# Allow the player to make up to 3 attempts to guess the number
for attempt in range(1, 4):
guess = int(input("Attempt {}: Guess the number between 1 and 10: ".format(attempt)))
if guess < 1 or guess > 10:
print("Please enter a number between 1 and 10.")
continue # Skip the rest of the loop body and prompt the player for another guess
if guess == secret_number:
print("Congratulations! You guessed the correct number:", secret_number)
break # Exit the loop since the player has guessed the correct number
print("Sorry, that's not the correct number. Try again.")
# If the loop completes without the player guessing the correct number, print the secret number
else:
print("Sorry, you've used all your attempts. The secret number was:", secret_number)
Python pass Statement
What is pass statement in Python?
• When the user does not know what code to write, So user simply
places a pass at that line. Sometimes, the pass is used when the
user doesn’t want any code to execute. So users can simply place a
pass where empty code is not allowed, like in loops, function
definitions, class definitions, or in if statements. So using a pass
statement user avoids this error.
Python pass Statement
This program prints even numbers between 1 and 10 and does
nothing for odd numbers
for i in range(1, 11):
if i % 2 == 0:
print(i, "is an even number.")
else:
pass
Activity:
Instructions:
Group yourselves into four based on the following categories:
Group 1: Break in for loop
Group 2: Break in while loop
Group 3: Continue in for loop
Group 4: Continue in while loop
Task Assignment:
• Each group will be assigned a specific task related to the usage and
understanding of break and continue statements in Python loops.
Task Execution:
• Execute the assigned task within your group.
• Analyze how the break and continue statements work in the context of the
assigned loop type (for or while).
Presentation:
• Present your findings and demonstrations to the class, explaining how break
and continue statements are utilized in different scenarios.
Discuss:
1. When would you use the break statement in a loop?
2. When would you use the continue statement in a loop?
3. What is the purpose of the pass statement in Python?
4. How are break, continue, and pass statements used in
industry-standard codebases?
Activity 1: Guessing Game with break
1. Write a Python program that generates a random number between 1
and 10.
2. Allow the user to guess the number in a loop.
3. Inside the loop:
• If the user's guess is correct, use break to exit the loop and display a
message like "Congratulations, you guessed it!".
• If the guess is higher or lower, provide hints like "Too high!" or "Too low!"
and prompt the user to guess again.
4. Once the loop exits (either by guessing correctly or exceeding a
maximum number of attempts), display a message indicating the end of
the game.
Activity 2: Filtering Even Numbers with continue
1. Create a list of numbers ranging from 1 to 20.
2. Use a for loop to iterate through the list.
3. Inside the loop:
• Use continue to skip any even number (numbers divisible by
2) and move on to the next iteration.
4. Print only the odd numbers from the list.
Activity 3: Empty Loop with pass
1. Create a while loop with a condition that is always True.
2. Indent the loop body with an empty line containing only the
pass statement.
3. Run the program and observe the behavior. The pass
statement essentially tells Python to do nothing within the
loop body.
References:
PDF
Kalb, I. (2018). Learn to Program with Python 3: A Step-by-Step Guide to Programming (2nd
ed.). ISBN-13 (pbk): 978-1-4842-3878-3, ISBN-13 (electronic): 978-1-4842-3879-0.
URL
W3schools.com. for loops. [https://www.w3schools.com/python/python_for_loops.asp]
Accessed by 16, January, 2024.
W3schools.com. while loops. [https://www.w3schools.com/python/python_while_loop.asp]
Accessed by 16, January, 2024.

This is all about control flow in python intruducing the Break and Continue.pptx

  • 1.
  • 2.
    Topic Outline: • Breakstatement • Continue statement • Pass statement
  • 3.
    Intended Learning Outcomes: •Explain the roles of break, continue, and pass statements in Python programming. • Distinguish between the break, continue, and pass statements in terms of their functionalities within loops.
  • 4.
    Introduction Using loops inPython automates and repeats the tasks in an efficient manner. But sometimes, there may arise a condition where you want to exit the loop completely, skip an iteration or ignore that condition. These can be done by loop control statements. Loop control statements change execution from their normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
  • 5.
    Python supports thefollowing control statements: • Break statement • Continue statement • Pass statement
  • 6.
    Break Statement • Thebreak statement in Python is used to terminate the loop or statement in which it is present. • After that, the control will pass to the statements that are present after the break statement, if available. If the break statement is present in the nested loop, then it terminates only those loops which contain the break statement. Syntax of Break Statement for loop: # Loop body statements if condition: break # statement(s) # loop end
  • 7.
    Break statement infor loop example #1: numbers = [1, 2, 3, 4, 5] for number in numbers: if number > 3: break print(number)
  • 8.
    Break Statement infor loop example #2: numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) num_sum = 0 count = 0 for x in numbers: num_sum = num_sum + x count = count + 1 if count == 5: break print("Sum of first ",count,"integers is: ", num_sum)
  • 9.
    Break Statement inwhile loop example #1: num_sum = 0 count = 0 while(count<10): num_sum = num_sum + count count = count + 1 if count== 3: break print("Sum of first ",count,"integers is: ", num_sum)
  • 10.
    Continue statement • Thecontinue statement is used in a while or for loop to take the control to the top of the loop without executing the rest statements inside the loop. • Continue is also a loop control statement just like the break statement. Continue statement is opposite to that of the break statement, instead of terminating the loop, it forces to execute the next iteration of the loop. • As the name suggests the continue statement forces the loop to continue or execute the next iteration. When the continue statement is executed in the loop, the code inside the loop following the continue statement will be skipped and the next iteration of the loop will begin.
  • 11.
    Continue statement The continuestatement in Python has the following syntax: for loop: # statement(s) if condition: continue # statement(s)
  • 12.
    Continue with forloop example #1. In this code prints each character of the string "Elephant", except for the letter "e". for var in “Fish": if var == “s": continue print(var)
  • 13.
    Continue with forloop example #2. In this program prints the elements of a list skipping None values my_list = [1, None, 3, 4, None, 6, None, 8] for element in my_list: if element is None: continue # Skip None values and move to the next iteration print("Current element:", element)
  • 14.
    Continue with whileloop example #1. In this example, we are using a while loop which traverses till 9 if i = 5 then skip the printing of numbers. i = 0 while i < 10: if i == 5: i += 1 continue print(i) i += 1
  • 15.
    Continue with whileloop example #2. In this program prints the first 10 positive integers, skipping odd numbers count = 0 number = 1 while count < 10: if number % 2 != 0: number += 1 continue # Skip odd numbers and move to the next iteration print("Current number:", number) count += 1 number += 1
  • 16.
    Using break andcontinue in for loop example: In this program finds the first 4 prime numbers between 1 and 20 prime_count = 0 for num in range(2, 21): for i in range(2, num): # Loop through numbers from 2 to num - 1 if num % i == 0: # If num is divisible by any number other than 1 and itself, break else: # If the inner loop completes without finding a divisor, prime_count += 1 print("Prime number found:", num) if prime_count == 4: # If we've found 4 prime numbers, break out of the outer loop break else: # If we've found only one prime number, continue searching continue print("Search complete.")
  • 17.
    Using break andcontinue in for loop example: # This program simulates a game where a player needs to guess a number between 1 and 10 import random # Generate a random number between 1 and 10 secret_number = random.randint(1, 10) print("Welcome to the Number Guessing Game!") # Allow the player to make up to 3 attempts to guess the number for attempt in range(1, 4): guess = int(input("Attempt {}: Guess the number between 1 and 10: ".format(attempt))) if guess < 1 or guess > 10: print("Please enter a number between 1 and 10.") continue # Skip the rest of the loop body and prompt the player for another guess if guess == secret_number: print("Congratulations! You guessed the correct number:", secret_number) break # Exit the loop since the player has guessed the correct number print("Sorry, that's not the correct number. Try again.") # If the loop completes without the player guessing the correct number, print the secret number else: print("Sorry, you've used all your attempts. The secret number was:", secret_number)
  • 18.
    Python pass Statement Whatis pass statement in Python? • When the user does not know what code to write, So user simply places a pass at that line. Sometimes, the pass is used when the user doesn’t want any code to execute. So users can simply place a pass where empty code is not allowed, like in loops, function definitions, class definitions, or in if statements. So using a pass statement user avoids this error.
  • 19.
    Python pass Statement Thisprogram prints even numbers between 1 and 10 and does nothing for odd numbers for i in range(1, 11): if i % 2 == 0: print(i, "is an even number.") else: pass
  • 20.
    Activity: Instructions: Group yourselves intofour based on the following categories: Group 1: Break in for loop Group 2: Break in while loop Group 3: Continue in for loop Group 4: Continue in while loop Task Assignment: • Each group will be assigned a specific task related to the usage and understanding of break and continue statements in Python loops. Task Execution: • Execute the assigned task within your group. • Analyze how the break and continue statements work in the context of the assigned loop type (for or while). Presentation: • Present your findings and demonstrations to the class, explaining how break and continue statements are utilized in different scenarios.
  • 21.
    Discuss: 1. When wouldyou use the break statement in a loop? 2. When would you use the continue statement in a loop? 3. What is the purpose of the pass statement in Python? 4. How are break, continue, and pass statements used in industry-standard codebases?
  • 22.
    Activity 1: GuessingGame with break 1. Write a Python program that generates a random number between 1 and 10. 2. Allow the user to guess the number in a loop. 3. Inside the loop: • If the user's guess is correct, use break to exit the loop and display a message like "Congratulations, you guessed it!". • If the guess is higher or lower, provide hints like "Too high!" or "Too low!" and prompt the user to guess again. 4. Once the loop exits (either by guessing correctly or exceeding a maximum number of attempts), display a message indicating the end of the game.
  • 23.
    Activity 2: FilteringEven Numbers with continue 1. Create a list of numbers ranging from 1 to 20. 2. Use a for loop to iterate through the list. 3. Inside the loop: • Use continue to skip any even number (numbers divisible by 2) and move on to the next iteration. 4. Print only the odd numbers from the list.
  • 24.
    Activity 3: EmptyLoop with pass 1. Create a while loop with a condition that is always True. 2. Indent the loop body with an empty line containing only the pass statement. 3. Run the program and observe the behavior. The pass statement essentially tells Python to do nothing within the loop body.
  • 25.
    References: PDF Kalb, I. (2018).Learn to Program with Python 3: A Step-by-Step Guide to Programming (2nd ed.). ISBN-13 (pbk): 978-1-4842-3878-3, ISBN-13 (electronic): 978-1-4842-3879-0. URL W3schools.com. for loops. [https://www.w3schools.com/python/python_for_loops.asp] Accessed by 16, January, 2024. W3schools.com. while loops. [https://www.w3schools.com/python/python_while_loop.asp] Accessed by 16, January, 2024.

Editor's Notes

  • #3 ‘Break’ in Python is a loop control statement. It is used to control the sequence of the loop. Suppose you want to terminate a loop and skip to the next code after the loop; break will help you do that. Continue statement is opposite to that of the break statement, instead of terminating the loop, it forces to execute the next iteration of the loop.
  • #5 What is for loop, is a control flow statement that allows code to be executed repeatedly. Good when you know the exact number of iterations. What is while loop, allows the code executed reapeatedly base on the given Boolean condition
  • #6 ‘Break’ in Python is a loop control statement. It is used to control the sequence of the loop. Suppose you want to terminate a loop and skip to the next code after the loop; break will help you do that. Continue statement is opposite to that of the break statement, instead of terminating the loop, it forces to execute the next iteration of the loop. When the user does not know what code to write, So user simply places a pass at that line.
  • #7  for item in sequence:: This line defines the for loop. item: This is a variable that will take on the value of each element in the sequence during each iteration of the loop. sequence: This is any iterable object like a list, tuple, or string that the loop iterates over. # Loop body statements: This section represents the code that will be executed for each element in the sequence. This is where your logic and operations using the current element (item) will be placed. if condition:: This conditional statement checks if a specific condition is met. If the condition is True, the break statement within the block will be executed. break: This statement terminates the for loop immediately if the condition evaluates to True. Once the break is executed, the program control jumps to the line immediately after the loop, skipping any remaining elements in the sequence.
  • #8 The break statement is usually used inside decision-making statements such as if...else. “1 2 3
  • #9 In the following example for loop breaks when the count value is 5. The print statement after the for loop displays the sum of first 5 elements of the tuple numbers. Sum of first 5 integers is: 15 numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9): This line initializes a tuple named numbers containing the integers from 1 to 9. num_sum = 0 and count = 0: These lines initialize two variables, num_sum to store the sum of integers and count to act as a counter for the loop. for x in numbers:: This line starts a for loop that iterates over each element x in the numbers tuple. num_sum = num_sum + x: In each iteration of the loop, the value of x is added to num_sum, accumulating the sum of the integers. count = count + 1: The value of count is incremented by 1 in each iteration to keep track of how many integers have been summed. if count == 5:: This line checks if the value of count has reached 5. break: If the value of count equals 5, the break statement is executed, causing the loop to terminate prematurely. print("Sum of first ", count, "integers is: ", num_sum): After the loop terminates, this line prints a message that includes the number of integers summed (count) and the total sum (num_sum). Let's understand how the loop works: The loop iterates over each element in the numbers tuple, summing them up until count reaches 5. When count becomes 5, the condition if count == 5: becomes True, causing the break statement to execute. As a result, the loop terminates prematurely, and the program prints the sum of the integers calculated until that point.
  • #10 In the following example while loop breaks when the count value is 5. The print statement after the while loop displays the value of num_sum (i.e. 0+1+2+3+4). OUTPUT:Sum of first 5 integers is: 10 num_sum = 0 and count = 0: These lines initialize two variables, num_sum to store the sum of integers and count to act as a counter for the loop. while(count < 10):: This line starts a while loop that continues as long as the count is less than 10. num_sum = num_sum + count: In each iteration of the loop, the value of count is added to num_sum, accumulating the sum of the integers. count = count + 1: The value of count is incremented by 1 in each iteration to move to the next integer. if count == 5:: This line checks if the value of count has reached 5. break: If the value of count equals 5, the break statement is executed, causing the loop to terminate prematurely. print("Sum of first ", count, "integers is: ", num_sum): After the loop terminates, this line prints a message that includes the number of integers summed (count) and the total sum (num_sum). Let's understand how the loop works: The loop runs until count reaches 5. During each iteration, the current value of count is added to num_sum. When count becomes 5, the condition if count == 5: becomes True, causing the break statement to execute. As a result, the loop terminates prematurely, and the program prints the sum of the integers calculated until that point.
  • #11 In the following example while loop breaks when the count value is 5. The print statement after the while loop displays the value of num_sum (i.e. 0+1+2+3+4).
  • #12 In the following example while loop breaks when the count value is 5. The print statement after the while loop displays the value of num_sum (i.e. 0+1+2+3+4).
  • #15 # prints the numbers between # 0 and 9 that are not equal to 5 1 2 3 4 6 7 8 9