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

Function Definition Syntax

The document discusses various aspects of functions in Python including: - Function definition syntax and calling syntax - Functions that return values vs functions that don't - Passing arguments to functions including immutable vs mutable objects - Default argument values, variable length arguments, and nested functions - Raising and handling exceptions within functions

Uploaded by

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

Function Definition Syntax

The document discusses various aspects of functions in Python including: - Function definition syntax and calling syntax - Functions that return values vs functions that don't - Passing arguments to functions including immutable vs mutable objects - Default argument values, variable length arguments, and nested functions - Raising and handling exceptions within functions

Uploaded by

mohammed ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Function definition syntax:

def function_name(argument1, argument2, ... , argumentN) :


    statement_1
    statement_2
    ....
Statement_m
Syntax of function call:
function_name(expression1, expression2, ... , expressionN)

The general form of a Paython program:

def function_name(argument1, argument2, ...) :


    statement_1
    statement_2
    ....
    return expression

def main():
. . .
val = function_name(arg1, arg2)
. . .

main()

Note: A function that has no return statement or one that has a return that is not followed by an expression,
returns a special value: None
The return statement exits a function.
Examples:
import math
def area_circle(radius):
area = math.pi * radius**2
return area
r = 2
a = area_circle(r)
print("Area of a circle with radius: %.1f cm is %.1f square cm" %(r, a))
-----------------------------------------------------------------------------------------
import math
def volume(radius, height):
return math.pi * radius ** 2 * height

def main():
print("volume of cylinder with radius", 1, " cm and height 2 cm is", volume(1,2), "cubic cm")
print("volume of cylinder with radius", 2, " cm and height 1 cm is", volume(2,1), "cubic cm")

main()

Page 1 of 6
Functions returning no values
Example:
def print_message():
print("This is Python 3.2 Tutorial")

print_message()

Functions returning multiple values


In Python, you can return multiple values by simply returning them separated by commas.In Python, comma-
separated values are considered tuples without parentheses.
Example: A function that returns the area and perimeter of a rectangle:
def getAreaAndPerimeter(length, width):
area = length * width
perimeter = 2 * (length + width)
return area, perimeter

def main():
len = float(input("Enter length [cm]: "))
wdth = float(input("Enter width [cm]: "))
area, perim = getAreaAndPerimeter(len, wdth)
print("area = %0.2f square cm." % area)
print("perimeter = %0.2f cm." % perim)

main()

Functions that call functions


import math
def area_circle(radius):
return math.pi * radius ** 2

def area_cylinder(radius,height):
circle_area = area_circle(radius)
height_area = 2 * radius * math.pi * height
return 2*circle_area + height_area

print( 'The area of a circle of radius 1 cm is', area_circle(1) )


r = 2
height = 10
print('The surface area of a cylinder with radius', r, 'cm')
print('and height', height, 'cm is', area_cylinder(r,height), 'cubic cm')

Page 2 of 6
Passing immutable objects to functions
A Python function cannot modify the value(s) of an immutable object passed to it.
def myFunction(x, string1):
x = 12 # a new local object is created
string1 = "Riyadh" # a new local object is created

x = 7
string1 = "Dhahran"
myFunction(7, string1)
print(x)
print(string1)

Output:
7
Dhahran

Passing mutable objects to functions


A Python function can modify the value(s) of a mutable object passed to it.
def myFunction2(list, dictionary):
list[2] = 65
dictionary["Muhsin"] = 90.0

list1 = [7, 12, 3, 4, 8]


dictionary1 = {"Ahmad" : 87.0, "Muhsin" : 50.5, "Ayman" : 66.5}
myFunction2(list1, dictionary1)
print(list1)
print(dictionary1)

Output:
[7, 12, 65, 4, 8]
{'Ahmad': 87.0, 'Muhsin': 90.0, 'Ayman': 66.5}
However, note the following:
def changeMe(mylist):
mylist = [1,2,3,4] # This creates a new mylist object
print(id(mylist))
return

mylist = [10,20,30]
changeMe( mylist )
print(id(mylist))
print(mylist)

Possible output:
2572178432384
2572178423552
[10, 20, 30]
Page 3 of 6
Default Argument Values [Optional]

In function's parameters list we can specify default value(s) for one or more arguments. A default value can be
written in the format "argument1 = value", therefore we will have the option to declare or not declare a value
for those arguments. See the following example.

Example:
The following function returns the square of the sum of two numbers, where default value of the second
argument is 2.

def nsquare(x, y = 2):


return (x*x + 2*x*y + y*y)

print("The square of the sum of 2 and 2 is : ", nsquare(2))


print("The square of the sum of 2 and 3 is : ", nsquare(2,3))

Variable-length arguments [Optional]

 The special syntax *args in function definitions in python is used to pass a variable number of
arguments to a function.
 Within the function, the vararg arguments are treated as a single tuple.
 A function can have a mixture of vararg and non-vararg parameters; but there can be only one vararg
parameter in a function.

Syntax for a header of function with vararg arguments is:


def functionName(arg1, arg2, . . ., argN, *var_args_parameter ):

where the non-vararg parameters arg1, arg2, . . .argN may be missing.

Example:

def mySum(*numbers):
s = 0
for n in numbers:
s += n
return s

print(mySum(1,2,3,4))
print(mySum(20,30))
print(mySum())

Output:
10
50
0

Functions that raise exceptions [Optional]


It is not good programming practice for a user-defined function to handle an exception. The handling of an
exception should be left to the caller of the function. A user-defined function should be designed to raise (or
throw an exception) if there is one.

Page 4 of 6
Example1:

def add2(x, y):


try:
return x + y
except:
raise TypeError("Error: cannot add non-numeric value(s)")

num1 = 5
num2 = "8"

try:
result = add2(num1, num2)
print("sum = ", result)
except TypeError as e:
print(e)
-------------------------------------------------------------------------------------------------------------------
Example2:
import math
def area_circle(radius):
if radius < 0:
raise Exception("Error: Negative radius.")
else:
area = math.pi * radius**2
return area

try:
r = float(input("Enter radius > 0 : "))
a = area_circle(r)
print("Area of a circle with radius: %.1f cm is %.1f square cm" %(r, a))
except Exception as e:
print(e.__class__.__name__, e)
----------------------------------------------------------------------------------------------------------------------------------------------------------------
Nested functions [Optional]
A python function can be nested inside another python function.

Example:

def factorial(number):
# Validate input
if not isinstance(number, int):
raise TypeError("Sorry. 'number' must be an integer.")
if number < 0:
raise ValueError("Sorry. 'number' must be zero or positive.")
# Calculate the factorial of number
def inner_factorial(number):
if number == 0 or number == 1:
return 1
Page 5 of 6
else:
num = 1
for k in range(1, number):
num *= num * k

return num

return inner_factorial(number)

try:
intnum = int(input("Enter an integer >= 0: "))
print("The factorial of %d is %d.", % (intnum, factorial(intnum))
except (TypeError, ValueError) as e:
print(e)

Page 6 of 6

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy