0% found this document useful (0 votes)
2 views

[CreativeProgramming]Lecture4_Functions in Python

The document outlines the importance of functions in Python programming, emphasizing their roles in modularization, reusability, and development efficiency. It explains how to define functions, the difference between parameters and arguments, and the scope of variables. Additionally, it includes exercises for practical application, such as creating functions for arithmetic operations, temperature conversion, and assessing body mass index.

Uploaded by

allrounderguno
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

[CreativeProgramming]Lecture4_Functions in Python

The document outlines the importance of functions in Python programming, emphasizing their roles in modularization, reusability, and development efficiency. It explains how to define functions, the difference between parameters and arguments, and the scope of variables. Additionally, it includes exercises for practical application, such as creating functions for arithmetic operations, temperature conversion, and assessing body mass index.

Uploaded by

allrounderguno
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Creative Programming

Spring 2025
CUL1122 Lecture #04
Functions in Python
Today

❖Functions
▪ Importance of Functions
▪ Parameters and Return Values
▪ Function Calls and Return Values
▪ Scope of Variables

3
Basic Idea of Functions

❖A function is a code block to perform specific tasks within a program.


▪ It is similar to a machine that receives input data, processes it, and produces a
result.
▪ For example, when you put laundry and detergent into a washing machine, you
receive clean laundry after it runs.
▪ Similarly, when 1) input data is provided to a function
and a task is requested, 2) the function performs
calculations and 3) returns the result.
2 0 10
x x x
x2 x2 x2

4 0 100 4
Mathematical Functions vs. Functions in Computer Programs

❖In mathematics, functions are either used from existing ones or defined
anew.
▪ Using existing functions: sine, cosine, etc.
▪ Defining new functions: f(x) = x2 + 2x + 1
❖Functions in computer programs
▪ Functions are written using programming languages.
▪ They encapsulate ideas for computation to solve problems and are assigned a
name.

5
Importance of Functions

❖1) Modularization: Allows for devising solutions at a higher level


without worrying about the underlying details.
▪ Would anyone want to think about calculating square roots within the complex
computation below?
r = (sqrt(250+110*sqrt(5))/20)*E

❖2) Reusability: Enables problem-solving without the need to write new


code each time, allowing for the reuse of existing functions.
❖3) Development Efficiency: Makes programs more concise and easier to
understand, facilitating error detection and modification.

6
Reusability of Functions

When Not Using Functions When Using Functions

7
Defining a Python Function

❖The function declaration consists of the function name on the first line,
followed by the function body.

def name(parameters): # Function name is the identifier used to call the function
# Parameters are a list of inputs passed to the function
code # Function body must be indented
code Function # Function body is executed each time the function is called
… Body
return value # ‘return’ ends the function call and sends result back to the caller
# You can omit the ‘return’ if you want to return nothing

: Indentation

8
Arguments and Return Values

❖Arguments: The buyer specifies the tier and cake type.


❖Return Values: The baker makes and delivers the requested cake.

bake_cake( tiers
1-tier , flavor
‘Cheese’ )

9
Arguments and Return Values

❖If you want a 4-tier chocolate cake?

bake_cake( tiers
4-tier , flavor
‘Choco’ )

10
Function Call and Result Passing

Calling a function
3- with arguments
bake_cake( tiers
3-tier flavor )
, ti ‘Cheese’)
er 3-tier ‘Cheese’
bake_cake

‘Cheese’

11
Function Call and Result Passing

Calling a function
3- with arguments
bake_cake( tiers
3-tier flavor )
, ti ‘Cheese’)
er 3-tier ‘Cheese’
bake_cake
Passing return
values
3

“Cheese”

12
Parameters vs. Arguments

❖Parameters represent input data defined within a function.


❖Arguments are the actual values passed during function invocation and
are assigned to the parameters.
❖In the given function, the arguments (1, 5) correspond to the
parameters (x, y) in order.
1, 5 Arguments def sqrt(x, y):
x, y result = x2 + y2
return result
sqrt(x, y) = x2 + y2 x, y: Parameters square_sum = sqrt(1, 5)

26 Return value
13
Function Execution Order

❖1) Call the function with arguments.


Python Script
❖2) Assign the arguments to the parameters. Function
sqrt(x, y)
❖3) Execute the function and generate return values.
❖4) If there is a return value, end the function with a
result = x2 + y2
return statement.
def sqrt(x, y): ②
❖5) If there is no return value, result = x2 + y2 ③
continue execution until the return result ④, ⑤
end and terminate the function.
square_sum = sqrt(1, 5) ①

14
Scope of Variables: Types
❖1) Local Variables
▪ Valid only within the function.
▪ Created upon function call and disappear when the function ends.
❖2) Global Variables
▪ Valid throughout the script (or program).
▪ Created at the start of the program and cease to exist when the program ends.
❖Example:
▪ Global Variable: A person known throughout the country, such as Elon Musk.
▪ A person who is well-known in a specific local area, such as Mayor Oh Se-hoon.
➢He is famous in Korea but may not be recognized outside of the country.

15
Scope of Variables: Access Error

❖The local variable is only valid within the function; therefore,


attempting to access it from outside the function will result in an error.

16
Scope of Variables: Priority

❖When global and local variables share the same name, each operates
within its own scope hierarchy.

17
Scope of Variables: Accessing Global Variables

❖Global variables can be accessed and modified within functions by


using the global keyword.

18
Lab 4
Today

❖1) Using a Calculator


❖2) Converting Temperature
❖3) Calculating Factorials
❖4) Understanding Variable Scope in Python
❖5) Calculating the Total Price
❖6) Assessing Body Mass Index (BMI)
❖7) Playing FizzBuzz

20
Exercise #1: Using a Calculator

❖Create a script that defines a function to perform arithmetic operations


(+, -, *, /, //, %) on two integers, calls the function, and displays the
result.
▪ The % operator calculates the remainder of division, and the // operator finds
the integer quotient.

21
Exercise #2: Converting Temperature

❖Create a script that defines a function for temperature conversion, calls


the function, and displays the converted temperature.
▪ The function should take a temperature type (C or F) and a temperature value
as input, perform the conversion, and return the converted temperature.
▪ The formulas are as follows:
➢F = 1.8 * C + 32
➢C = (F - 32) / 1.8

22
Exercise #3: Calculating Factorials

❖Create a script that defines a function to calculate the factorial of a


number (N) according to the following rule, then call the function and
display the output:
▪ 1) N = 1: 1! = 1
▪ 2) N > 1: N! = N * (N-1)!

23
Exercise #4: Understanding Variable Scope in Python

❖Create a script that defines both a global variable and a local variable
within a function to explore how variable scope works in Python.
▪ Use the same name, celebrity, for both the global and local variables, assigning
famous names to each.
▪ Test the scope by attempting to access the celebrity variable both inside and
outside the function.

24
Exercise #5: Calculating the Total Price

❖Create a script that defines a function to calculate the drink price based
on the order, calls the function, and displays the result.
▪ Declare the total price as a global variable accessible throughout the script.

25
Exercise #6: Assessing Body Mass Index (BMI)

❖Create a script to assess body condition using functions.


▪ Define two functions: one for calculating BMI and another for assessing body
condition based on the criteria provided below:

26
Exercise #7: Playing FizzBuzz

❖Create a script that defines a function to play FizzBuzz for a given


number, calls the function, and displays the result.
▪ The function should handle the logic according to the following rules and
return the FizzBuzz result:
… 9 10 11 12 13 14 15 16 …
Fizz Buzz 11 Fizz 13 14 FizzBuzz 16

27
수고하셨습니다!

28

You might also like