Combining Everything: Functions, Conditions, and Loops
In this lesson, you'll see how to combine all the major concepts you've learned so far: functions, conditions, loops, and return values. This is where Python starts to feel powerful and expressive.
Combining Concepts
You can use loops inside functions, functions inside conditions, and even multiple functions working together.
Let’s walk through some examples:
Example 1: Filtering Even Numbers
def get_even_numbers(numbers):
evens = []
for number in numbers:
if number % 2 == 0:
evens.append(number)
return evens
nums = [1, 2, 3, 4, 5, 6]
print(get_even_numbers(nums)) # Output: [2, 4, 6]
Example 2: Sum of Positive Numbers
def sum_positive(numbers):
total = 0
for n in numbers:
if n > 0:
total += n
return total
print(sum_positive([-2, 5, 3, -1])) # Output: 8
Example 3: Check if a String is a Palindrome
def is_palindrome(word):
return word == word[::-1]
print(is_palindrome("level")) # Output: True
print(is_palindrome("python")) # Output: False
Mini Project Example
Let’s say we want a function that takes a list of names and returns the ones that are longer than 4 characters and start with a vowel.
def filter_names(names):
vowels = "aeiouAEIOU"
result = []
for name in names:
if len(name) > 4 and name[0] in vowels:
result.append(name)
return result
name_list = ["John", "Emily", "Oscar", "Uma", "Alan", "Irene"]
print(filter_names(name_list)) # Output: ['Emily', 'Oscar', 'Irene']
This example used:
- A loop
- An if condition
- A return value
- String operations
Exercise: Try It Yourself!
- Write a function that returns all odd numbers from a list.
- Write a function that checks if a number is prime.
- Write a function that receives a list of words and returns those with more than 5 letters.
- Combine loops and conditions to write a function that finds the sum of even numbers between 1 and 100.
Summary
- Python becomes powerful when you combine its building blocks.
- You can nest loops, conditions, and function calls to solve complex problems.
- Keep your functions clean and reusable.