Functions
§ A function is a reusable block of code that performs a specific task.
§ Two types: Built-in functions and user-defined functions
vBuilt-in functions: In-built (Inherently present) in the language. E.g. print( ), type
( ), range ( ), input( ), and many more.
vUser-defined functions: Those that are written by the user and allows a
programmer to break a problem into pieces (modules) that can be reused.
§ The modular programming helps a programmer focus on one part of a larger
problem at a time. As a result, writing functions is often an important part of
developing larger pieces of software.
§ In other words, functions allows you to break a large problem into smaller,
manageable functions. This makes code more organized and reusable.
§ Use-defined Functions can have inputs, called parameters, and they can
return values as outputs.
§ In Python, you define a function using the def keyword.
User-defined Function
Basic syntax of function is as follows:
Using User-defined functions to perform addition
§ Here, x and y are the parameters (numbers to be added), add is the function
defined (You can give any name to this function).
§ z = x + y is the formula (statement) and return will give output z.
§ Then you assign x and y values and print the output as sum.
§ Use-defined functioned can be used for numerical analysis such as
differentiation, integration, quadratic, polynomials etc.
Building Calculator using User-defined functions
functions allows you to break
a large problem into smaller,
manageable functions. This
makes code more organized
and reusable.
Problems 5
Q. 1. Distance between two points in a plane :
(a) Write a function Distance that reads the coordinates of two points in a plane and
returns the distance between the two points.
(b) Write a main program that asks the user to input the coordinates of the two points,
uses the function Distance to compute the distance between the points and displays the
output with appropriate message.
Q.2. Write a function Mean that reads a list of numbers and return the mean (Average)
of the numbers and displays both the given list of numbers & the mean with appropriate
messages
Q.3. Comparing Strings: Write a function nearlyequal to compare two strings. The
function should return:
’Strings are equal’ if the two strings are identical
’Strings are nearly equal’ if the two strings differ in just one character
’Strings are not nearly equal’ if the two strings differ in more than one character
’Strings cannot be compared’ if the two strings are of unequal lengths
Q.4. Write a Slogan and pass it as a parameter to a function.
(a) Count the number of characters
(b) Count the number of vowels
Return these two numbers to main function and display the output.