[go: up one dir, main page]

0% found this document useful (0 votes)
10 views32 pages

Lecture 17 18 PythonFunctions

Uploaded by

Sachin razz
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)
10 views32 pages

Lecture 17 18 PythonFunctions

Uploaded by

Sachin razz
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
You are on page 1/ 32

Principles of Computing

Introduction: Computers and Programming


Languages

By Dr. Joydeep Chandra


Indian Institute of Technology, Patna

25/08/23 1 Indian Institute of Technology Patna


Today…

• Last Session:
• Basic Elements of Python Programs

• Today’s Session:
• Functions- Part I:
• Why using functions?
• Formal definition, parameters, local and global scopes of
variables, return values, and pass-by-value

25/08/23 2 Indian Institute of Technology Patna


Multiple-line Snippets and Functions
• So far, we have been using only one-line
snippets in the interactive mode, but we may
want to go beyond that and execute an entire
sequence of statements

• Python allows putting a sequence of statements


together to create a brand-new command or
function >>> def hello():
These indentations are necessary to ... print("Hello")
indicate that these two statements ... print("Programming is
belong to the same block of code, fun!")
which belongs to this function ...
>>>

25/08/23 3 Indian Institute of Technology Patna


Indentations Are Mandatory

• If indentations are not provided, an error will be


generated
>>> def hello():
... print("Hello")
File "<stdin>", line 2
print("Hello")
^
IndentationError: expected an indented block
>>>

25/08/23 4 Indian Institute of Technology Patna


Invoking Functions

• After defining a function, we can call (or invoke) it


by typing its name followed by parentheses

>>> def hello():


This is how we invoke our
... print("Hello")
defined function hello(); ... print("Programming is fun!")
notice that the two print ...
statements (which form one >>> hello()
code block) were executed Hello
in sequence! Programming is fun!
>>>

25/08/23 5 Indian Institute of Technology Patna


Invoking Functions

• Invoking a function without parentheses will NOT


generate an error, but rather the location
(address) in computer memory where the
function definition has been stored
>>> def hello():
... print("Hello")
... print("Programming is fun!")
...
>>> hello
<function hello at 0x101f1e268>
>>>

25/08/23 6 Indian Institute of Technology Patna


Parameters

• We can also add parameters (or arguments) to


our defined functions
person is a parameter; >>> def hello(person):
it acts as an input to the ... print("Hello " + person)
function hello(…) ... print("Programming is
fun!")
...
>>> hello("Mohammad")
Hello Mohammad
Programming is fun!
>>>

25/08/23 7 Indian Institute of Technology Patna


Multiple Parameters

• We can add multiple parameters and not only


one
>>> def hello(person, course):
... print("Hello " + person + “ from “ +
course)
... print("Programming is fun!")
...
>>> hello("Mohammad“, “15-110”)
Hello Mohammad from 15-110
Programming is fun!
>>>

25/08/23 8 Indian Institute of Technology Patna


Parameters with Default Values

• In addition, parameters can be assigned default


values
def print_func(i, j = def print_func(i, j = def print_func(i, j =
100): 100): 100):
print(i, j) print(i, j) print(i, j)

print_func(10, 20) print_func(10) print_func()

Ru
Ru

Ru
n
n

n
10 10 100 ERROR
20

25/08/23 9 Indian Institute of Technology Patna


Modularity and Maintenance

• Consider the following code


def happy():
print("Happy birthday to you!")
print("Happy birthday to you!")
print("Happy birthday to you!") def singFred():
print("Happy birthday, dear happy()
Fred") happy()
print("Happy birthday to you!") print("Happy birthday, dear
Fred")
Can we write this program with
happy()
ONLY two prints?
singFred()
More modular & maintainable– changing anything in the lyric “Happy birthday
to you!” requires making a change at only one place in happy(); thanks to the
happy function!

25/08/23 10 Indian Institute of Technology Patna


Extensibility and Readability

• Consider the following code


print("Happy birthday to you!")
print("Happy birthday to you!") print("Happy birthday to you!")
print("Happy birthday to you!") print("Happy birthday, dear Fred")
print("Happy birthday, dear print("Happy birthday to you!")
Fred") print("Happy birthday to you!")
print("Happy birthday to you!") print("Happy birthday to you!")
print("Happy birthday, dear Lucy")
What if we want to sing a verse for print("Happy birthday to you!")
Lucy right after Fred?
What if we utilize functions?

25/08/23 11 Indian Institute of Technology Patna


Extensibility and Readability
• Consider the following code

def happy():
print("Happy birthday to you!")
print("Happy birthday to you!")
print("Happy birthday to you!")
print("Happy birthday, dear def sing(name):
happy()
Fred")
happy()
print("Happy birthday to you!") print("Happy birthday, dear " + name)
happy()
What if we want to sing a verse for
Lucy right after Fred? sing("Fred")
sing("Lucy")

Easy to extend, more readable, and necessitates less typing!

25/08/23 12 Indian Institute of Technology Patna


Formal Definition of Functions

• Formally, a function can be defined as follows:


def <name>(<formal-parameters>):
<body>
• The <name> of a function should be an identifier and <formal-
parameters> is a (possibly empty) list of variable names (also identifiers)

• <formal-parameters> and all local variables declared in a function are


only accessible in the <body> of this function

• Variables with identical names declared elsewhere in a program are


distinct from <formal-parameters> and local variables inside a function’s
<body>

25/08/23 13 Indian Institute of Technology Patna


Local Variables

• Consider the following code


def func1(x, y):
#local scope 234
z=4 Traceback (most recent call last):
print(x, y, z) Run File "func1.py", line 6, in <module>
print(x, y, z)
func1(2, 3) NameError: name 'x' is not defined
print(x, y, z)

x, y, and z belong solely to the scope of func1(...) and can only be accessed
inside func1(…); z is said to be local to func1(…), hence, referred to as a local
variable

25/08/23 14 Indian Institute of Technology Patna


Global Variables

• Consider the following code


#global scope
x = 100

def func2(): 100


Run
print(x) 100

func2()
print(x)

x is said to be a global variable since it is defined within the global scope of the
program and can be, subsequently, accessed inside and outside func2()

25/08/23 15 Indian Institute of Technology Patna


Local vs. Global Variables

• Consider the following code


x = 100

def func3():
x = 20 20
Run
print(x) 100

func3()
print(x)

The global variable x is distinct from the local variable x inside func3()

25/08/23 16 Indian Institute of Technology Patna


Parameters vs. Global Variables

• Consider the following code


x = 100

def func4(x):
print(x) 20
Run
100
func4(20)
print(x)

The global variable x is distinct from the parameter x of func4(…)

25/08/23 17 Indian Institute of Technology Patna


The global Keyword

• Consider the following code


def func5():
global x
x = 20
print(x) 20
Run
20
func5()
print(x)

The global keyword binds variable x in the global scope; hence, can be
accessed inside and outside func5()

25/08/23 18 Indian Institute of Technology Patna


Getting Results From Functions

• We can get information from a function by having


it return a value

>>> def square(x): >>> def cube(x): >>> def power(a, b):
... return x * x ... return x * x * x ... return a ** b
... ... ...
>>> square(3) >>> cube(3) >>> power(2, 3)
9 27 8
>>> >>> >>>

25/08/23 19 Indian Institute of Technology Patna


Pass By Value

• Consider the following code

>>> def addInterest(balance, rate):


... newBalance = balance * (1+rate)
... return newBalance
...
>>> def test():
... amount = 1000
... rate = 0.05
... nb = addInterest(amount, rate)
... print(nb)
...
>>> test()
1050.0
>>>

25/08/23 20 Indian Institute of Technology Patna


Pass By Value
• Is there a way for a function to communicate
back its result without returning it?
>>> def addInterest(balance,
rate):
... newBalance = balance *
rate
... balance = newBalance
...
>>> def test():
... amount = 1000
What will be the result? ... rate = 0.05
... addInterest(amount, rate)
... print(amount)
...
>>> test()
1000
>>>
25/08/23 21 Indian Institute of Technology Patna
Pass By Value
• Is there a way for a function to communicate
back its result without returning it?
>>> def addInterest(balance,
rate):
... newBalance = balance *
rate
... balance = newBalance
...
>>> def test():
... amount = 1000
... rate = 0.05
Why 1000 and ... addInterest(amount, rate)
NOT 1050.0? ... print(amount)
...
>>> test()
1000
>>>

25/08/23 22 Indian Institute of Technology Patna


Pass By Value
• The function only receives the values of the
parameters 1000

>>> def addInterest(balance,


rate):
addInterest(…) ... newBalance = balance *
gets ONLY the rate
value of amount ... balance = newBalance
... Python is said
(i.e., 1000)
>>> def test(): to pass
... amount = 1000 parameters by
... rate = 0.05 value!
... addInterest(amount, rate)
... print(amount)
...
>>> test()
1000
>>>
25/08/23 23 Indian Institute of Technology Patna
Pass By Value vs. Returning a Value

• Consider the following code

def increment_func(x): def increment_func(x):


x=x+1 x=x+1
return x
x=1
increment_func(x) x=1
print(x) x = increment_func(x)
print(x)
Ru

Ru
n

n
1 2

25/08/23 24 Indian Institute of Technology Patna


More on the Print Function

• There are different forms of the print function


1) print(), which produces a blank line of output

>>> print()

>>>

25/08/23 25 Indian Institute of Technology Patna


More on the Print Function

• There are different forms of the print function


2) print(<expr>, <expr>, …, <expr>), which indicates that
the print function can take a sequence of expressions,
separated by commas

>>> print(3+4)
7
>>> print(3, 4, 3+4)
347
>>> print("The answer is ", 3 + 4)
The answer is 7
>>> print("The answer is", 3 + 4)
The answer is 7

25/08/23 26 Indian Institute of Technology Patna


More on the Print Function
• There are different forms of the print function
3) print(<expr>, <expr>, …, <expr>, end = “\n”), which
indicates that the print function can be modified to
have an ending text other than the default one (i.e., \
n or a new line) after all the supplied expressions are
printed
>>> def answer():
Notice how we used the end ... print("The answer is:", end = " ")
parameter to allow multiple ... print(3 + 4)
prints to build up a single line ...
>>> answer()
of output!
The answer is: 7
>>>

25/08/23 27 Indian Institute of Technology Patna


write a python program to take input of your name and print that using function

# Function to get and print a name


def print_name():
name = input("Enter your name: ")
print("Your name is:", name)

# Call the function to get and print the name


print_name()

25/08/23 28 Indian Institute of Technology Patna


write a python program to take input of a number and print the suqare
of that number using function

# Function to calculate and print the square of a number


def calculate_square(number):
square = number ** 2
print("The square of", number, "is:", square)

# Input
num = float(input("Enter a number: "))

# Call the function to calculate and print the square


calculate_square(num)

25/08/23 29 Indian Institute of Technology Patna


Write down a python program using function to take
input of two numbers in two different integers, swap
them and print.
# Function to swap two integers
def swap_numbers(a, b):
temp = a
a=b
b = temp
return a, b
# Input
num1 = int(input("Enter the first integer: "))
num2 = int(input("Enter the second integer: "))
# Swapping values using the function
num1, num2 = swap_numbers(num1, num2)
# Printing the swapped values
print("After swapping:")
print("First integer:", num1)
print("Second integer:", num2)

25/08/23 30 Indian Institute of Technology Patna


Write down a python program to take input of two numbers,
print the addition, subtraction , multiplication and division
results using functions.
# Function to perform addition
def add(num1, num2):
return num1 + num2
# Function to perform subtraction
def subtract(num1, num2):
return num1 - num2
# Function to perform multiplication
def multiply(num1, num2):
return num1 * num2
# Input
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Calculate and print results
print("Addition result:", add(num1, num2))
print("Subtraction result:", subtract(num1, num2))
print("Multiplication result:", multiply(num1, num2)) Indian Institute of Technology Patna
25/08/23 31
Next Class…

• Functions- Part II

25/08/23 32 Indian Institute of Technology Patna

You might also like