Python Control Structures: Loops, Conditionals, and Data Processing

This section focuses on reading Python code that demonstrates control structures in a Pythonic way - emphasizing readability, built-in functions, and elegant data processing patterns.

Python Reading Strategy: Notice how Python’s syntax makes control flow very readable. Pay attention to indentation, built-in functions like enumerate() and zip(), and list comprehensions that replace traditional loops.

How to Read Python Control Structures

  • Python uses indentation for structure - No braces needed, indentation shows control flow
  • Built-in functions simplify loops - enumerate(), zip(), range() make code cleaner
  • List/dict comprehensions - Compact way to transform data, replace many loops
  • Idiomatic Python - for item in collection, if not list, truthiness patterns

Example 1: Shopping Cart with Complex Conditional Logic

Code to Read:

  1def process_shopping_data():
  2    """Demonstrate Python number operations with shopping cart calculations."""
  3    
  4    # Basic number types and operations
  5    item_count = 12
  6    unit_price = 15.99
  7    tax_rate = 0.08
  8    shipping_threshold = 50.0
  9    
 10    print("=== Shopping Cart Calculation ===")
 11    print(f"Items: {item_count}")
 12    print(f"Unit price: ${unit_price}")
 13    print(f"Tax rate: {tax_rate * 100}%")
 14    
 15    # Mathematical calculations
 16    subtotal = unit_price * item_count
 17    tax_amount = subtotal * tax_rate
 18    total_before_shipping = subtotal + tax_amount
 19    
 20    # Conditional shipping calculation
 21    if total_before_shipping >= shipping_threshold:
 22        shipping_cost = 0.0
 23        shipping_message = "Free shipping!"
 24    else:
 25        shipping_cost = 8.99
 26        needed_for_free = shipping_threshold - total_before_shipping
 27        shipping_message = f"Add ${needed_for_free:.2f} for free shipping"
 28    
 29    final_total = total_before_shipping + shipping_cost
 30    
 31    print(f"\n=== Price Breakdown ===")
 32    print(f"Subtotal: ${subtotal:.2f}")
 33    print(f"Tax: ${tax_amount:.2f}")
 34    print(f"Shipping: ${shipping_cost:.2f}")
 35    print(f"Final total: ${final_total:.2f}")
 36    print(f"Shipping note: {shipping_message}")
 37    
 38    # Number formatting and mathematical operations
 39    price_per_item_with_tax = (subtotal + tax_amount) / item_count
 40    rounded_total = round(final_total, 2)
 41    whole_dollars = int(final_total)
 42    cents = final_total - whole_dollars
 43    
 44    print(f"\n=== Detailed Analysis ===")
 45    print(f"Price per item (with tax): ${price_per_item_with_tax:.3f}")
 46    print(f"Rounded total: ${rounded_total}")
 47    print(f"Whole dollars: ${whole_dollars}")
 48    print(f"Cents portion: {cents:.2f}")
 49    
 50    # Mathematical functions
 51    import math
 52    
 53    sqrt_items = math.sqrt(item_count)
 54    items_squared = item_count ** 2
 55    max_value = max(item_count, whole_dollars)
 56    min_value = min(item_count, whole_dollars)
 57    absolute_difference = abs(item_count - whole_dollars)
 58    
 59    print(f"\n=== Math Operations ===")
 60    print(f"Square root of items: {sqrt_items:.2f}")
 61    print(f"Items squared: {items_squared}")
 62    print(f"Maximum value: {max_value}")
 63    print(f"Minimum value: {min_value}")
 64    print(f"Absolute difference: {absolute_difference}")
 65    
 66    # String to number conversion with error handling
 67    price_string = "24.95"
 68    quantity_string = "7"
 69    
 70    try:
 71        parsed_price = float(price_string)
 72        parsed_quantity = int(quantity_string)
 73        combined_value = parsed_price * parsed_quantity
 74        
 75        print(f"\n=== String to Number Conversion ===")
 76        print(f"Parsed price: ${parsed_price}")
 77        print(f"Parsed quantity: {parsed_quantity}")
 78        print(f"Combined value: ${combined_value:.2f}")
 79        
 80    except ValueError as e:
 81        print(f"Error converting strings to numbers: {e}")
 82    
 83    # Percentage calculations
 84    discount_percent = 15
 85    discount_amount = subtotal * (discount_percent / 100)
 86    discounted_price = subtotal - discount_amount
 87    savings_ratio = discount_amount / subtotal
 88    
 89    print(f"\n=== Discount Analysis ===")
 90    print(f"Original subtotal: ${subtotal:.2f}")
 91    print(f"Discount ({discount_percent}%): ${discount_amount:.2f}")
 92    print(f"After discount: ${discounted_price:.2f}")
 93    print(f"Savings ratio: {savings_ratio:.1%}")
 94    
 95    return {
 96        'subtotal': subtotal,
 97        'tax': tax_amount,
 98        'shipping': shipping_cost,
 99        'total': final_total,
100        'item_count': item_count
101    }
102
103# Example usage
104if __name__ == "__main__":
105    cart_data = process_shopping_data()
106    print(f"\nReturned data: {cart_data}")
107    print(f"Average cost per item: ${cart_data['total'] / cart_data['item_count']:.2f}")

