0511241056292731 (6)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

STD X – AI – PRACTICAL PROGRAMS

(solution)

1) Factorial Number using While Loop


Aim:
To find the factorial for given number using while loop.
Program:
#Python program find factorial of a number # using while loop

num=int(input("Enter a number to find factorial:"))#takes input from user


factorial=1;#declareandinitializefactorialvariabletoone#checkifthe
numberisnegative,positiveorzero
if num<0:
print("Factorial does not defined for negative integer")
elif (num==0):
print("The factorial of 0 is 1");
else:
while(num>0):
factorial=factorial*num
num=num-1
print("factorial of the given number is:",factorial)
Output:

Result:
Thus the Python program to find the factorial for a given number using
while loop has been verified and executed successfully.
2) Fibonacci Series using for loop
Aim:
To find the Fibonacci series till a given number using for loop.
Program:
n=int(input("Enter the number of series:"))

first, second=0, 1

print("Fibonacciseries")

print(first, second, end='') #first2 nos of series

for i in range(2,n):

third = first + second

print(third, end='')

first, second = second, third

Output:

Result:

Thus the Python program to find the Fibonacci series till a given number

using for loop has been verified and executed successfully.


3) Finding Prime Numbers between given Limits
Aim:
To find the prime numbers between the given Limits.

Coding:
#Take the input from the user:
lower=int(input("Enterlowerrange:"))
upper=int(input("Enter upper range:"))
for num in range(lower,upper+1):
if num>1:
for i in range(2,num):
if(num % i)==0:
break
else:
print(num)
Output:

Result:

Thus the Python program to find the prime numbers between the given
limits has been verified and executed successfully.
4) String Palindrome
Aim:
To find the whether a given string is palindrome or not.
Coding:
#Python Program to Check a Given String is Palindrome or Not

string = input("Please enter your own String:")


str1=""
for i in string:
str1 = i + str1
print("String in reverse Order:", str1)
if(string==str1):
print("This is a Palindrome String")
else:
print("This is Not a Palindrome String")
Output:

Result:

Thus the Python program to find whether the given string is palindrome or
not has been verified and executed successfully.
5. Check whether the entered number is Armstrong or not.

Aim:
To create a simple pyramid pattern in python

Coding:
#Enter a number to check

n=int(input("Enter number to check:")) #Store the original number into temporary variable
t=n

s=0 #Computing the sum of cube of each digit and iterating until n=0
while n!=0:

r=n%10
s=s+(r**3)
n//=10 #Checking & displaying whether armstrong or not

if t==s: print(s," is Armstrong number")


else:
print(s," is not an Artmstrong number")

Output:

Result:

Thus the Python program to create a simple pyramid pattern has been

verified and executed successfully.


6. Simple Pyramid Pattern (Asterisk Symbol)
Aim:
To create a simple pyramid pattern in python

Coding:
rows=int(input("Enter number of rows:"))
k=0
for i in range(1,rows+1):
for space in range(1,(rows-i)+1):
print(end="")
while k!=(2*i-1):
print("* ", end="")
k+=1
k=0
print()

Output:

Result:

Thus the Python program to create a simple pyramid pattern has been
verified and executed successfully.
7. Counting alphabets, digits, uppercase, lower case
and special characters in a string.
Aim:
To create a Python program for counting the number of alphabets, digits,
upper case, lower case and special characters in a string.
Coding:
str1='0123abcdEFG@@@'
digit=upper=lower=0
special=alpha=0
for x in str1:
if x.isalnum():
if x.isalpha():
alpha += 1
if x.isupper():
upper+=1
else:
lower+=1
else:
digit+=1
else:
special+=1
print("digit is:",digit)
print("uppercase is:",upper)
print("lowercase is:",lower)
print("alphabet is:",alpha)
print("special character is:",special)
Output:

Result:
Thus the Python program for counting the number of alphabets, digits,
upper case, lower case and special characters in a string has been
verified and executed successfully.
8. Program to add the elements of the two lists.

