GOVERNMENT POLYTECHNIC MUZAFFARPUR Name – Sakshi kumari Roll no. – 2024-CSE-01 Branch – Computer Science & Engineering Mentor name :- Prof. Naiyer Hoda sir
Functions in Python ~ Sakshi kumari
Functions Function is a named, reusable block of code used to perform a specific task which can be executed repeatedly Characteristics Reusable – A function is reusable. It can be used any number of times in a program. No need to create it again. Readable – Python program is created as a set of functions. It makes program more readable. Easy to maintain – It is easy to find an error and debug (correct error) a program .
Function Syntax
Types of functions ( i ) Built-in functions (ii) Functions defined in module (iii) User-defined functions Output - Hello, World! Example : # Define a simple function def greet(): print( " Hello, World!") # Call the function greet()
Built-in Function Built-in functions are a set of predefined functions always available for use. These functions are used directly and do not need to import them from a module. Examples : print() – displays output len () – returns length of an object input() – prompts user from input from keyword sum() – calculates sum of elements in collection data type int(), float(), str() – convert value to integer, float, or string range() – generates a sequence of numbers type() – returns data type of an object
Functions defined in Module Module is a python file that contains a code to perform a specific task. A module contains functions, variables, classes , etc. Example : math module, time date module. Functions defined in module cannot be used directly and we need to import them . To import a module, we write import and then module name e.g , import math. Examples of math module functions math.ceil () – rounds-up to next integer. math.floor () – rounds-down to previous integer. math.factorial () – returns factorial of number math.exp () – returns e**x math.sqrt () – returns square root of a number math.pow (x, y) – returns x**y
Example :- import math print( math.ceil (2.34)) print( math.floor (2.34)) print( math.factorial (4)) print( math.exp (0)) print( math.sqrt (81)) print( math.pow (4, 3)) Output – 3 2 24 1.0 9.0 64.0 User-defined Functions User-defined functions are blocks of reusable code created by a user to perform specific tasks .