Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11
FUNCTIONS
The process of dividing a computer program into separate independent
blocks of code or separate sub-problems with different names and specific functionalities is known as modular programming. Functions: Function can be defined as a named group of instructions that accomplish a specific task when it is asked. Once defined, a function can be called repeatedly from different places of the program without writing all the codes of that function every time, or it can be called from inside another function, by simply writing the name of the function and passing the required parameters. Advantages of Functions: 1. Increases readability, for longer code because the program is better organized and easy to understand. 2. Reduces code length as same code is not required to be written at multiple places in a program. This also makes debugging easier. 3. Increases reusability, as function can be called from another function or another program. Thus, we can reuse or build upon already defined functions and avoid repetitions of writing the same piece of code. 4. Work can be easily divided among team members and completed in parallel. There are two types of functions: Library Functions and User Defined Functions Library Functions: There are many functions already available in Python under standard library. We can call them directly without defining them, this is called library functions. User Defined Functions: a function defined to achieve some tasks as per the programmer's requirement is called a user defined function. Creating User Defined Functions: A function definition begins with def (short for define). The items enclosed in "[ ]" are called parameters and they are optional. Hence, a function may or may not have parameters. Also, a function may or may not return a value. Function header always ends with a colon (:). Function name should be unique. Rules for naming identifiers also applies for function naming. The statements outside the function indentation are not considered as part of the function. Write a user defined function to add 2 numbers and display their sum. #Function to add two numbers #The requirements are listed below: #1. We need to accept 2 numbers from the user. #2. Calculate their sum #3. Display the sum. #function definition def addnum(): fnum = int(input("Enter first number: ")) snum = int(input("Enter second number: ")) sum = fnum + snum print("The sum of ",fnum,"and ",snum,"is ",sum) #function call addnum() Arguments and Parameters: An argument is a value passed to the function during the function call which is received in corresponding parameter defined in function header. Write a program using a user defined function that displays sum of first n natural numbers, where n is passed as an argument. #Program to find the sum of first n natural numbers #function header def sumN(n): #n is the parameter sum = 0 for i in range(1,n+1): sum = sum + i print("The sum of first",n,"natural numbers is: ",sum) num = int(input("Enter the value for n: ")) #num is an argument referring to the value input by the user sumN(num) #function call Write a program using user defined function that accepts an integer and increments the value by 5. Also display the id of argument (before function call), id of parameter before increment and after increment. def incrValue(num): #id of Num before increment print("Parameter num has value:",num,"\nid =",id(num)) num = num + 5 #id of Num after increment print("num incremented by 5 is",num,"\nNow id is ",id(num)) number = int(input("Enter a number: ")) print("id of argument number is:",id(number)) #id of Number incrValue(number) Write a program using a user defined function calcFact() to calculate and display the factorial of a number num passed as an argument. #Function to calculate factorial def calcFact(num): fact = 1 for i in range(num,0,-1): fact = fact * i print("Factorial of",num,"is",fact) num = int(input("Enter the number: ")) calcFact(num) String as Parameters: Write a program using a user defined function that accepts the first name and lastname as arguments, concatenate them to get full name and displays the output as: def fullname(first,last): #+ operator is used to concatenate strings fullname = first + " " + last print("Hello",fullname) #function ends here first = input("Enter first name: ") last = input("Enter last name: ") fullname(first,last) #function call OUTPUT: Enter first name: Soda Enter last name: Bottlewala Hello Soda Bottlewala Default Parameter: A default value is a value that is predecided and assigned to the parameter when the function call does not have its corresponding argument. Write a program that accepts numerator and denominator of a fractional number and calls a user defined function mixedFraction() when the fraction formed is not a proper fraction. The default value of denominator is 1. The function displays a mixed fraction only if the fraction formed by the parameters does not evaluate to a whole number. def mixedFraction(num,deno = 1): remainder = num % deno #check if the fraction does not evaluate to a whole number if remainder!= 0: quotient = int(num/deno) print("The mixed fraction=", quotient,"(",remainder, "/", deno,")") else: print("The given fraction evaluates to a whole number") #function ends here num = int(input("Enter the numerator: ")) deno = int(input("Enter the denominator: ")) print("You entered:",num,"/",deno) if num > deno: #condition to check whether the fraction is improper mixedFraction(num,deno) #function call else: print("It is a proper fraction")
Functions returning value:
The functions that do not return a value is called void function. When we must send value(s) from the function to its calling function, it is done using return statement. The return statement does the following : a) returns the control to the calling function . b) return value(s) or none. Write a program using user defined function calcPow() that accepts base and exponent as arguments and returns the value Bas e exponent where Base and exponent are integers. def calcpow(number,power): #function definition result = 1 for i in range(1,power+1): result = result * number return result base = int(input("Enter the value for the Base: ")) expo = int(input("Enter the value for the Exponent: ")) answer = calcpow(base,expo) #function call print(base,"raised to the power",expo,"is",answer) Different types of functions are: • Function with no argument and no return value • Function with no argument and with return value(s) • Function with argument(s) and no return value • Function with argument(s) and return value(s) Flow of execution: The interpreter starts executing in a program from the first statement. When the interpreter encounters a function definition, the statements inside the function are not executed until the function is called. When the interpreter encounters a function call, the control jumps to the function rather than the next statement and executes the statement of the function. The control then comes back to execute the remaining statements. It is also important to note that a function must be defined before its call within a program. Write a program using user defined function that accepts length and breadth of a rectangle and returns the area and perimeter of the rectangle. def calcAreaPeri(Length,Breadth): area = length * breadth perimeter = 2 * (length + breadth) #a tuple is returned consisting of 2 values area and perimeter return (area,perimeter) l = float(input("Enter length of the rectangle: ")) b = float(input("Enter breadth of the rectangle: ")) #value of tuples assigned in order they are returned area,perimeter = calcAreaPeri(l,b) print("Area is:",area,"\nPerimeter is:",perimeter) Scope of a Variable: A variable defined inside a function cannot be accessed outside. The part of the program where a variable is accessible is called scope of a variable. The two types are: Global variable and local variable. Global Variable: A variable that is defined outside any function or any block is known as a global variable. It can be accessed in any functions which is defined later. Any change made to the global variable will impact all the functions in the program where that variable can be accessed. Local Variable: A variable that is defined inside any function or a block is known as a local variable. It can be accessed only in the function or a block where it is defined. It exists only till the function executes. Python Standard library: It is a collection of many built in functions that can be called in a program when required. Built in functions: they are readymade functions used in python that are frequently used in a program. Module: A group of functions is called a module. The program is divided into different parts under different levels called modules. To use a module, we need to import them and we can directly use all the functions of that module. import modulename1(,modulename2,…) To call a function of a module, the function should be preceded with the name of the module with a dot(.) as a separator. modulename.functionname() Built-in modules: Import statement can be written anywhere in the program. Module must be imported only once. To get a list of modules available in Python, we can use the following statement: >>> help("module").To view the content of a module say math, type the following: >>> help("math"). From statement: Instead of loading all the functions into memory by importing a module, from statement can be used to access only the required functions from a module. It loads only the specified function(s) instead of all the functions in a module. Its syntax is >>> from modulename import functionname [, functionname,...]. >>> from random import random >>> random() #Function called without the module name Output: 0.9796352504608387
>>> from math import ceil,sqrt
>>> value = ceil(624.7) >>> sqrt(value) Output: 25.0
Python Advanced Programming: The Guide to Learn Python Programming. Reference with Exercises and Samples About Dynamical Programming, Multithreading, Multiprocessing, Debugging, Testing and More
Instant ebooks textbook Financial Sector Development in Ghana: Exploring Bank Stability, Financing Models, and Development Challenges for Sustainable Financial Markets James Atta Peprah download all chapters
Python Advanced Programming: The Guide to Learn Python Programming. Reference with Exercises and Samples About Dynamical Programming, Multithreading, Multiprocessing, Debugging, Testing and More
Instant ebooks textbook Financial Sector Development in Ghana: Exploring Bank Stability, Financing Models, and Development Challenges for Sustainable Financial Markets James Atta Peprah download all chapters