How to Make functions in python
As we know in python math module there is in built functions are factorial(),max(),min(),pallindrome() .thesefunctions are in built ,buthere today we will learn how to define these function by user (you or I).
so we are going to make function i.e
max().
Testcases1:
Input:
[1,6,3,7,7]
Output:
7
Testcases2:
[9,7,90,43]
Output:
90
#Now your max()function is made by your code ,so i think you have understood that you can also make the functions that are already made i.ein built function.
So my aim is to clarify you that all the functions are made using these things these are not automatically made or these are not made by any .
Now we will move forward to make min() function to find number from the list
Testcases1:
Input:
[9,6,96,9,1,8,7]
Output:
1
Testcases2:
Input:
[1,-7,4,8,3]
Output:
-7
Through this program or by calling your function you can find minimum value from the list.
Now i think you have learned that how can you make your own function even you can call your own function in another file .
Now we will make function i.e factorial function that is already inbuilt in python module i.e math module but here we will learn how to make our factorial function .
Factorial means
5! (This is called five factorial)=5*4*3*2*1=120
4=4*3*2*1=24
Testcases1:
5
Output:
120
How this program will run see below:
Let take example
num=5
Now it will go to for loop the value of i will go upto num because for loop go upto num+1-1 i.e num
so ,
fact=fact*i
here value of
i=1 fact=1
fact=1*1=1
now value of i will increase by +1
i=2 fact=1
fact=1*2=2
i=3 fact=2
fact=2*3=6
i=4 fact=6
fact=6*4=24
i=5 fact=24
fact=24*5=120
this is program how it will run.
Similarily we will move to make a function i.e pallindrome() function to pallindrome of any number.
Pallindrome means it opposite is equal then it is called pallindrome.
Example;
N=121
This is pallindrome
N=122
Not pallindrome number.
Testcases1:
Input:
121
Output:
Pallindrome number
Testcases2:
Input:
231
Output:
Not Pallindrome
How To check pallindrome number?
To check given number is pallindrome or not ,you must have to reverse the given number.then we can check that the given number is pallindrome or not.
How This program will execute:
Let take a example:
N=121
Now value of rev=0 i.e reverse and temp=121 beacuse we have assigned the value of N in temp variable
Now while loop check your given number greater than 0 or not.Here True then it will execute the task in its indent
Now
rem=N%10=121%10=1
rev=rev*10+rem=0*10+1=1
N=N//10=121//10=12
Again now value of N will check in the while loop it is greater than 0 the again it will come in its intend and do the task.
rem=N%10=12%10=2 because N=12
rev=rev*10+rem=1*10+2=12
N=N//10=12//10=1
Now value of N is 1 that is greater than 0 or not .
Now it will come in the intend
rem=1%10=1
rev=rev*10+rem=12*10+1=121
N=N//10=1//10=0
Now value of N is 0 then N is not greater than 0 so your loop will stop.
No comments: