0% found this document useful (0 votes)
6 views13 pages

Python Functions: Basics and Examples

The document provides an introduction to Python functions, including definitions, examples of function usage, and various types of functions such as recursive and lambda functions. It also covers built-in functions, existing modules, and the random module in Python. The content is structured to illustrate how to define and utilize functions effectively in programming.

Uploaded by

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

Python Functions: Basics and Examples

The document provides an introduction to Python functions, including definitions, examples of function usage, and various types of functions such as recursive and lambda functions. It also covers built-in functions, existing modules, and the random module in Python. The content is structured to illustrate how to define and utilize functions effectively in programming.

Uploaded by

sjw83042
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Introduction to Python Function

Byung-In Kim
Department of Industrial & Management Engineering
POSTECH
function
def cal_area(x,y):
return x*y

x=10
y=20
print("x = ",x,",y = ", y, ",area = ", cal_area(x,y))

Logistics Lab. 2
function
def f(x): def spam(eggs):
y=x [Link](0)
x=5 [Link](1)
return y*y eggs = [2,3]
x=3 ham = [0] [0] [0, 1] [2, 3]
print(f(x)) spam(ham)
print(x) print(ham)

9 [1] ham = [0] ham [Link](1) ham eggs


3

• Python 은 객체의 주소가 함수로 넘어간다는 뜻으로 , 객체 호출 (call by object reference) 로 명명되는 방식을 사용한다 .

Logistics Lab. 3
function
def calculate(x,y):
global a,b
total = x+y
print("In funtion")
print("a=",a,"b=",b,"a+b=",a+b)
print(“x=",x,“y=",y,“x+y=",total)
b = 30
return total

a=5 In Program -1
b=7 a= 5 b= 7
total=0 In function
print("In Program -1") a= 5 b= 7 a+b= 12
print("a=",a,"b=",b) x= 50 y= 70 x+y= 120
After calculation
sum=calculate(50,70) total= 0 sum= 120
print("After calculation") a= 5 b= 30
print("total=",total,"sum=",sum)

Logistics Lab. 4
Function arguments
def print_something(my_name, your_name):
print("Hello ", your_name," my name is ", my_name)

print_something("Byung-In Kim", "IST Class")


print_something(your_name = "IST class", my_name = "Byung-In Kim")Keyword arguments

def print_something(my_name, your_name = "IST Class"):Default arguments


print("Hello ", your_name," my name is ", my_name)

print_something("Byung-In Kim", "IST Class")


print_something("Byung-In Kim")

Logistics Lab. 5
Recursive function: Factorial
def fact(n):
if n==1:
return 1
else:
return n*fact(n-1)
num = int(input("Input Number for factorial: "))
print(num,"! = ", fact(num))

def fact(n):
result = 1
for i in range(1, n+1):
result *= i
return result
num = int(input("Input Number for factorial: "))
print(num,"! = ", fact(num))

import math
print(num,"! = ", [Link](num))

Logistics Lab. 6
lambda function
def f(x,y):
return x+yA lambda function is a small anonymous function.
print(f(5,6)) A lambda function can take any number of arguments, but can only have one expres

f = lambda x,y: x+y


print(f(5,6))

g = lambda x: x**2
print(g(10))

Logistics Lab. 7
map() function
ex = [1,2,3,4,5]
f=lambda x: x**2
updated_ex = list(map(f,ex))
print(updated_ex)

Python's map() is a built-in function that allows you to process


and transform all the items in an iterable without using an
explicit for loop, a technique commonly known as mapping. map()
is useful when you need to apply a transformation function to each
item in an iterable and transform them into a new iterable.

Logistics Lab. 8
reduce() function
ex = [1,2,3,4,5]
x = 0
for y in ex:
x+=y
print(x)

from functools import reduce


print(reduce(lambda x,y: x+y, ex))

Python's reduce() is a function that implements a


mathematical technique called folding or reduction. reduce()
is useful when you need to apply a function to an iterable and
reduce it to a single cumulative value.

Logistics Lab. 9
Built-in Functions
function Description
abs(x) Return the absolute value of a number.
all(iterable) Return True if bool(e) is True for each element e.
any(iterable) Return True if bool(e) is True for at least one element e.
chr(integer) Return a one-character string with the given Unicode code point.
divmod(x, y) Return (x // y, x % y) as tuple, if x and y are integers.
hash(obj) Return an integer hash value for the object (see Chapter 10).
id(obj) Return the unique integer serving as an “identity” for the object.
input(prompt) Return a string from standard input; the prompt is optional.
isinstance(obj, cls) Determine if obj is an instance of the class (or a subclass).
iter(iterable) Return a new iterator object for the parameter (see Section 1.8).
len(iterable) Return the number of elements in the given iteration.
map(f, iter1, iter2, ...) Return an iterator yielding the result of function calls f(e1, e2, ...)
for respective elements e1 ∈ iter1,e2 ∈ iter2,...
max(iterable) Return the largest element of the given iteration.

Logistics Lab. 10
Built-in Functions
function Description
max(a, b, c, ...), Return the largest of the arguments.
max(a,b,key=abs)
min(iterable) Return the smallest element of the given iteration.
min(a, b, c, ...) Return the smallest of the arguments.
next(iterator) Return the next element reported by the iterator (see Section 1.8).
ord(char) Return the Unicode code point of the given character.
pow(x, y) Return the value xy (as an integer if x and y are integers); equivalent to x**y.
pow(x, y, z) Return the value (xy mod z) as an integer.
reversed(sequence) Return an iteration of the sequence in reverse.
round(x) Return the nearest int value (a tie is broken toward the even value).
round(x, k) Return the value rounded to the nearest 10−k (return-type matches x). print(round(100.375, 2))  100.38
print(round(100.375, 1))  100.4
sorted(iterable) Return a list containing elements of the iterable in sorted order.
sum(iterable) Return the sum of the elements in the iterable (must be numeric).
type(obj) Return the class to which the instance obj belongs

Logistics Lab. 11
Existing modules (libraries)

Module Name Description


array Provides compact array storage for primitive types.
collections Defines additional data structures and abstract base classes involving col-
lections of objects.
copy Defines general functions for making copies of objects.
heapq Provides heap-based priority queue functions (see Section 9.3.7).
math Defines common mathematical constants and functions.
os Provides support for interactions with the operating system.
random Provides random number generation.
re Provides support for processing regular expressions.
sys Provides additional level of interaction with the Python interpreter.
time Provides support for measuring time, or delaying a program.

Logistics Lab. 12
Random module

Function Description
seed(hashable) Initializes the pseudo-random number generator based upon the hash value of the parame-
ter
random() Returns a pseudo-random floating-point value in the interval [0.0,1.0).
randint(a,b) Returns a pseudo-random integer in the closed interval [a, b].
randrange(start, stop, Returns a pseudo-random integer in the standard Python (exclusive) range indicated by
step) the parameters. [Link](0, 10, 2)  [0, 2, 4, 6, 8]
choice(seq) Returns an element of the given sequence chosen pseudo-randomly.
[Link]([True, False])
[Link](['e', 'd', 'a', 'c', 'b'])
shuffle(seq) Reorders the elements of the given sequence pseudo-randomly.
[Link](['a', 'b', 'c', 'd', 'e'])

Logistics Lab. 13

You might also like