Week 4: Advanced Functions & Data Processing – 40-Day Python Challenge

Welcome to Week 4! Each day’s challenge unlocks 24 hours after the current date, keeping you on track. Ready to level up? 🚀

Day 22: Functions with Variable Arguments

🔓 Unlocked

Create a flexible function that sums any number of inputs using *args. Perfect for building dynamic tools like calculators!

Sample Code


def sum_numbers(*args):
    return sum(args)

print("Sum of 2 numbers:", sum_numbers(1, 2))
print("Sum of 3 numbers:", sum_numbers(1, 2, 3))
print("Sum of 5 numbers:", sum_numbers(1, 2, 3, 4, 5))
                

Why Learn This?

This script teaches you to handle unlimited inputs, making your functions versatile. Imagine summing shopping cart totals or game scores! Try modifying it to multiply numbers in your 10-15 minute practice.

Key Concepts

Concept Description
*args Accepts any number of arguments as a tuple.
Variable Arguments Allows dynamic input counts for flexibility.
sum() Adds all items in an iterable.

Day 23: Keyword Arguments and Dictionaries

🔒 Locked

Build a function that prints personal details using **kwargs, turning keyword inputs into a dictionary. Great for user profiles!

Sample Code


def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=25)
print_info(name="Bob", city="New York", job="Engineer")
                

Why Learn This?

Learn to process flexible data like form submissions. Experiment with adding default messages or specific key checks in your practice time!

Key Concepts

Concept Description
**kwargs Accepts keyword arguments as a dictionary.
Dictionary Unpacking Uses ** to pass/receive dicts as keywords.
f-string Formats strings with embedded variables.

Day 24: List Comprehensions

🔒 Locked

Use list comprehensions to create lists of even numbers and squares in one line. A concise way to process data!

Sample Code


evens = [x for x in range(1, 11) if x % 2 == 0]
print("Evens:", evens)

numbers = [1, 3, 5]
squares = [x ** 2 for x in numbers]
print("Squares:", squares)
                

Why Learn This?

Comprehensions simplify loops for filtering (evens) or transforming (squares) data. Try filtering squares > 10 in your practice—perfect for data tasks!

Key Concepts

Concept Description
List Comprehension One-line syntax to create lists: [expr for item in iterable if condition].
Filtering Includes items based on a condition.
Mapping Transforms each item in the output list.

Day 25: Basic String Parsing

🔒 Locked

Convert a comma-separated string (e.g., “1,2,3”) into a list of integers and sum them. Ideal for processing user inputs!

Sample Code


input_str = input("Enter numbers (comma-separated): ")
num_list = [int(x) for x in input_str.split(",")]
print("Numbers:", num_list)
print("Sum:", sum(num_list))
            

Why Learn This?

Learn to parse text into usable data, like reading CSV files. Add error handling (try/except) in your practice for robustness!

Key Concepts

Concept Description
.split() Splits a string into a list at a delimiter.
Type Conversion Converts strings to integers with int().
List Comprehension Used to convert split strings to integers.

Day 26: Simple Data Validation

🔒 Locked

Create a function to validate email addresses (checks for “@” and “.com”). Essential for form processing!

Sample Code


def validate_email(email):
    return "@" in email and email.endswith(".com")

print(validate_email("user@domain.com"))  # True
print(validate_email("invalid.email"))    # False
            

Why Learn This?

Validate user inputs like emails to ensure data quality. Try adding more checks (e.g., “.” before “@”) in your practice!

Key Concepts

Concept Description
String Methods .endswith() and in for string checks.
Boolean Return Returns True/False for logic.
Validation Logic Ensures data meets specific rules.

Day 27: Basic Data Aggregation

🔒 Locked

Process a list of student score dictionaries to find the average and highest scorer. Great for analytics!

Sample Code


students = [
    {"name": "Alice", "score": 85},
    {"name": "Bob", "score": 90},
    {"name": "Charlie", "score": 78}
]
scores = [student["score"] for student in students]
average = sum(scores) / len(scores)
highest = max(students, key=lambda x: x["score"])
print("Average score:", average)
print("Highest scorer:", highest["name"], highest["score"])
            

Why Learn This?

Aggregate data like grades or sales with lists and dicts. Experiment with finding the lowest score in your practice!

Key Concepts

Concept Description
List of Dictionaries Stores structured data like records.
Aggregation Summarizes data (e.g., average, max).
Lambda Function Anonymous function for tasks like max() key.

Day 28: Review & Expand

🔒 Locked

Combine Week 4 skills: Parse numbers, validate inputs, process with a function, and store results in a dictionary.

Sample Code


def process_numbers(numbers_str):
    try:
        nums = [int(x) for x in numbers_str.split(",")]
        result = {"sum": sum(nums), "count": len(nums)}
        return result
    except ValueError:
        return {"error": "Invalid numbers"}

input_str = input("Enter numbers (comma-separated): ")
result = process_numbers(input_str)
print("Results:", result)
            

Why Learn This?

Build a mini data app combining parsing, validation, and functions. Add max/min to the result dict in your practice for a challenge!

Key Concepts

Concept Description
String Parsing Converts strings to data (e.g., split to list).
Error Handling Uses try/except for robust code.
Returning Dictionaries Stores multiple results in a dict.
Join Challenge Group 💬

