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 = count = 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 = count = 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 t his 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 = 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 = number = 1 while count < 10 : if number % 2 != : 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 p rogram finds the first 4 prime numbers between 1 and 20 prime_count = for num in range ( 2 , 21 ): for i in range ( 2 , num ): # Loop through numbers from 2 to num - 1 if num % i == : # 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 == : 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: When would you use the break statement in a loop? When would you use the continue statement in a loop? What is the purpose of the pass statement in Python? How are break, continue, and pass statements used in industry-standard codebases?
Activity 1: Guessing Game with break Write a Python program that generates a random number between 1 and 10. Allow the user to guess the number in a loop. 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 Create a list of numbers ranging from 1 to 20. Use a for loop to iterate through the list. 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 Create a while loop with a condition that is always True. Indent the loop body with an empty line containing only the pass statement. 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.