Week 7 MAK
Week 7 MAK
16.04.2025
Dr. Merve AKBAŞ KAPLAN 1
🧠 PYTHON FUNCTIONS
What is a Function in Python?
A function is a block of organized, reusable code that is used to perform a single, specific
task. Functions help make your code more modular and easier to manage.
2
🧠 PYTHON FUNCTIONS
TYPES OF FUNCTIONS
🔧 Built-in vs User-Defined Functions
1. Built-in Functions
These are already available in Python:
2. User-Defined Functions
You can create your own:
3
🧠 PYTHON FUNCTIONS
🔁 Parameters and Return
Parameters let you pass data into the function
Return sends the result back to where the
function was called
🎓 Mini Quiz
1.What keyword is used to define a function? → def
2.What does return do? → Sends a value back from the function
3.How to call a function? → Use function_name()
5
🧠 PYTHON FUNCTIONS
6
🧠 PYTHON FUNCTIONS
7
🧠 PYTHON FUNCTIONS
📘 DEFINING A FUNCTION
🔹 How to Define a Function in Python?
To define a function in Python, follow these steps:
✅ 1. Start with the keyword defThis tells Python you’re defining a function.
✅ 2. Followed by a function name and parentheses ( )Put any input parameters inside the
parentheses.
✅ 3. End the function header with a colon :
✅ 4. The function body must be indented.At least one valid Python statement must be inside.
✅ 5. Use return to send back a result (optional)If you write return without a value, it returns
8
None by default.
🧠 PYTHON FUNCTIONS
💡 Notes:
•Function names should be meaningful and
lowercase (with underscores if needed)
•Indentation is very important in Python
•If you don't use return, the function will
return None by default
9
🧠 PYTHON FUNCTIONS
📘 STRUCTURE OF A FUNCTION
Function Syntax – How is it Structured?
11
🧠 PYTHON FUNCTIONS
📘 RETURN vs PRINT: WHAT’S WRONG?
🔍 We assign the result of the function to the variable greeting.
We see output ("Hello!") because of the print() inside the
function.
But... greeting is None because the function doesn’t return
anything. 🚫 These are called void functions
Functions that don’t return a value are known as "void
functions" – they do something (like print), but don’t return
data.
✅ Fix it with return. 12
🧠 PYTHON FUNCTIONS
💡 Summary:
•print() shows something on screen
•return sends data back to where the
function was called
•A function without return will return
None by default
13
🧠 PYTHON FUNCTIONS
📘 FUNCTION PARAMETERS & ARGUMENTS ✅ Definitions:
🔹 What Are Parameters and Arguments? •Parameters: placeholders inside the
function definition.
•Arguments: actual data you send
into the function when calling it.
14
🧠 PYTHON FUNCTIONS
💡 Key Tip:
•Think of parameters as "empty containers"
•Arguments are the values you fill into them
15
🧠 PYTHON FUNCTIONS
📘 FUNCTION PARAMETERS & ARGUMENTS
🔹 Parameter vs Argument
A parameter is the variable listed in a function’s definition.
An argument is the actual value passed to the function when it is called.
🧠 Tip:
You define parameters, but you provide arguments. 16
🧠 PYTHON FUNCTIONS
🧠 Tip:
You define parameters, but you provide arguments. 17
🧠 PYTHON FUNCTIONS
📘 SOME EXAMPLES
Let’s look at three custom functions to better understand how functions
work in Python.
18
🧠 PYTHON FUNCTIONS
19
🧠 PYTHON FUNCTIONS
📘 COMMON RETURN MISTAKES
❗ Mistake 1: Returning too early in a loop
return is inside the loop, so the function Now, return is outside the loop – it returns the
20
returns after only one iteration. correct total after the loop finishes.
🧠 PYTHON FUNCTIONS
21
🧠 PYTHON FUNCTIONS
📘 DEFAULT ARGUMENTS FOR PARAMETERS
🔹 What Are Default Arguments?
Sometimes you want your function to work even if the user
doesn't pass all the arguments. That’s where default values help.
💡 Key Tip:
•Default values are used only when no
argument is provided for that parameter.
•You can override them by passing your
own values. 22
🧠 PYTHON FUNCTIONS
📘 WHY DO WE HAVE DEFAULT ARGUMENTS ?
23
🧠 PYTHON FUNCTIONS
💡 Key Takeaway:
Default arguments = fewer things to worry about when calling the function. 24
🧠 PYTHON FUNCTIONS
>>> help(print)
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
25
🧠 PYTHON FUNCTIONS
🔹 What Are Keyword Arguments?
When calling a function, you can name the arguments explicitly using the parameter
name. These are called keyword arguments.
✅ Why Use Them?
o You don’t have to remember the order of arguments.
o You can skip optional ones if they have defaults
o More readable function calls def full_name(first, last):
return "Your name is " + first + " " + last
>>> full_name(first='Merve', last='Akbas')
'Your name is Merve Akbas'
27
🧠 PYTHON FUNCTIONS
28
🧠 PYTHON FUNCTIONS
📘 SCOPE OF VARIABLES
🔹 What is Scope?
▪ A scope is the area of code where a variable can be accessed.
▪ Python has:
Local Scope → inside a function
Global Scope → outside all functions
💡 Summary:
•Variables inside a function = local
•Variables outside = global
•To modify a global variable inside a function, use the global keyword
29
🧠 PYTHON FUNCTIONS
30
🧠 PYTHON FUNCTIONS
31
🧠 PYTHON FUNCTIONS
📘 LOCAL VS GLOBAL VARIABLES
💡 Key Takeaways:
•Variables created inside a function are local
•They are not connected to global variables with the same name
•The function uses its own copy of the variable
•Even if a global variable exists, the local one takes precedence
inside the function
32
🧠 PYTHON FUNCTIONS
💡 Key Takeaways:
•Variables created inside a function are local
•They are not connected to global variables with the same name
•The function uses its own copy of the variable
•Even if a global variable exists, the local one takes precedence inside the function 33
🧠 PYTHON FUNCTIONS
📘 ACCESSING GLOBAL VARIABLES
💡 Key Takeaways:
•Functions can access global variables
🧠 Why does this happen?
•But those variables must already exist
•The function tries to return a variable called total
•If the variable isn't defined yet, you get a NameError
•But there is no global variable named total yet
•Python cannot find it, so it raises a NameError 34
🧠 PYTHON FUNCTIONS
📘 ACCESSING VS MODIFYING GLOBAL VARIABLES
35
🧠 PYTHON FUNCTIONS
📘 ACCESSING VS MODIFYING GLOBAL VARIABLES
❗ Summary:
•✅ You can read global variables in a function
•❌ But you cannot modify them without using global
💡 Key Takeaway:
To modify a global variable inside a function, use the global keyword.
Otherwise, Python assumes it’s local and gives an error. 36
🧠 PYTHON FUNCTIONS
📘 MODIFYING GLOBAL VARIABLES WITH global
✅ Using global to Access & Modify
🔍 Explanation:
•By using the global keyword, we tell Python:
“Hey! Don’t treat total as a new local variable. Use
the global one.”
•Now the function can:
•Access the global variable
•Modify its value
💡 Summary:
•Without global, assignment to a global variable causes an error
•With global, the function can change the variable permanently 37
🧠 PYTHON FUNCTIONS
📘 DOCUMENTING FUNCTIONS
What Is a Docstring?
A docstring is a special kind of string placed at the very
beginning of a function to describe what the function does.
You use triple quotes: """...""«
💡 Key Concept:
•Packing: using *args to collect
multiple arguments
•Unpacking: using * to break a
list/tuple into individual arguments 39
🧠 PYTHON FUNCTIONS
40
🧠 PYTHON FUNCTIONS
📘 UNPACKING POSITIONAL ARGUMENTS
🧠 Why Did It Work?
•The *names syntax unpacks the list
•It assigns:
•a = 'Tolga'
•b = 'Ahmet'
•c = 'Feyza'
•d = 'Dilek'
💡 Tip:
Use * to unpack lists or tuples into positional arguments
The number of elements must match the number of parameters
41
🧠 PYTHON FUNCTIONS
📘 PACKING POSITIONAL ARGUMENTS WITH *args
🔹 What Is Packing?
Packing means collecting multiple arguments into a single variable — usually a tuple — using the * operator.
🧠 How It Works:
•args becomes a tuple:
•args = (10, 20)
•args = (10, 20, 30, 40, 50)
You can now loop over it and do whatever you want!
42
🧠 PYTHON FUNCTIONS
💡 Key Point:
Use *args when you want your function
to accept any number of positional
arguments.
43
🧠 PYTHON FUNCTIONS
🔹 Double Star Operator: **
📘 A Note on Packing & Unpacking
•Used to pack or unpack keyword
🔹 Star Operator: * arguments
•Works with dictionaries
•Used to pack or unpack positional arguments
•Commonly used as **kwargs, but you can
•Works with tuples or lists name it anything
•Commonly used as *args, but name is flexible
44
🧠 PYTHON FUNCTIONS
📘 A Note on Packing & Unpacking
45
🧠 PYTHON FUNCTIONS
📘 GENERAL EXAMPLE FOR PACKING (*args & **kwargs)
🧠 What Happened?
•1, 2, 3 → packed into args → a tuple
•first_name='Tolga', last_name='Ozudogru'
→ packed into kwargs → a dictionary
46
🧠 PYTHON FUNCTIONS
📘 GENERAL EXAMPLE FOR UNPACKING
💡 Key Point:
•Use * to unpack positional arguments from a list or tuple
•Use ** to unpack keyword arguments from a dictionary
•Together, they allow you to combine different data types in
one function call.
🧠 How Does It Work?
•*my_list unpacks the list:
→ a = 10, b = 20
•**my_dict unpacks the dictionary:
→ c = 30, d = 40 47
🧠 PYTHON FUNCTIONS
📘 RECURSIVE FUNCTIONS
🔁 What Is Recursion?
A recursive function is a function that calls itself to solve a smaller
version of the original problem.
💡 Key Points:
•Recursion must have a base case to stop
•Useful for problems that can be broken down into smaller,
similar sub-problems
•Too many recursive calls may cause a stack overflow 48
🧠 PYTHON FUNCTIONS
49
🧠 PYTHON FUNCTIONS
📘 LAMBDA FUNCTIONS
🔹 What Is a Lambda Function?
❑ A lambda function is also called an anonymous function
❑ It is a quick way to define small, one-line functions
❑ No need for the def keyword or a name
50
🧠 PYTHON FUNCTIONS
📘 HIGHER ORDER FUNCTIONS
🔹 What Is a Higher Order Function?
A Higher Order Function is a function that:
Takes another function as an argument
OR
Returns a function as its result
51
🧠 PYTHON FUNCTIONS
💡 Summary:
•You can pass functions as arguments
•Functions are first-class objects in Python
•Great for creating flexible and reusable code
52
🧠 PYTHON FUNCTIONS
📘 MAP, FILTER, REDUCE
🔹 Functional Programming Helpers
These three higher-order functions simplify iteration by applying a function across a
sequence:
✅ map(function, iterable)Applies a function to each item of an iterable.
✅ filter(function, iterable)Keeps only the items where the function returns True.
✅ reduce(function, iterable)Applies a rolling computation — combines the elements one by
one.
Note: map() and filter() are built-in.reduce() needs to be imported from functools.
53
🧠 PYTHON FUNCTIONS
💡 Why Use Them?
❖ Clean, loop-free code 🧠 Key Benefit:
❖ Easy to use with lambda expressions just pass a function and let Python handle it!
54
🧠 PYTHON FUNCTIONS
📘 MAP FUNCTION
🔹 What is map()?
map(function, iterable) applies a function to each -element in the given iterable (e.g. list, tuple).
56
🧠 PYTHON FUNCTIONS
📘 FILTER FUNCTION EXAMPLE: PALINDROME DETECTOR
🔹 What is a Palindrome?
A palindrome is a word or phrase that reads the same forward and backward, e.g. "madam", "level", "racecar".
💡 Takeaway:
filter() + lambda is
perfect for custom
filtering with clear logic
and minimal code.
🔍 What’s Happening?
•word[::-1] reverses the word
•word == word[::-1] checks if it’s a palindrome
•filter() applies this condition to each word 57
🧠 PYTHON FUNCTIONS
📘 REDUCE FUNCTION
🔹 What Is reduce()?
reduce(function, sequence) applies a function of two arguments cumulatively to the elements of a
sequence from left to right, reducing it to a single result.
58
🧠 PYTHON FUNCTIONS
EXERCISES
59
Exercise #1: number_compare(a, b)
• Write a function called number_compare(a, b).
• This function takes in two parameters (both numbers).
• If the first number is greater than the second, the function returns:
• "First number is greater."
• If the second number is greater than the first, the function returns:
• "Second number is greater."
• Otherwise, the function returns:
• "Both numbers are equal." >>> number_compare(10, 5)
"First number is greater."
>>> number_compare(5, 10)
"Second number is greater."
>>> number_compare(10, 10)
"Both numbers are equal." 60
Exercise #1: number_compare(a, b)
• Solution:
def number_compare(a, b):
if a > b:
return "First number is greater."
elif b > a:
return "Second number is greater."
return "Both numbers are equal."
>>> number_compare(10, 5)
"First number is greater."
>>> number_compare(5, 10)
"Second number is greater."
>>> number_compare(10, 10)
"Both numbers are equal."
61
Exercise #2: flip_coin()
• Write a function called flip_coin().
• The function has no parameters/arguments.
• It will randomly return "Heads" or "Tails".
>>> flip_coin()
"Heads"
>>> flip_coin()
"Heads"
>>> flip_coin()
"Tails"
>>> flip_coin()
"Heads"
62
Exercise #2: flip_coin()
• Solution (3 alternatives):
from random import random from random import randint
64
Exercise #3: flip_coins(n)
• Solution:
def flip_coins(n=1):
results = []
for i in range(n):
results.append(flip_coin())
heads = results.count("Heads")
tails = n - heads
text = "You flipped the coin " + str(n) + " times. "
text += "You got " + str(heads) + " Heads and " + str(tails) + " Tails."
return text
>>> flip_coin()
"You flipped the coin 1 times. You got 1 Heads and 0 Tails."
>>> flip_coin(7)
"You flipped the coin 7 times. You got 5 Heads and 2 Tails."
65
Exercise #3: flip_coins(n)
• Alternative solution, using list comprehension:
def flip_coins(n=1):
results = [flip_coin() for _ in range(n)]
heads = results.count("Heads")
tails = n - heads
text = "You flipped the coin " + str(n) + " times. "
text += "You got " + str(heads) + " Heads and " + str(tails) + " Tails."
return text
>>> flip_coin()
"You flipped the coin 1 times. You got 1 Heads and 0 Tails."
>>> flip_coin(7)
"You flipped the coin 7 times. You got 5 Heads and 2 Tails."
66
Exercise #4: remove_duplicates(L)
• Write a function called remove_duplicates(L).
• The function has one parameter, which is a list.
• It will return a new list with unique items, i.e. no duplicates.
67
Exercise #4: remove_duplicates(L)
• Solution:
def remove_duplicates(L):
my_list = []
for i in L:
if i not in my_list:
my_list.append(i)
return my_list
68
Exercise #5: remove_duplicates2(data)
• Improve your remove_duplicates(L) function so that:
• It can accept a tuple or a list.
• It will return the same data type as the passed argument, i.e., a tuple for a tuple or a
list for a list.
• It will return None if the passed argument is not a tuple or a list.
• Give your function a new name: remove_duplicates2(data)
>>> remove_duplicates2("A")
69
Exercise #5: remove_duplicates2(data)
• Solution:
def remove_duplicates(data):
data_type = type(data)
if data_type in (tuple, list):
my_list = []
for i in data:
if i not in my_list:
my_list.append(i)
return data_type(my_list)
return None # This line is not necessary
>>> remove_duplicates2(["a", "b", "A", "a", "b", "C"])
['a', 'b', 'A', 'C']
>>> remove_duplicates2("A")
70