Aim:
To create a Python program to add the elements of the two lists.
Coding:

print("Enter two lists of same size")


L = eval(input("Enter first list(L): "))

M = eval(input("Enter second list(M): "))


N = []

for i in range(len(L)):
N.append(L[i] + M[i])

print("List N:")
print(N)

OUTPUT:

Result:

Thus the Python program to add the elements of the two lists has been
verified and executed successfully.
9. Program to draw bar chart
Aim:
To create a Python program to draw a bar chart.
Coding:

import matplotlib.pyplot as pl
year=['2015','2016','2017','2018','2019']
p=[98.5,70.2,55.6,90.5,61.5]
c=['b','g','r','m','c']
pl.bar(year,p,width=0.5,color=c)
pl.title("BARCHART")
pl.xlabel("Year")
pl.ylabel("Profit%")
pl.show()

Output:

Result:

Thus the Python program to draw a bar chart has been verified and
executed successfully.
10. Program to plot a Chart for y=x2

Aim:
To create a Python program to plot a Chart for y=x2.

Coding:
import matplotlib.pyplot as pl
import numpy as np
pl.title("LINEGRAPH")
pl.xlabel("xaxis")
pl.ylabel("yaxis")
x=np.linspace(-50,50)
y=x**2
pl.plot(x,y,linestyle="dotted")
pl.show()

Output:

Result:

Thus the Python program to plot a Chart for y=x2 has been verified and
executed successfully.
11. Program to draw a pie chart

Aim:
To create a Python program to draw a pie chart.

Coding:
import matplotlib.pyplot as plt
runs=[77,103,42,22]
players=['Rohitsharma','MSdhoni','Jasmitbumrah','Viratkohli']
cols=['c','m','r','b']
plt.pie(runs,labels=players,colors=cols,startangle=90,shadow=True,explode=(0,0.0,0,0.1),aut
opct='%1.1f%%')
plt.title('Runs Scored Chart')
plt.show()

Output:

Result:
Thus the Python program to draw a pie chart has been verified and

executed successfully.
12. Program to convert a python list to a NumPy array.

Aim:
To create a Python program to draw a pie chart.
Coding:
#Import NumPy Package

import numpy as np
#Creating empty

list l = []
#Take input for n no. of elements

n=int(input("Enter the no. of elements:"))

#Append the values into the list


for i in range(n):
val=int(input("Enter value "+str(i+1)+":"))
l.append(val)
#Converting list into numpy array
arr=np.array(l)
print("Array:",arr)

Output:

Result:
Thus the Python program to draw a pie chart has been verified and
executed successfully.
13. Basic Array operations in numpy using for loop

Aim:
To create a Python program to perform basic array operations in numpy
module using for loop.

Coding:
import numpy as np
a1 = np.array([[1, 2,3],[4, 5,6], [2,4,2],[6,8,9]])
a2=np.array([[1,1,1],[2,3,4],[2,4,2],[2,2,2]])
print("Array1:")
for i in a1:
print(i)
print("Array2:")
for j in a2:
print(j)
print("Sum of two arrays")
sum=np.add(a1,a2)
print(sum)

Output:

Result:
Thus the Python program to perform basic array operations in numpy
module using for loop has been verified and executed successfully.
14. Date and Time Operation in Python
Aim:
To create a Python program to perform Date and Time Operation.
Coding:
import datetime as dt
import calendar
#To print date and time
my_date= dt.datetime.now()
print(my_date)
#To print time alone
my_time=dt.datetime.now().time()
print(my_time)
#To get month from date
print('Month:',my_date.month)
# To get month from year
print('Year:',my_date.year)
#To get day of the month
print('Day of Month:', my_date.day)
# to get name of day(in number) from date
print('Day of Week(number):',my_date.weekday())
#to get name of day from date
print('Day of Week(name):',calendar.day_name[my_date.weekday()])

Output:

Result:
Thus the Python program to perform Date and Time Operation has been
verified and executed successfully.
15. Python program for various math function
Aim:
To create a Python program to perform various math operations.
Coding:
import math
val1=eval(input("Enter a decimal value to find its floor & ceiling value:"))
print('The Ceiling of the',val1,"=",math.ceil(val1))
print('The Floor of the',val1,"=",math.floor(val1)) #finding square root
val2=eval(input("Enter a value to find its square root:"))
print('Square root of ',val2,"=",math.sqrt(val2)) #finding power
print('The value of 5^8: ',math.pow(5,8)) #finding gcd
a1=int(input("Enter number1:"))
a2=int(input("Enter number2:"))
print('The GCD of:',a1,a2,'=',math.gcd(a1,a2)) #finding area of circle using pi value
r=eval(input("Enter radius of circle:"))
pi=math.pi
area=pi*r*r
print("Area of circle is:",area)

Output:

Result:
Thus the Python program to perform various math operations has been
verified and executed successfully.
16. Computer Vision
Visit https://www.w3schools.com/colors/colors_rgb.asp.
On the basis of this online tool, try and write answers of all the below-
mentioned questions.

i. What is the output colour when you put R=G=B=255?

ii. What is the output colour when you put R=G=255,B=0?

iii. What is the output colour when you put R=255,G=0,B=255?

iv. What is the output colour when you put R=0,G=255,B=255?

v. What is the output colour when you put R=G=B=0?

vi. What is the output colour when you Put R=0,G=0,B=255?

vii. What is the output colour when you Put R=255,G=0,B=0?

viii. What is the output colour when you put R=0,G=255,B=0?

ix. What is the value of your colour?


17. Do the following tasks in Open CV.
a. Load an image and Give the title of the image.
b. Change the colour of image and Change the image to grayscale.
c. Print the shape of image.
d. Display the maximum and minimum pixels of image.
e. Crop the image and extract the part of an image.
f. Save the Image.

Aim:
To write a program to perform
a. Load an image and Give the title of the image.
b. Change the colour of image and Change the image to grayscale.
c. Print the shape of image.
d. Display the maximum and minimum pixels of image.
e. Crop the image and extract the part of an image.
f. Save the Image.
Coding:
1. Load Image and Give the title of image
#import required module cv2, matplotlib and numpy
import cv2
import matplotlib.pyplot as plt
import numpy as np #Load the image file into memory
img = cv2.imread('d:\\DOG.jpg') #Display Image
plt.imshow(img)
plt.title('DOG')
plt.axis('off')
plt.show()

Output:
2. Change the colour of image and Change the image to grayscale
#import required module cv2, matplotlib and numpy
import cv
import matplotlib.pyplot as plt
import numpy as np
#Load the image file into memory
img = cv2.imread('d:\\DOG.jpg')
#Chaning image colour image colour
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.title('DOG')
plt.axis('off')
plt.show()

Output:

3. Print the shape of image


import cv2
img = cv2.imread('d:\\DOG.jpg',0)
print(img.shape)
Output:
4. Display the maximum and minimum pixels of image
import cv2
img = cv2.imread('d:\\DOG.jpg',0)
print(img.min())
print(img.max())
Output:

5. Crop the image and extract the part of an image


import cv2
import matplotlib.pyplot as plt
img = cv2.imread('d:\\DOG.jpg')
pi=img[150:400,100:200]
plt.imshow(cv2.cvtColor(pi, cv2.COLOR_BGR2RGB))
plt.title('DOG')
plt.axis('off')
plt.show()

Output:
6. Save the Image
import cv2
import matplotlib.pyplot as plt
img = cv2.imread('d:\\DOG.jpg')
plt.imshow(img)
cv2.imwrite('d:\\DOG.jpg',img)
plt.title('DOG')
plt.axis('off')
plt.show()
Output:

Result:
Thus the Python program to perform various tasks in Open CV has been
verified and executed successfully.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy