1. Function to return arithamtic claculation
def arithmaticOperation(a,b):
return a+b,a-b,a*b,a/b
arithmaticOperation(a=4,b=2)
(6, 2, 8, 2.0)
2. Swap two values
def swapvalues(a,b):
a,b=b,a
return a,b
swapvalues(5,6)
(6, 5)
3. Function return String
#Method 1 -
def return_string(num):
print(type(num))
if type(num) is not str:
return str(num)
else:
return num
#Method 2 -
def convert_to_string(my_input):
print(type(my_input))
print(my_input)
is_numeric = isinstance(my_input, (float, int))
if is_numeric:
return str(my_input)
else:
return my_input
return_string(num=5)
'5'
type(return_string(num=5))
type(return_string('Fusion Forest'))
4. Function to get Area of triangle
def triangle_area(b,h):
return .5*b*h
triangle_area(10,5)
25.0
def triangle_area():
b = float(input("Enter base of triangle : "))
h = float(input("Enter height of triangle : "))
return .5*b*h
triangle_area()
Enter base of triangle : 2
Enter height of triangle : 2
2.0
5. Function to get the largest number
def largest_num(list_in):
return max(list_in)
largest_num(list_in=[1,2,3,4,5])
5
6. Function removing duplicates
def removeDuplicate(list_in):
return(set(list_in))
removeDuplicate(list_in=[1,1,1,1,1,1,1,1,2,2,2,3,3,4,4,5])
{1, 2, 3, 4, 5}
7. Function to sum the whole list
def sumList(list_in):
return sum(list_in)
sumList(list_in=[1,1,1,1,1,1,1,1,2,2,2,3,3,4,4,5])
33
8. Function reversing the String
#Method 1 -
def reverseString(mstr):
new_str = ""
for i in mstr:
new_str = i + new_str
return new_str
#Method 2 -
def reverseString(mstr):
return mstr[::-1]
reverseString("Fusion Forest")
tseroF noisuF
9. Factorial Function -
def factorial(num):
fact=1
for i in range(1, num+1):
fact *= i
return fact
factorial(5)
120
Comments