Programming in Python
(Functions in Python)
Dr. Faisal Anwer
Department of Computer Science
Aligarh Muslim University 1
Copyright © Dept of Computer Science, AMU, Aligarh. Permission required for reproduction or display.
Recap
• Decision Making
• For Loop
• While Loop
• Nested Loops
Contents
• Exercise on loop and decision making
• Introduction to Function
• Syntax of Function
Functions
A function is a organized block of code designed to carry out
a distinct, related task.
Alternatively, a function can be described as a collection of
instructions that accepts input, executes a particular task, and
then produces some output.
Advantages of Functions
• Acts as building blocks for the program.
• Reuse of code, i.e., help enhance software reusability.
• Improves clarity of the code.
• Function supports the divide and conquer strategy
• Decomposing complex problems into simpler pieces
Main
Searching Sorting Traversing
5
Linear Binary
Function
Built-in functions: The standard functions that are provided by
python.
User-defined functions: The programmer can define its own
functions.
def prime(n):
for x in range(2, n):
if n % x == 0:
break
else:
# loop fell through without finding a factor
print(n, 'is a prime number')
Syntax of Function
def functionName(paramList):
function_suite (Code)
return [Expression/Value/Variable]
• Function name (functionName) is a valid identifier.
• Valid Function names: IntegerSum, _FloatSum23, printSum
• Invalid Function names: 23IntegerSum, $FloatSum23,
print&$Sum
• The parameter list (paramList) is a comma-separated list of
parameters received by the function.
• The statement return [expression] exits a function.
• A return statement with no arguments is the same as return None.
Syntax of Function
• Define before call
• Must be defined before it is called
• Calling a function
• Specify the function name and its arguments
• Arguments (optional)
• The arguments are the data you pass into the method’s
parameters.
• Parameters (optional)
• A parameter is a variable in a method definition.
• The return information (optional)
• Information that the function returns to the source that
invoked it.
Creating Functions with Return Values
# function definition
def square( y ):
return y * y
for x in range( 1, 11 ):
print (square(x))
Exercises
1. Write a Python function to calculate the factorial of a
number.
2. Write a Python function to calculate the sum of digits
of a given integer.
Summary
• Introduction to Function
• Syntax of Function
• Function with return value