Index
Loops in Python
While Loop in Python
For Loop in Python
Iterators and Iteration in Python
Break and Continue Keywords
range() Function
Linear Search
pass Statement
1. Loops in Python
Definition:
Loops are a fundamental concept in programming that allow you to execute a block of code repeatedly, either a specific number of times or until a certain condition is met. This can save time, reduce code redundancy, and help in managing repetitive tasks effectively.
Use-Case Example:
Imagine you need to print numbers from 1 to 100. Instead of writing 100 print
statements, you can use a loop to accomplish this task in just a few lines of code.
Syntax:
# Generic loop structure in Python
while condition:
# Code block to be executed
for variable in sequence:
# Code block to be executed
Rules:
Loops can run indefinitely if not properly controlled.
Loop conditions are evaluated before each iteration.
Python supports
while
andfor
loops, each suited for different scenarios.
Basic Example:
# Printing numbers 1 to 5 using a while loop
i = 1
while i <= 5:
print(i)
i += 1
2. While Loop in Python
Definition:
The while
loop in Python repeatedly executes a block of code as long as the given condition is true. It's useful when the number of iterations is not known beforehand.
Use-Case Example:
A while
loop can be used to keep a program running until a user decides to quit, such as in a menu-driven console application.
Syntax:
while condition:
# Code block to be executed
Rules:
The condition is checked before entering the loop. If the condition is
False
, the loop is skipped.The loop can become infinite if the condition never becomes
False
.
Basic Example:
# Counting down from 5 using a while loop
count = 5
while count > 0:
print(count)
count -= 1
3. For Loop in Python
Definition:
The for
loop in Python iterates over a sequence (like a list, tuple, or string) and executes a block of code for each item in the sequence.
Use-Case Example:
A for
loop is ideal for iterating through a list of items, such as printing each element in a list of names.
Syntax:
for item in sequence:
# Code block to be executed
Rules:
The loop iterates over each item in the sequence.
The loop ends when there are no more items to iterate over.
Basic Example:
# Printing each character in a string using a for loop
for char in "Python":
print(char)
4. Iterators and Iteration in Python
Definition:
An iterator is an object in Python that contains a countable number of values and can be traversed, i.e., iterated upon. The process of looping over an iterable object is called iteration.
Use-Case Example:
Iterators are useful when you need to traverse through all the elements of a collection, such as reading each line in a file.
Syntax:
iterable = [1, 2, 3]
iterator = iter(iterable)
for item in iterator:
# Code block to be executed
Rules:
Not all objects are iterable; they must implement the
__iter__()
and__next__()
methods.Iteration stops when there are no more elements to retrieve.
Basic Example:
# Iterating through a list using an iterator
numbers = [1, 2, 3]
iterator = iter(numbers)
for num in iterator:
print(num)
5. Break and Continue Keywords
Definition:
The break
and continue
statements are control flow tools in loops. break
exits the loop prematurely, while continue
skips the rest of the code inside the loop for the current iteration and jumps to the next iteration.
Use-Case Example:
break
: Exiting a loop when a certain condition is met, such as stopping a search when an item is found.continue
: Skipping even numbers while iterating through a list of numbers.
Syntax:
# break
for item in sequence:
if condition:
break
# continue
for item in sequence:
if condition:
continue
Rules:
break
ends the loop entirely.continue
only skips the current iteration and continues with the next one.
Basic Example:
# Using break to exit loop
for num in range(10):
if num == 5:
break
print(num)
# Using continue to skip even numbers
for num in range(10):
if num % 2 == 0:
continue
print(num)
6. range() Function
Definition:
The range()
function in Python generates a sequence of numbers, often used with loops to iterate over a block of code a specified number of times.
Use-Case Example:range()
is commonly used in for
loops to iterate a specific number of times or to create sequences of numbers.
Syntax:
range(start, stop[, step])
Rules:
The
start
parameter is inclusive, and thestop
parameter is exclusive.step
is optional and defaults to 1.
Basic Example:
# Using range to print numbers from 0 to 4
for i in range(5):
print(i)
7. Linear Search
Definition:
Linear search is a simple search algorithm that checks each element in a list one by one until the desired element is found or the list ends.
Use-Case Example:
Linear search is useful when dealing with small or unsorted data sets where the overhead of more complex algorithms isn't justified.
Syntax:
def linear_search(sequence, target):
for index, item in enumerate(sequence):
if item == target:
return index
return -1
Rules:
The time complexity is O(n), where n is the number of elements in the sequence.
Basic Example:
# Implementing linear search
def linear_search(sequence, target):
for index, item in enumerate(sequence):
if item == target:
return index
return -1
numbers = [10, 20, 30, 40, 50]
result = linear_search(numbers, 30)
print("Found at index:", result)
8. pass Statement
Definition:
The pass
statement in Python is a null operation. It is used as a placeholder for future code. When the pass
statement is executed, nothing happens, but it can act as a placeholder in loops, functions, classes, or conditionals.
Use-Case Example:pass
is useful when you're working on new code and want to implement the logic later without causing syntax errors.
Syntax:
pass
Rules:
The
pass
statement does nothing and is ignored by the interpreter.It is commonly used when a statement is syntactically required but you have nothing to write.
Basic Example:
# Using pass as a placeholder
for i in range(5):
pass # Placeholder for future implementation