Loops and Control Statements
Loops are a fundamental concept in programming that allow us to repeat a set of instructions multiple times. In Python, there are two types of loops: for loops and while loops. In this lecture, we will cover both types of loops in depth, including how to use them, how to control their behavior, and common use cases.
For loops
A for loop is used to iterate over a sequence of items, such as a list, tuple, or string. Here's the basic syntax of a for loop:
for item in sequence:
# do something with item
The for keyword starts the loop, followed by a loop variable (item in this case) that takes on each value in the sequence one at a time. The in keyword separates the loop variable from the sequence. The colon at the end of the first line indicates the start of a new block of code, which is indented one level deeper than the for statement.
Let's look at an example:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
In this example, we have a list of fruits, and we use a for loop to iterate over each fruit and print it to the console. The loop variable fruit takes on the value of each item in the list in turn, starting with 'apple', then 'banana', and finally 'cherry'.
Range Function
The range() function is commonly used in for loops to generate a sequence of numbers. Here's the basic syntax of the range() function:
range(start, stop, step)
The range() function generates a sequence of numbers starting from start (inclusive) and ending at stop (exclusive), with a step size of step (default is 1). The start and step arguments are optional, and the default values are 0 and 1, respectively. Here's an example:
for i in range(5):
print(i)
This code will print the numbers 0 through 4 to the console.
While Loops
A while loop is used to repeatedly execute a block of code as long as a certain condition is true. Here's the basic syntax of a while loop:
while condition:
# do something
The while keyword starts the loop, followed by a condition that is checked before each iteration of the loop. If the condition is true, the block of code inside the loop is executed. This continues until the condition becomes false.
Let's look at an example
i = 0
while i < 5:
print(i)
i += 1
In this example, we use a while loop to print the numbers 0 through 4 to the console. The condition 'i < 5' is checked before each iteration of the loop. As long as 'i' is less than 5, the block of code inside the loop is executed. Inside the loop, we print the value of 'i' and then increment it by 1 using the '+=' operator.
Control Statements
In Python, we can use control statements such as break, continue, and pass to control the behavior of loops.
- break: terminates the loop and exits the loop's block of code.
- continue: skips the current iteration of the loop and moves on to the next one.
- pass: does nothing and is used as a placeholder when a statement is missing or incomplete.
Here are more details about control statements:
-
break: The break statement is used to terminate a loop prematurely. When the break statement is executed inside a loop, the loop is immediately exited and the program continues with the next statement after the loop. Here's an example:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
if fruit == 'banana':
break
print(fruit)
In this example, we use a for loop to iterate over a list of fruits. Inside the loop, we use an if statement to check whether the current fruit is 'banana'. If it is, we execute the break statement to exit the loop prematurely. If it's not, we print the fruit to the console.
-
continue: The continue statement is used to skip over the current iteration of a loop and move on to the next one. When the continue statement is executed inside a loop, the remaining code in the loop's block is skipped and the loop immediately moves on to the next iteration. Here's an example:
for i in range(10):
if i % 2 == 0:
continue
print(i)
In this example, we use a for loop and the range() function to iterate over the numbers 0 through 9. Inside the loop, we use an if statement to check whether the current number is even (i % 2 == 0). If it is, we execute the continue statement to skip over the remaining code in the loop's block. If it's not, we print the number to the console.
-
pass: The pass statement is used as a placeholder when a statement is required syntactically but doesn't do anything. It is commonly used as a placeholder when you're defining a function or class that you plan to implement later. Here's an example:
if x < 0:
print('x is negative')
elif x == 0:
pass
else:
print('x is positive')
In this example, we use an if statement to check the value of x. If x is negative, we print a message to the console. If x is zero, we don't want to do anything, so we use the pass statement as a placeholder. If x is positive, we print a different message to the console.
Conclusion
Loops are an essential concept in programming, and Python provides two types of loops (for and while) to help us repeat a set of instructions multiple times. We can use control statements such as break, continue, and pass to control the behavior of loops and make them more powerful.
Basic Topics
- Introduction to Python
- Basic Syntax and Data Types
- Variables and Operators
- Input
- Conditional statements
- Loops
- Functions
- List
- Tuples
- Sets
- Dictionary
- Modules
- Packages
- Exception Handling
- Read/Write Files