Python Functions and Lambda Expressions: What I Learned Today
Today was one of those productive days in my Python learning journey. I dove deeper into functions, understood how return statements work, and even got introduced to the sleek and compact lambda functions. Here’s a quick breakdown of what I covered:
Understanding Functions in Python
A function is like a blender — you feed in ingredients (data), it processes them, and gives you a result (smoothie 🍓). In Python, a function is a named block of reusable code that performs a specific task.
Basic Function Structure
def function_name(parameters):
# code block
Parameters are the variables inside the function definition.
Arguments are the actual values you pass when calling the function.
Example: Greeting a User
def greet(name): # Function definition
print(f"Hello {name}!")
name = input("Enter your name: ")
greet(name) # Function call with argument
Returning Values from a Function
Functions aren’t limited to just printing — they can also return values for further processing.
Addition Example
def add(a, b):
return a + b
result = add(6, 8)
print(f"The sum is: {result}")
Multiplication Example
def multiply(a, b):
return a * b
print(multiply(23, 10))
Function Exercises
✅ Square of a Number
def square(num):
return pow(num, 2)
print(square(6))
➕ Adding Three Numbers
def add(a, b, c):
return a + b + c
print(add(1, 2, 3))
🔎 Even or Odd Check
def checks_even(number):
if number % 2 == 0:
print("The number is even")
else:
print("The number is odd")
number = int(input("Enter any number: "))
checks_even(number)
Combining Strings
def combine_strings(str1, str2):
return str1 + str2
str1 = input("Enter your name: ")
str2 = input("Enter your profession: ")
combined = combine_strings(str1, str2)
print(f"My name is {str1} and my profession is {str2}")
Enter Lambda Functions
Lambda functions are small, anonymous functions used when you want a quick, throwaway function — one-liners without the def keyword.
double = lambda x: x * 2
add = lambda a, b: a + b
square = lambda y: y * y
print(double(2)) # Output: 4
print(add(10, 20)) # Output: 30
print(square(8)) # Output: 64
🎯 Final Thoughts
Functions form the core of any Python program. Learning how to define and use them — especially with return statements and even lambda for quick tasks — really enhances how I structure and reuse code. This is another solid step toward writing cleaner and more efficient Python!