FUNCTIONS in Python
FUNCTIONS in Python
FUNCTIONS in Python
Example 1-
def hello():
print(“how are you”)
hello()
Example 2-
def greet(name):
print(“hello”,name)
print(“how are you”)
greet(“Rose”)
number_a=5
number_b=6
add(number_a,number_b)
example 2-
def add_numbers(n1,n2):
sum=n1+n2
return sum
number1=5
number2=10
result=add_numbers(number1,number2)
print(“the sum is”,result)
BUILT IN FUNCTIONS
1. Float(),int(),input(),type()
2. Len()
Example- marks=[55,64,50,45]
Length=len(marks)
Print(“length is ”,length)
3. sum()
a=sum(marks)
print(“total marks”,a)
4. round()
eg:-
print(round(15))
print(round(51.6))
print(round(54.3))
print(round(2.665,2) ) - 2.67
print(round(2.676,2)) -2.68
print(round(2.592,2)) -2.60
example 2
def calc(a, b):
sum(a, b)
diff(a, b)
mult(a,b)
div(a,b)
def sum(x, y):
c=x+ y
print (“sum= ",c)
a=int(input())
b=int(input())
calc(a,b)
Example 3
import math
def pri_Twice(bruce):
print(bruce, bruce)
pri_Twice('Spam')
pri_Twice(5)
pri_Twice(3.14159)
pri_Twice('Spam'*4)
pri_Twice(math.cos(math.pi))
output
Spam Spam
55
3.14159 3.14159
SpamSpamSpamSpam SpamSpamSpamSpam
-1.0 -1.0
Recursive functions
To find the factorial of a number using recursion-
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
def fact(n):
res = 1
return res
n = int(input("enter n"))
r = int(input("enter r"))
print(int(nCr(n, r)))
a,b=2,4
print (check(a,b))
Output
0.5
5,0
def quadrant(x, y):
if (x > 0 and y > 0):
print ("lies in First quadrant")
else:
print ("lies at origin")
x = int(input())
y = int(input())
quadrant(x, y)
a=int(input()
y= int (input(“press 1 to find whether the no is odd or even\n press 2
”)
if y==1
def odd_even(a)
elif y==2
def
else
def
10-1,10,2,5