Python Basics: Functions
Continuation of Python Basics — After
Control Structures
Immersion compiled by:
Prof. Mohammed TAMALI
Head Of SimulIA Team
ENERGARID Lab.
Overview
• This lesson builds upon variables and control structures.
• It introduces reusable code blocks known as functions.
• Topics covered:
• Function definition
• Parameters and return values
• Default and keyword arguments
• Variable arguments (*args, **kwargs)
• Lambda (anonymous) functions
SDE roots with optimized code
from cmath import sqrt
a, b, c = map(float, input("Saisissez trois nombres séparés par un espace: ").split())
delta = b**2 - 4*a*c
x1, x2 = (-b + sqrt(delta))/(2*c), (-b - sqrt(delta))/(2*c)
print(f"Delta={delta}\na={a:.3f}, b={b:.3f}, c={c:.3f}\nLes racines: x1={x1}, x2={x2}")
Source Code
Defining a Function
• A function is a block of reusable code.
• Syntax:
def function_name(parameters):
'''Docstring describing the function'''
statement(s)
return value
• Example:
def greet(name):
return f'Hello, {name}!'
Parameters and Return Values
• Functions can take inputs (parameters) and
return results.
• Example:
def calculate_area(length, width):
return length * width
print(calculate_area(5, 3))
# Output: 15
Default and Keyword Arguments
• Default parameters provide fallback values.
• Example:
def greet_with_title(name, title='Mr./Ms.'):
return f'Hello, {title} {name}!'
• Keyword arguments improve readability:
create_profile(name='Alice', age=30, city='Paris')
Variable Arguments
• *args → for any number of positional arguments
• **kwargs → for keyword arguments
• Example:
def sum_numbers(*args):
return sum(args)
def print_info(**kwargs):
for key, value in [Link]():
print(f'{key}: {value}')
Lambda (Anonymous) Functions
• Lambda functions are small, unnamed functions
for simple tasks.
• Syntax:
lambda arguments: expression
• Examples:
square = lambda x: x ** 2
add = lambda x, y: x + y
print(square(5))
# Output: 25
Relation to Previous Lessons
• Variables and Data Types provide the values that
functions manipulate.
• Control Structures decide when and how functions are
executed.
• Functions organize logic into reusable, modular blocks.
Together, they form the core of structured
programming in Python.
Summary
• In this lesson, we learned:
• How to define and call functions
• Use of parameters, return values, and defaults
• Handling flexible argument lists (*args, **kwargs)
• Using lambda expressions for concise functions
Exercise: Write a Python code source for processing roots of a QE using
function (def, lambda statement) while optimizing the code.
→ Next: Understanding Modules and Packages!