What to Notice:

Python's Readable Conditional Logic

Clean if-else structure:

1if total_before_shipping >= shipping_threshold:
2    shipping_cost = 0.0
3    shipping_message = "Free shipping!"
4else:
5    shipping_cost = 8.99
6    # Complex calculation inside conditional
7    needed_for_free = shipping_threshold - total_before_shipping
8    shipping_message = f"Add ${needed_for_free:.2f} for free shipping"

F-string formatting with calculations:

  • Variables can be calculated inside f-strings
  • :.2f formats numbers to 2 decimal places
  • :.1% automatically converts decimals to percentages
Built-in Functions and Error Handling

Mathematical functions:

  • round(), max(), min(), abs() work directly with numbers
  • math.sqrt() and ** operator for exponentiation
  • Type conversion: int(), float() for string parsing

Exception handling:

1try:
2    parsed_price = float(price_string)
3    # ... more operations
4except ValueError as e:
5    print(f"Error converting strings to numbers: {e}")
Dictionary Return Patterns

Structured data return:

1return {
2    'subtotal': subtotal,
3    'tax': tax_amount,
4    'shipping': shipping_cost,
5    'total': final_total,
6    'item_count': item_count
7}
  • Functions return dictionaries for structured data
  • Keys provide self-documenting access to results
  • Easier to extend than returning multiple values

Trace Through Example:

 1# Initial values:
 2item_count = 12, unit_price = 15.99, tax_rate = 0.08
 3
 4# Calculations:
 5subtotal = 15.99 * 12 = 191.88
 6tax_amount = 191.88 * 0.08 = 15.35 (rounded)
 7total_before_shipping = 191.88 + 15.35 = 207.23
 8
 9# Conditional logic:
10if 207.23 >= 50.0:  # True
11    shipping_cost = 0.0
12    shipping_message = "Free shipping!"
13
14final_total = 207.23 + 0.0 = 207.23

Example 2: List Processing with Loops and Comprehensions

Code to Read:

  1def analyze_customer_feedback():
  2    """Demonstrate string operations and list processing with customer feedback."""
  3    
  4    # Sample customer feedback data
  5    reviews = [
  6        "  EXCELLENT service and fast delivery! Really happy with my purchase.  ",
  7        "good product, but shipping was slow",
  8        "Amazing quality! Will definitely buy again. 5 stars!!!",
  9        "Poor packaging, item arrived damaged :(",
 10        "Best online store ever! Great customer service.",
 11        "Product was okay, nothing special"
 12    ]
 13    
 14    print("=== Original Feedback ===")
 15    for i, review in enumerate(reviews, 1):  # Start numbering at 1
 16        print(f"{i}. '{review}'")
 17    
 18    # String cleaning using list comprehension
 19    cleaned_reviews = []
 20    for review in reviews:
 21        cleaned = review.strip().lower()
 22        # Remove excessive punctuation
 23        cleaned = cleaned.replace('!!!', '!').replace('!!', '!')
 24        cleaned_reviews.append(cleaned)
 25    
 26    print(f"\n=== Cleaned Reviews ===")
 27    for i, review in enumerate(cleaned_reviews, 1):
 28        print(f"{i}. '{review}'")
 29    
 30    # List comprehension for length analysis
 31    review_lengths = [len(review) for review in cleaned_reviews]
 32    total_characters = sum(review_lengths)
 33    longest_review = max(cleaned_reviews, key=len)
 34    shortest_review = min(cleaned_reviews, key=len)
 35    
 36    print(f"\n=== Length Analysis ===")
 37    print(f"Total reviews: {len(reviews)}")
 38    print(f"Review lengths: {review_lengths}")
 39    print(f"Total characters: {total_characters}")
 40    print(f"Average length: {total_characters / len(reviews):.1f}")
 41    print(f"Longest: '{longest_review}'")
 42    print(f"Shortest: '{shortest_review}'")
 43    
 44    # Word frequency analysis
 45    all_words = []
 46    for review in cleaned_reviews:
 47        words = review.split()
 48        all_words.extend(words)
 49    
 50    # Count word frequencies using dictionary
 51    word_counts = {}
 52    for word in all_words:
 53        # Remove punctuation for counting
 54        clean_word = word.strip('.,!:();')
 55        if clean_word:  # Skip empty strings
 56            word_counts[clean_word] = word_counts.get(clean_word, 0) + 1
 57    
 58    # Find most common words
 59    sorted_words = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
 60    
 61    print(f"\n=== Word Frequency (Top 10) ===")
 62    for word, count in sorted_words[:10]:
 63        print(f"'{word}': {count}")
 64    
 65    # Sentiment analysis (simple keyword-based)
 66    positive_words = ['excellent', 'good', 'amazing', 'great', 'best', 'happy']
 67    negative_words = ['poor', 'slow', 'damaged', 'bad', 'terrible', 'awful']
 68    
 69    sentiment_scores = []
 70    for review in cleaned_reviews:
 71        positive_score = sum(1 for word in positive_words if word in review)
 72        negative_score = sum(1 for word in negative_words if word in review)
 73        net_sentiment = positive_score - negative_score
 74        sentiment_scores.append(net_sentiment)
 75    
 76    print(f"\n=== Sentiment Analysis ===")
 77    for i, (review, score) in enumerate(zip(cleaned_reviews, sentiment_scores), 1):
 78        sentiment = "Positive" if score > 0 else "Negative" if score < 0 else "Neutral"
 79        print(f"{i}. {sentiment} ({score:+d}): '{review[:50]}...'")
 80    
 81    # Statistics
 82    positive_count = sum(1 for score in sentiment_scores if score > 0)
 83    negative_count = sum(1 for score in sentiment_scores if score < 0)
 84    neutral_count = len(sentiment_scores) - positive_count - negative_count
 85    
 86    print(f"\n=== Overall Statistics ===")
 87    print(f"Total reviews: {len(reviews)}")
 88    print(f"Positive: {positive_count} ({positive_count/len(reviews)*100:.1f}%)")
 89    print(f"Negative: {negative_count} ({negative_count/len(reviews)*100:.1f}%)")
 90    print(f"Neutral: {neutral_count} ({neutral_count/len(reviews)*100:.1f}%)")
 91    print(f"Total unique words: {len(word_counts)}")
 92    print(f"Average words per review: {len(all_words) / len(reviews):.1f}")
 93    
 94    return {
 95        'reviews': cleaned_reviews,
 96        'word_counts': word_counts,
 97        'sentiment_scores': sentiment_scores,
 98        'stats': {
 99            'positive': positive_count,
100            'negative': negative_count,
101            'neutral': neutral_count
102        }
103    }
104
105# Example usage
106if __name__ == "__main__":
107    analysis = analyze_customer_feedback()
108    print(f"\nMost positive review score: {max(analysis['sentiment_scores'])}")
109    print(f"Most negative review score: {min(analysis['sentiment_scores'])}")

