How to Use Python FOR LOOPS
Python’s for
loop is a versatile tool for iterating over data, essential for any business dealing with datasets. Let’s dive right into how businesses can leverage this.
Basic Syntax
for variable in iterable:
This is the fundamental syntax of the “for” loop in Python .
- “
variable
” is a temporary variable that takes the value of each item in theiterable
during each iteration. Usually, you will see this value as “I”. - “
iterable
” can be any object that supports iteration, such as lists, tuples, strings, dictionaries, etc.
What’s an iterable?
An iterable is any Python object you can loop over, like lists, strings, or dictionaries. It lets you go through its items one by one. List, tuples, dictionaries, and strings
Looping Through Sales Data (List)
Imagine you have monthly sales figures:
sales = [1200, 1350, 1100, 1250]
for sale in sales:
if sale > 1300:
print("High Sale:", sale)
Analyzing Feedback (String)
Loop through customer feedback to count negative words:
feedback = "The product is bad and not working."
negative_words = ['bad', 'not', 'poor']
count = 0
for word in feedback.split():
if word in negative_words:
count += 1
print("Negative word count:", count)
Looping Through Employee Records (Dictionary)
Check which employees exceeded their sales targets:
targets = {"Alice": 1200, "Bob": 1100, "Charlie": 1300}
actuals = {"Alice": 1250, "Bob": 1050, "Charlie": 1400}
for employee, target in targets.items():
if actuals[employee] > target:
print(employee, "exceeded target!")
range()
for Repetitive Tasks
Send a weekly report 4 times:
for week in range(1, 5):
print(f"Sending report for week {week}")
Alternatives to Loops
You can use quite a few different Python methods that have a similar function to a for loop. The most often used is List Comprehension. “While” loops are also similar to “for” loops but are applicable when Used when you want to iterate based on a condition rather than iterating over an iterable. Recursive functions are also an alternative to looping.