CONTROL STATEMENTS IN PYTHON
Let’s learn about the control statements in python now, control statements change the way we execute a loop from it’s normal behavior. There are many types of control statements in python that you can use to control the loops:
Break statement is used to terminate or abandon the loop. Once the loop breaks then the next statement after the break continues. The main reason we could use the break statement is to take a quick exit from a nested loop (i.e. a loop within a loop). The break statement is used with both while and for loop.
This is how a break statement works within a loop:
Let’s look at a quick example of how to use a break statement to exit a while loop:
country_name = "\nPlease enter the name of the country you love: " while True: country = input(country_name) if country == 'quit': break else: print("My favorite country is: " + country.title())
Please enter the name of the country you love: France My favorite country is: France Please enter the name of the country you love: quit ***Repl Closed***
Continue statement in Python is used to continue running the program even after the program encounters a break during execution. The continue statement enables the code to proceed inside a loop and move on skipping the particular condition.
This is how a continue statement works within a loop:
Let’s look at a quick example of how to use a continue statement inside a loop:
for letter in 'Py thon': if letter == ' ': continue print ('Letters:', letter)
The above code will print the following output:
Letters: P Letters: y Letters: t Letters: h Letters: o Letters: n
The execution will skip the ‘space’ character and continue to print the rest of the loop without any interruptions.
The pass statement is used when comment cannot be printed to show the program’s status to the programmer. It is always going to be a null operation. For example if a programmer has written a comment within the code, then that comment will be ignored but the pass statement won’t be ignored. It will be used as a placeholder.
Let’s look at a quick example of how to use a pass statement in Python:
for letter in 'Python': if letter == 'h': pass print("We are still printing letters") print ('Letters:', letter)
Letters: P Letters: y Letters: t We are still printing letters Letters: h Letters: o Letters: n