What to Notice:

Python Loop Patterns and Built-ins

enumerate() for indexed loops:

1for i, review in enumerate(reviews, 1):  # Start at 1
2    print(f"{i}. '{review}'")
  • More Pythonic than for i in range(len(reviews))
  • Automatically provides both index and value

zip() for parallel iteration:

1for i, (review, score) in enumerate(zip(cleaned_reviews, sentiment_scores), 1):
  • Combines multiple iterables
  • Automatically stops at shortest sequence
List Comprehensions and Data Processing

List comprehension for transformation:

1review_lengths = [len(review) for review in cleaned_reviews]
  • More concise than equivalent for loop
  • Creates new list from existing data

Conditional expressions in comprehensions:

1positive_count = sum(1 for score in sentiment_scores if score > 0)
  • Combines iteration, filtering, and counting
  • sum() with generator expression for efficiency
Dictionary Operations and Frequency Counting

Dictionary.get() for safe counting:

1word_counts[clean_word] = word_counts.get(clean_word, 0) + 1
  • Avoids KeyError when key doesn’t exist
  • More concise than if/else checking

Sorting with lambda functions:

1sorted_words = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
  • lambda x: x[1] sorts by count (second element of tuple)
  • reverse=True for descending order
String Processing Methods

String cleaning pipeline:

1cleaned = review.strip().lower()
2cleaned = cleaned.replace('!!!', '!').replace('!!', '!')
  • Method chaining for multiple transformations
  • strip() removes whitespace, lower() normalizes case

String splitting and joining:

1words = review.split()  # Split on whitespace
2clean_word = word.strip('.,!:();')  # Remove punctuation

Trace Through Example:

 1# Initial data:
 2reviews = ["  EXCELLENT service...", "good product...", ...]
 3
 4# Processing first review:
 5review = "  EXCELLENT service and fast delivery! Really happy..."
 6cleaned = review.strip().lower()  # "excellent service and fast delivery!..."
 7words = cleaned.split()  # ["excellent", "service", "and", "fast", ...]
 8
 9# Sentiment analysis:
10positive_words in "excellent service..."  finds "excellent"  +1
11negative_words in "excellent service..."  finds none  0
12net_sentiment = 1 - 0 = 1 (Positive)
13
14# Final statistics:
15positive_count = sum([1, 0, 1, -1, 1, 0])  # Count scores > 0
16# Result: 3 positive reviews out of 6 total

Practice Exercises

Reading Exercise 1: Trace through the shopping cart calculation with item_count=5, unit_price=9.99. Will shipping be free?

Reading Exercise 2: In the feedback analyzer, what happens if you add the word “great” to a review? How does it affect the sentiment score?

Reading Exercise 3: Compare the Python list comprehension [len(review) for review in reviews] with the equivalent Java code. Which is more readable?

Reading Exercise 4: Identify all the places where Python’s built-in functions (enumerate, zip, sum, max, min) simplify the code compared to manual loops.

← Previous: Fundamentals Next: Advanced Examples →