Program Practice
Program Practice
a string.
Using a for loop
count = 0
my_string = "Programiz"
my_char = "r"
for i in my_string:
if i == my_char:
count += 1
print(count)
Output
2
In the above example, we have found the count
of 'r' in 'Programiz'. The for-loop loops over each character
of my_string and the if condition checks if each character
of my_string is 'r'. The value of count increases if there is a
match.
Using method count()
my_string = "Programiz"
my_char = "r"
print(my_string.count(my_char))
Output
2
count() counts the frequency of the character passed as
parameter.
Program 2:
WAP to perform sequential search using
function.
def seq_Search(list1, n, key):
list1 = [1 ,3, 5, 4, 7, 9]
key = 4
n = len(list1)
res = seq_Search(list1, n, key)
if(res == -1):
print("Element not found")
else:
print("Element found at index: ", res)
output:
Element found at index: 3
solution:
• factorial(5)
•
• 5*factorial(4)
• 5*4*factorial(3)
• 5*4*3*factorial(2)
• 5*4*3*2*factorial(1)
• 5*4*3*2*1 = 120
Prog 4:
WAP to print Fibonacci sequence using recursive
function.
def fibo(n):
if n <= 1:
return n
else:
return(fibo(n-1) + fibo(n-2))
# take input from the user
print(" enter a positive integer")
n = int(input("How many terms? "))
print("Fibonacci sequence:")
for i in range(n):
print(fibo(i))
output:
enter positive integer
how many terms? 6
011235
Prog 5: Python Program to find volume, surface
area of a cuboid.
import math
def find_surafce_area(l, b, h):
# formula of surface_area = 2(lb + bh + hl)
Surface_area = 2 * ( l * b + b * h + h * l)
print(Surface_area)
def find_volume(l, b, h):
# volume = (l * b*h)
Volume = (l * b * h)
print(Volume)
# Driver Code
l=9
b=6
h = 10
find_surafce_area(l, b, h)
find_volume(l, b, h)
output:
408
540
Program 6:
Write a program that uses doc strings and
multiple length arguments passed to a function.
def add(*args)
’’’ function returns the sum of values passed to
it’’’
sum=0
for i in args:
sum+=i
return sum
print(add.__doc__)
print(“ sum= “ , add( 4, 5, 6 ))
output:
function returns the sum of values passed to it
sum= 15
Prog 5:
WAP to check number is Armstrong or not.
num = int(input("Enter a number: "))
sum = 0
n1 = len(str(num))
temp = num
digit = temp % 10
sum += digit ** n1
temp //= 10
if num == sum:
else:
print(num,"is not an Armstrong number")