Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
20 views70 pages

Week 7 MAK

This document provides an overview of functions in Python, explaining their definition, types (built-in vs user-defined), and the importance of parameters and return values. It covers key concepts such as scope, default arguments, keyword arguments, and the use of lambda functions and recursion. Additionally, it emphasizes best practices for defining functions, including the use of docstrings for documentation.

Uploaded by

nixak34028
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views70 pages

Week 7 MAK

This document provides an overview of functions in Python, explaining their definition, types (built-in vs user-defined), and the importance of parameters and return values. It covers key concepts such as scope, default arguments, keyword arguments, and the use of lambda functions and recursion. Additionally, it emphasizes best practices for defining functions, including the use of docstrings for documentation.

Uploaded by

nixak34028
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

WEEK 7: Functions

INS 107E Introduction to Programming Languages (Python)

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.

📦 WHY DO WE USE FUNCTIONS?


• Makes the code cleaner and readable
• Avoids repeating the same code
• Allows for easy testing and debugging

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

📦 WHY DO WE USE FUNCTIONS?


o Makes the code cleaner and readable
o Avoids repeating the same code
o Allows for easy testing and debugging
4
🧠 PYTHON FUNCTIONS

🎓 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

❓ What is a Function? 🧠 Imagine This:


A function is: What if you had to rewrite the print()
•✅ A process for executing a task function every time you wanted to
•✅ It can accept input (called parameters) display something?
•✅ It can return output (using return) Instead, Python gives you built-in
•✅ Great for doing similar things repeatedly functions like print() – so we don’t
have to reinvent the wheel every time!

6
🧠 PYTHON FUNCTIONS

💡 Why Do We Use Functions?


🛠 Stay DRY – Don't Repeat Yourself!
✂️ Avoid writing the same code again and again
🧹 Keep your code clean and organized
🧳 "Abstract away" complex code – make it easier for others to use

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?

❗ What’s Wrong Here?


•The function say_hi() prints 'Hello!' but does not return anything.
•So greeting gets assigned None, because there is no return value! 10
🧠 PYTHON FUNCTIONS

❗ What’s Wrong Here?


•The function say_hi() prints 'Hello!'
but does not return anything.
•So greeting gets assigned None,
because there is no return value!

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

🔁 Now the function returns a value → stored in greeting

💡 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.

•7 and 5 are arguments – actual values passed to the function.

14
🧠 PYTHON FUNCTIONS

•first and second are parameters – variable


names defined in the function.
•When you call the function like this:

💡 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

💡 What Do These Teach?


•Loops inside functions
•Returning numeric results
•Using conditions like if
•Writing general-purpose tools (not specific to one value)

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 ?

🔹 Why Use Default Arguments?


❑ They make functions more flexible
❑ Allow you to skip common values
❑ Help keep your code clean and readable

23
🧠 PYTHON FUNCTIONS

This tells us:


•sep=' ' → separates printed values (default is a space)
•end='\n' → adds a newline after each print
•file=sys.stdout → by default, prints to the screen
•flush=False → controls whether to immediately flush the
output buffer

💡 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)

Prints the values to a stream, or to sys.stdout by default.


Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

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'

>>> full_name(last='Akbas', first='Merve')


26
'Your name is Merve Akbas '
🧠 PYTHON FUNCTIONS
📘 KEYWORD & DEFAULT ARGUMENTS
🔧 Let’s Rewrite the power() Function

✅ What Does This Mean?


•If you don’t pass any arguments, it uses x = 2 and n = 3
•You can provide arguments in any order using keyword syntax

27
🧠 PYTHON FUNCTIONS

•Default arguments provide fallback values


•Keyword arguments allow you to skip or reorder inputs
Most flexible = Use both together!

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

🧠 Why this error?


•The variable person is defined inside the function
•It does not exist outside, so it’s not accessible globally

💡 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

🧠 What’s the Issue?


•Even though total is global, Python thinks we
are trying to create a new local variable because
we are assigning (+= 1)
•You cannot change a global variable directly
inside a function without telling Python
explicitly.

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: """...""«

✅ Why Use It?


❑ Helps you and others understand what the function does
❑ Used by tools like help() or IDE tooltips
❑ Essential for complex or reusable functions 38
🧠 PYTHON FUNCTIONS
📘 PACKING & UNPACKING ARGUMENTS
🔹 What’s Happening Here?
Function Definition:

💡 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:

❖ Functional programming style You don’t need to manually write loops —

❖ Easy to use with lambda expressions just pass a function and let Python handle it!

❖ Work well with lists, tuples, etc.

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).

💡 Why Use map()?


•Cleaner than loops
•Works great with short
functions and lambdas
•Returns a map object, so
wrap it in list() to view
results
55
🧠 PYTHON FUNCTIONS
📘 FILTER FUNCTION
🔹 What is filter()?
filter(function, iterable) applies a Boolean-returning
function to each element in an iterable
• Only the elements where the function returns True
pass through.

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

def flip_coin(): def flip_coin():


if random() < 0.5: if randint(0, 1) == 0:
return "Heads" return "Heads"
return "Tails" return "Tails"

from random import choice >>> flip_coin()


"Heads"
def flip_coin(): >>> flip_coin()
return choice(("Heads", "Tails")) "Heads"
>>> flip_coin()
"Tails"
>>> flip_coin()
"Heads"
63
Exercise #3: flip_coins(n)
• Write a function called flip_coins(n).
• The function has one numeric parameter.
• The default value of this parameter is 1.
• It will randomly flip the coin n times and return such output:
• "You flipped the coin 3 times. You got 2 Heads and 1 Tails.".

>>> flip_coins() HINT:


"You flipped the coin 1 times. You got 1 Heads and 0 Tails." In your solution, you may use
>>> flip_coins(5) the previously defined
"You flipped the coin 5 times. You got 2 Heads and 3 Tails."
flip_coin() function.
>>> flip_coins(7)
"You flipped the coin 7 times. You got 5 Heads and 2 Tails."

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.

>>> a_list = [1, 2, 3, 2, 1, 3, 4, 5, 3, 3, 2, 13, 5, 7, 8]


>>> remove_duplicates(a_list)
[1, 2, 3, 4, 5, 13, 7, 8]

>>> remove_duplicates(["a", "b", "A", "a", "b", "C"])


['a', 'b', 'A', 'C']

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

>>> a_list = [1, 2, 3, 2, 1, 3, 4, 5, 3, 3, 2, 13, 5, 7, 8]


>>> remove_duplicates(a_list)
[1, 2, 3, 4, 5, 13, 7, 8]

>>> remove_duplicates(["a", "b", "A", "a", "b", "C"])


['a', 'b', 'A', 'C']

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", "b", "A", "a", "b", "C"])


['a', 'b', 'A', 'C'] HINT:
You can use built-in type()
>>> remove_duplicates2(("a", "b", "A", "a", "b", "C")) function to find out the data
('a', 'b', 'A', 'C') type.

>>> 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", "b", "A", "a", "b", "C"))


('a', 'b', 'A', 'C')

>>> remove_duplicates2("A")
70

You might also like