In todays post lets see some simple programs with function!!!!
GCD of two numbers:
Gcd stands for greatest common divisor
def computeGcd(x,y):
if(x>y):
smaller=y
else:
smaller=x
for i in range(1, smaller+1):
if((x%i==0)and(y%i==0):
gcd=i
return gcd
num1 = int(input("Enter first number:"))
num2 = int(input("Enter second number:"))
print("The gcd of number is:"computeGcd(num1,num2)
Output:
Enter first number:2
Enter second number:8
The gcd of number is: 2
In this program we calculate gcd of two numbers by creating function named computeGcd().Then by using if condition we are finding smallest number. Then inside a for loop we are performing following step till smaller+1
->check if((x%i==0) and (y%i==0))
then assign gcd=i last print the gcd
To find exponential of the number:
def power(base,exp):
if(exp==1):
return(base)
if(exp!=1):
return(base*power(base,exp-1))
base = int(input("Enter base value:"))
exp = int(input("Enter exponential value:"))
print("result:", power (base,exp))
Output:
Define a function named power() with parameters base and exp. Then read the value of base and exp by using if condition check if the exp is equal to 1or not
-> if 1 print base value
->if exp is not equal to 1 then return base*power(base,exp-1)
At last print the result,
Finding maximum from a list of numbers:
l = []
n = int(input("Enter the upper limit:"))
for i in range(0,n):
a = int(input("enter the numbers:"))
l.append(a)
max_no=l[0]
for i in range (0,len(l)):
if l[i]>max_no:
max_no=l[i]
print("the maximum number is",max_no)
Output:
Create a empty list named l read the value of n.
Then read the value of list elements until n. Assign l[0] as max_no.
If l[i]>max_no then set max_no = l[i].
Increment i by 1.
Repeat the following until the last element of the list.
Finally print the max_no value
To make it more clear and understandable go to the python console page and try the code with different variable and values or try the program in your editor. If you have any doubt feel free to comment!!!!!
Comments
Post a Comment