Function Definition Syntax
Function Definition Syntax
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()
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()
def area_cylinder(radius,height):
circle_area = area_circle(radius)
height_area = 2 * radius * math.pi * height
return 2*circle_area + height_area
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
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.
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.
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
Page 4 of 6
Example1:
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