Week 4: Advanced Functions & Data Processing – 40-Day Python Challenge

Welcome to Week 4! Each day’s challenge unlocks 24 hours after the current date, keeping you on track. Ready to level up? 🚀

Day 22: Functions with Variable Arguments

🔓 Unlocked

Create a flexible function that sums any number of inputs using *args. Perfect for building dynamic tools like calculators!

Sample Code


def sum_numbers(*args):
    return sum(args)

print("Sum of 2 numbers:", sum_numbers(1, 2))
print("Sum of 3 numbers:", sum_numbers(1, 2, 3))
print("Sum of 5 numbers:", sum_numbers(1, 2, 3, 4, 5))
                

Why Learn This?

This script teaches you to handle unlimited inputs, making your functions versatile. Imagine summing shopping cart totals or game scores! Try modifying it to multiply numbers in your 10-15 minute practice.

Key Concepts

Concept Description
*args Accepts any number of arguments as a tuple.
Variable Arguments Allows dynamic input counts for flexibility.
sum() Adds all items in an iterable.

Day 23: Keyword Arguments and Dictionaries

🔒 Locked

Build a function that prints personal details using **kwargs, turning keyword inputs into a dictionary. Great for user profiles!

Sample Code


def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=25)
print_info(name="Bob", city="New York", job="Engineer")
                

Why Learn This?

Learn to process flexible data like form submissions. Experiment with adding default messages or specific key checks in your practice time!

Key Concepts

Concept Description
**kwargs Accepts keyword arguments as a dictionary.
Dictionary Unpacking Uses ** to pass/receive dicts as keywords.
f-string Formats strings with embedded variables.

Day 24: List Comprehensions

🔒 Locked

Use list comprehensions to create lists of even numbers and squares in one line. A concise way to process data!

Sample Code


evens = [x for x in range(1, 11) if x % 2 == 0]
print("Evens:", evens)

numbers = [1, 3, 5]
squares = [x ** 2 for x in numbers]
print("Squares:", squares)
                

Why Learn This?

Comprehensions simplify loops for filtering (evens) or transforming (squares) data. Try filtering squares > 10 in your practice—perfect for data tasks!

Key Concepts

Concept Description
List Comprehension One-line syntax to create lists: [expr for item in iterable if condition].
Filtering Includes items based on a condition.
Mapping Transforms each item in the output list.

Day 25: Basic String Parsing

🔒 Locked

Convert a comma-separated string (e.g., “1,2,3”) into a list of integers and sum them. Ideal for processing user inputs!

Sample Code


input_str = input("Enter numbers (comma-separated): ")
num_list = [int(x) for x in input_str.split(",")]
print("Numbers:", num_list)
print("Sum:", sum(num_list))
            

Why Learn This?

Learn to parse text into usable data, like reading CSV files. Add error handling (try/except) in your practice for robustness!

Key Concepts

Concept Description
.split() Splits a string into a list at a delimiter.
Type Conversion Converts strings to integers with int().
List Comprehension Used to convert split strings to integers.

Day 26: Simple Data Validation

🔒 Locked

Create a function to validate email addresses (checks for “@” and “.com”). Essential for form processing!

Sample Code


def validate_email(email):
    return "@" in email and email.endswith(".com")

print(validate_email("user@domain.com"))  # True
print(validate_email("invalid.email"))    # False
            

Why Learn This?

Validate user inputs like emails to ensure data quality. Try adding more checks (e.g., “.” before “@”) in your practice!

Key Concepts

Concept Description
String Methods .endswith() and in for string checks.
Boolean Return Returns True/False for logic.
Validation Logic Ensures data meets specific rules.

Day 27: Basic Data Aggregation

🔒 Locked

Process a list of student score dictionaries to find the average and highest scorer. Great for analytics!

Sample Code


students = [
    {"name": "Alice", "score": 85},
    {"name": "Bob", "score": 90},
    {"name": "Charlie", "score": 78}
]
scores = [student["score"] for student in students]
average = sum(scores) / len(scores)
highest = max(students, key=lambda x: x["score"])
print("Average score:", average)
print("Highest scorer:", highest["name"], highest["score"])
            

Why Learn This?

Aggregate data like grades or sales with lists and dicts. Experiment with finding the lowest score in your practice!

Key Concepts

Concept Description
List of Dictionaries Stores structured data like records.
Aggregation Summarizes data (e.g., average, max).
Lambda Function Anonymous function for tasks like max() key.

Day 28: Review & Expand

🔒 Locked

Combine Week 4 skills: Parse numbers, validate inputs, process with a function, and store results in a dictionary.

Sample Code


def process_numbers(numbers_str):
    try:
        nums = [int(x) for x in numbers_str.split(",")]
        result = {"sum": sum(nums), "count": len(nums)}
        return result
    except ValueError:
        return {"error": "Invalid numbers"}

input_str = input("Enter numbers (comma-separated): ")
result = process_numbers(input_str)
print("Results:", result)
            

Why Learn This?

Build a mini data app combining parsing, validation, and functions. Add max/min to the result dict in your practice for a challenge!

Key Concepts

Concept Description
String Parsing Converts strings to data (e.g., split to list).
Error Handling Uses try/except for robust code.
Returning Dictionaries Stores multiple results in a dict.
Join Challenge Group 💬

Scroll to Top