Python Programs for Variable Exchange and Distance Calculation
Python Programs for Variable Exchange and Distance Calculation
AIM
To write a Write a python program using Simple Statements to exchange the values of two
variables
ALGORITHM
1. Declared a two variable a and b
2. Assign the value of a and b,
3. Assign the value of a to b, and b to a
4. we don’t even need to perform arithmetic operations. We can use: a,b = b,a
5. Display the result
6. End the program.
PROGRAM
a=int(input(“enter the value of A”))
b=int(input(”enter the value of B”))
a,b=b,a
print("The swapping of a value is=",a)
print("The swapping of b value is=",b)
OUTPUT
enter the value of A 5
enter the value of B 4
The swapping of a value is= 4
The swapping of b value is= 5
RESULT
The Python program to exchange the values of two variables has been executed
successfully, and the output has been verified.
Ex No: 1b
Date : PYTHON PROGRAMMING USING SIMPLE STATEMENTS AND
EXPRESSIONS(CALCULATE THE DISTANCE BETWEEN TWO POINTS)
AIM
To write a python program to calculate the distance between two points
ALGORITHM
1. Start the program.
2. Read all the values of x1,x2,y1,y2
3. Calculate the distance using the Formula
4. Display the result
5. End the program.
PROGRAM
import math
x1=int(input("enter the value of x1="))
x2=int(input("enter the value of x2="))
y1=int(input("enter the value of y1="))
y2=int(input("enter the value of y2="))
dx=x2-x1
dy=y2-y1
d=dx**2+dy**2
result=[Link](d)
print(result)
OUTPUT
enter the value of x1=5
enter the value of x2=6
enter the value of y1=6
enter the value of y2=3
3.1622776601683795
RESULT
The python program to calculate the distance between two points has been executed
successfully, and the output has been verified.
AIM
To write a Python program to print Number Series using Conditional and Iterative Loops
ALGORITHM
1. Start the program.
2. Read the value of n
3. Initialize i = 1,x=0.
4. Repeat the following until i is less than or equal to n.
5. : x=x*2+1.
6. Print x.
7. Increment the value of i
8. End the program.
PROGRAM
n=int(input(" Enter the number of terms for the series "))
i=1
x=0
while(i<=n):
x=x*2+1
print(x)
i+=1
OUTPUT
Enter the number of terms for the series 5
1
3
7
15
31
RESULT
The Python program to print Number Series using Conditional and Iterative Loops
Executed successfully and the output is verified.
Ex No: 2b
SCIENTIFIC PROBLEMS USING CONDITIONALS AND
Date : ITERATIVE LOOPS. –NUMBER PATTERNS
AIM
To write a Python program to print Number Pattern using Conditional and Iterative
Loops
ALGORITHM
1. Start the program.
2. Declare the value for rows.
3. Let i and j be an integer number
4. Repeat step 5 to 8 until all value parsed.
5. Set i in outer loop using range function, i = rows+1 and rows will be initialized to i
6. Set j in inner loop using range function and i integer will be initialized to j;
7. Print i until the condition becomes false in inner loop.
8. Print new line until the condition becomes false in outer loop.
9. End the program.
PROGRAM
rows = int(input('Enter the number of rows'))
for i in range(rows+1):
for j in range(i):
print(i, end = ' ')
print(' ')
OUTPUT
Enter the number of rows5
1
22
333
4444
55555
RESULT
The Python program to print Number Pattern using Conditional and Iterative
Loops executed successfully and the output is verified.
AIM
To write a Python program to print Pyramid using Conditional and Iterative Loops
ALGORITHM
1. Start the program
2. Read the value for rows.
3. Let i and j be an integer number.
4. Repeat step 5 to 8 until all value parsed.
5. Set i in outer loop using range function, i = 0 to rows ; y
6. Set j in inner loop using range function, j=0 to i+1;
7. Print * until the condition becomes false in inner loop.
8. Print new line until the condition becomes false in outer loop.
9. Stop the program..
PROGRAM
n = int(input('Enter the number of rows'))
for i in range(0,n):
for j in range(0,i+1):
print("*", end = '')
print(' ')
OUTPUT
RESULT
The Python program to print Pyramid using Conditional and Iterative Loops executed
successfully and the output is verified.
Ex No: 3a
IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USING
Date : LISTS, TUPLES-ITEMS PRESENT IN A LIBRARY)
AIM
To write a python program to print items present in a library using Lists and Tuples
ALGORITHM
1. Start the program
2. Create the variable inside that variable assigned the list of elements based on the
library using List and tuple
3. Using array index to print the items using list and tupel
4. To print the result using output statement
5. End the program.
PROGRAM
library=["books", "author", "barcodenumber" , "price"]
library[0]="Let us C"
print(library[0])
library[1]=" Yashavant Kanetkar"
library[2]=123987
library[3]=234
print(library)
tup1 = (12134,250000 )
tup2 = ('books', 'totalprice')
tup3 = tup1 + tup2;
print(tup3)
OUTPUT
Let us C
['Let us C', 'Yashavant Kanetkar', 123987, 234]
(12134, 250000, 'books', 'totalprice')
RESULT
The python program to print items present in a library using Lists and Tuples executed
successfully and the output is verified.
AIM
To write a python program to print system names using Lists and Tuples
ALGORITHM
1. Start the program.
2. Create the variable inside that variable assigned the list of elements based on the car
using List and tuple
3. Using array index to print the items using list and tuple
4. print the result using output statement
5. Display the result
6. End the program.
PROGRAM
LIST:
Computers = ["Dell", "Lenovo", "HP", "Apple", "Acer", "Asus"]
new_list = []
for i in computers:
if "A" in i:
new_list.append(i)
print(new_list)
TUPLE:
Computers=("Dell", "Lenovo", "HP", "Apple", )
print(Computers)
print(Computers [0])
print(Computers [1])
print(Computers [2])
print(Computers [3])
OUTPUT
LISTS
['Apple']
['Apple', 'Acer']
['Apple', 'Acer', 'Asus']
TUPLE:
('Dell', 'Lenovo', 'HP', 'Apple')
Dell
Lenovo
HP
Apple
RESULT
Thus the python program to print system names using Lists and Tuples was successfully
executed and the output is verified.
AIM
To write a python program to print materials required for construction of a building using
Lists and Tuples
ALGORITHM
PROGRAM
LISTS:
materials= ["cementbags", "bricks", "sand", "Steelbars", "Paint"]
[Link](“ Tiles”)
[Link](3,"Aggregates")
[Link]("sand")
materials[5]="electrical"
print(materials)
TUPLES:
materials = ("cementbags", "bricks", "sand", "Steelbars", "Paint")
print(materials)
print ("list of element is=",materials)
print ("materials[0]:", materials [0])
print ("materials[1:3]:", materials [1:3])
OUTPUT
LIST:
TUPLE:
RESULT
Thus the python program to print materials required for construction of a building using
Lists and Tuples was successfully executed and the output is verified
AIM
ALGORITHM
1. Start the program.
2. Create the variable and stored the unordered list of elements based on materials
required for construction of building set and dictionary
3. Using for loop to list the number of elements and using array index to print the items
using set and dictionary
4. print the result using output statement
5. Display the result.
6. End the program.
PROGRAM
SETS:
DICTIONARY:
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements one at a time
Dict[0] = 'BRICKS'
Dict[2] = 'CEMENT'
Dict[3] = BLUE PRINT
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values # to a single Key
Dict['Value_set'] = 2, 3, 4
OUTPUT
SETS:
Approach#1= {'BMW','Mercedes','Toyota','Audi','Ferrari','Tesla','Honda'}
==========
Approach #2
Car name = BMW
Car name = Mercedes
Car name = Toyota
Car name = Audi
Car name = Ferrari
Car name = Tesla
Car name = Honda
==========
New cars set = {'BMW', 'Mercedes', 'Toyota', 'Audi', 'Ferrari', 'Tesla', 'Honda', 'Tata'}
discard() method = {'BMW', 'Toyota', 'Audi', 'Ferrari', 'Tesla', 'Honda', 'Tata'}
DICTIONARY:
Empty Dictionary:{}
Dictionary after adding 3 elements:
{0: 'BRICKS', 2: 'CEMENT', 3: 'BLUE_PRINT'}
Dictionary after adding 3 elements:
{0: 'BRICKS', 2: 'CEMENT', 3: 'BLUE_PRINT', 'Value_set': (2, 3, 4)}
Updated key value:
{0: 'BRICKS', 2: 'STEEL', 3: 'BLUE_PRINT', 'Value_set': (2, 3, 4)}
Adding a Nested Key:
{0: 'BRICKS', 2: 'STEEL', 3: 'BLUE_PRINT', 'Value_set': (2, 3, 4), 5: {'Nested': {'1': 'LIME', '2':
'SAND'}}}
RESULT
Thus the python program to implement Components of an automobile using Sets and
Dictionaries was successfully executed and verified.
Ex No: 5a
IMPLEMENTING FACTORIAL PROGRAMS USING FUNCTIONS
Date :
AIM
To Write a Python Program to calculate the factorial of a number using functions
ALGORITHM
1. Start the program.
2. Get a positive integer input (n) from the user.
3. check if the values of n equal to 0 or not if it's zero it will return 1 Otherwise else
statement can be executed
4. Using the below formula, calculate the factorial of a number n*factorial(n-1)
5. Display the result
6. End the program.
PROGRAM
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number to compute the factiorial : "))
print(factorial(n))
OUTPUT
Input a number to compute the factiorial: 4
24
RESULT
Thus a Python Program to calculate the factorial of a number using functions is
successfully executed and the output is verified.
AIM
To Write a Python program to get the largest number from a list using Functions
ALGORITHM
1. Start the program.
2. Declare a function that will find the largest number
3. Use max() method and store the value returned by it in a variable
4. Return the variable
5. Declare and initialize a list or take input
6. Call the function and print the value returned by it
7. Display the Result
8. End the program.
PROGRAM
def max_num_in_list( list ):
max = list[ 0 ]
for a in list:
if a > max:
max = a
return max
print(max_num_in_list([1, 2, -8, 0]))
OUTPUT
2
RESULT
Thus the Python program to get the largest number from a list using Functions is
successfully executed and the output is verified.
Ex No: 5c IMPLEMENTING PROGRAMS USING FUNCTIONS – AREA OF
Date: SHAPE
AIM
To Write a python program to implement area of shape using functions
ALGORITHM
1. Start the program
2. Get the input from the user shape’s name.
3. If it exists in our program then we will proceed to find the entered shape’s area according
to their respective formulas
4. If that shape doesn’t exist then we will print “Sorry!
5. End of the program.
PROGRAM
name = input("Enter the name of shape whose area you want to find: ")
calculate_area(name)
# define a function for calculating
# the area of a shapes
def calculate_area(name):\
name = [Link]()
# check for the conditions
if name == "rectangle":
l = int(input("Enter rectangle's length: "))
b = int(input("Enter rectangle's breadth: "))
# calculate area of rectangle
rect_area = l * b
print(f"The area of rectangle is {rect_area}.")
elif name =="square":
s = int(input("Enter square's side length: "))
# calculate area of square
sqt_area = s * s
print(f"The area of square is {sqt_area}.")
elif name == "triangle":
h = int(input("Enter triangle's height length: "))
b = int(input("Enter triangle's breadth length: "))
# calculate area of triangle
tri_area = 0.5 * b * h
print(f"The area of triangle is{tri_area}.")
elif name == "circle":
r = int(input("Enter circle's radius length: "))
pi = 3.14
# calculate area of circle
circ_area = pi * r * r
print(f"The area of circle is{circ_area}.")
elif name == 'parallelogram':
b = int(input("Enter parallelogram's base length: "))
h = int(input("Enter parallelogram's height length: "))
# calculate area of parallelogram
para_area = b * h
print(f"The area of parallelogram is{para_area}.")
else:
print("Sorry! This shape is not available")
# driver code
if name == "__main__" :
print("Calculate Shape Area")
OUTPUT
Calculate Shape Area
Enter the name of shape whose area you want to find: rectangle
Enter rectangle's length: 10
Enter rectangle's breadth: 15
The area of rectangle is 150.
RESULT
The python program to implement area of shape using functions is executed successfully
and the output is verified.
Ex No: 6a
IMPLEMENTING PROGRAMS USING STRINGS –REVERSE
Date:
AIM
To write a python program to implement reverse of a string using string functions
ALGORITHM
1. Start the program.
2. Using function string values of arguments passed in that function
3. python string to accept the negative number using slice operation
4. to print the reverse string value by Using reverse method function
5. print the result
6. End the program.
PROGRAM
def reverse(string):
string = string[::-1]
return string
s =input("enter a string")
print ("The original string is : ",end="")
print (s)
print ("The reversed string(using extended slice syntax) is : ",end="")
print (reverse(s))
OUTPUT
The original string is : Firstyearcse
The reversed string(using extended slice syntax) is : escraeytsriF
RESULT
Python program to implement reverse of a string using string functions is executed
successfully and the output is verified.
Ex No: 6b IMPLEM
Date:
AIM
To write a python program to implement palindrome using string functions
ALGORITHM
1.
Start the program.
2.
Declare the function isPalindrome() and passing the string argument.
3.
Then, in the function body,
4.
To get the reverse of the input string using a slice operator – string[::-1].
5.
-1 is the step parameter that ensures that the slicing will start from the end of the string
with one step back each time.
6. if the reversed string matches the input string, it is a palindrome Or else, it is not a
palindrome.
7. End of the program.
PROGRAM
def isPalindrome(s):
return s == s[::-1]
# Driver code
s = input("Enter the string=")
ans = isPalindrome(s)
if ans:
print("the string is palindrome ")
else:
print("The string is not a palindrome")
OUTPUT
Enter a string: madam
The string is a palindrome
RESULT
The python program to implement palindrome using string functions is executed
successfully and the output is verified.
AIM
To write a python program to implement Characters count using string functions.
ALGORITHM
1. Start the program.
2. User to enter the string. Read and store it in a variable.
3. Initialize one counter variable and assign zero as its value.
4. Increment this value by 1 if any character is found in the string.
5. Using one loop, iterate through the characters of the string one by one.
6. Check each character if it is a blank character or not. If it is not a blank character,
increment the value of the counter variable by ’1‘.
7. After the iteration is completed, print out the value of the counter.
8. This variable will hold the total number of characters in the string.
9. End the program.
PROGRAM
input_string = input("Enter a string : ") count = 0
for c in input_string :
if [Link]() != True:
count = count + 1
print("Total number of characters : ",count)
OUTPUT
Enter a string: Hello, world!
Total number of characters : 13
RESULT
Thus the a python program to implement Characters count using string functions is
executed successfully.
AIM
To Write a python program to implement File Copying.
PROCEDURE
1. Start the program.
2. Creating/opening an output file in writing mode.
3. Opening the input file in reading mode
4. Reading each line from the input file and writing it in the output file.
5. End the program.
PROGRAM
# Creating an output file in writing mode
output_file = open("[Link]",'w')
# Opening input file and scanning each line
# from input file and writing in output file
with open("[Link]",'r') as scan:
output_file.write([Link]())
# Closing the output file
output_file.close()
OUTPUT
RESULT
Thus the python program to implement File Copying is executed successfully.
AIM
To write a python program to implement word count in File operations in python.
ALGORITHM
1. Start the program.
2. create a text file of which we want to count the number of words
3. Create a new variable to store the total number of words in the text file
4. open the text file in read-only mode using the open() function.
5. Read the content of the file using the read() function
6. storing them in a new variable. And then split the data stored in the data variable into
separate lines using the split() function and then storing them in a new variable.
7. add the length of the lines in our number_of_words variable. End the program.
PROGRAM
number_of_words = 0
with open(r"[Link]",'r') as file:
# Reading the content of the file
# using the read() function and storing
# them in a new variable
data = [Link]()
# Splitting the data into separate lines
# using the split() function
lines = [Link]()
# Adding the length of the
# lines in our number_of_words
# variable
number_of_words += len(lines)
# Printing total number of words
print(number_of_words)
OUTPUT
5
RESULT
Thus the python program to implement word count in File operations in python is
executed successfully.
AIM
To write a exception handling program using python to depict the divide by zero Error
ALGORITHM
1. Start the program.
2. The try block tests the statement of error. The except block handle the error.
3. A single try statement can have multiple except statements. This is useful when the try
block contains statements that may throw different types of exceptions
4. To create the two identifier name and enter the values
5. by using division operation and if there is any error in that try block raising the error in
that block
6. display the result
7. End the program.
PROGRAM
a=int(input("Entre a="))
b=int(input("Entre b="))
try:
c = ((a+b) / (a-b))
if a==b:
raise ZeroDivisionError #Handling of error
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)
OUTPUT
Enter a=6
Enter b=4
5.0
RESULT
Thus the python program to implement Characters count using string functions is
executed successfully.
AIM
To write a exception handling program using python to depict the voters eligibility
ALGORITHM
1. Start the program.
2. Read the input file which contains names and age by using try catch exception handling
method
3. To Check the age of the person. if the age is greater than 18 then write the name into
voter list otherwise write the name into non voter list.
4. Display the Result.
5. End the program.
PROGRAM
age=int(input("Enter your age"))
try:
if age>18:
print("Eligible to vote")
else:
print("Not eligible to vote")
except:
print("age must be a valid number")
main()
OUTPUT
Enter your age20
Eligible to vote
RESULT
Thus the a python program to implement Characters count using string functions is
executed successfully.
AIM
To write a python program to implement pandas
ALGORITHM
1. Start the program.
2. Read the input file which contains names and age by using try catch exception handling
method
3. To Check the age of the person. if the age is greater than 18 then write the name into
voter list otherwise write the name into non voter list.
4. Display the Result.
5. End the program.
PROGRAM
import pandas as pd
df = [Link]({"Name": [ "Mr. Owen Harris", "Mr. William Henry","Miss.
Elizabeth",],
"Age": [22, 35, 58], "Sex": ["male", "male", "female"],})
print(df)
print(df["Age"])
ages = [Link]([22, 35, 58],name="Age")
print(ages)
df["Age"].max()
print([Link]())
print([Link]())
OUTPUT
Name Age Sex
0 Braund, Mr. Owen Harris 22 male
1 Allen, Mr. William Henry 35 male
2 Bonnell, Miss. Elizabeth 58 female
0 22
1 35
2 58
Name: Age, dtype: int64
0 22
1 35
2 58
Age
count 3.000000
mean 38.333333
std 18.230012
min 22.000000
25% 28.500000
50% 35.000000
75% 46.500000
max 58.000000
RESULT
Thus the a python program to implement Pandas package is executed successfully.
AIM
To Write a python program to implement Numpy package.
ALGORITHM
1. Start the program.
2. Create the package of numpy in python and using array index in Numpy for numerical
calculation
3. Create the array index inside that index to assign the values in that dimension
4. Declare the method function of arrange statement can be used in that program
5. Display the Result.
6. End the program.
PROGRAM
import numpy as np
a = [Link](6)
a2 = a[[Link], :]
[Link]
#Array Creation and functions:
a = [Link]([1, 2, 3, 4, 5, 6])
a = [Link]([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(a[0])
print(a[1])
[Link](2)
[Link](2)
[Link](4)
[Link](2, 9, 2)
[Link](0, 10, num=5)
x = [Link](2, dtype=np.int64)
print(x)
arr = [Link]([2, 1, 5, 3, 7, 4, 6, 8])
[Link](arr)
a = [Link]([1, 2, 3, 4])
b = [Link]([5, 6, 7, 8])
[Link]((a, b)) #Array Dimensions:
array_example = [Link]([[[0, 1, 2, 3], [4, 5, 6, 7]], [[0, 1, 2, 3], [4, 5, 6, 7]],[[0 ,1 ,2, 3], [4, 5, 6,
7]]])
array_example.ndim
array_example.size
array_example.shape
a = [Link](6)
print(a)
b=[Link](3, 2)
print(b)
[Link](a, newshape=(1, 6), order='C')
OUTPUT
[1 2 3 4]
[5 6 7 8]
[1 1]
[0 1 2 3 4 5]
[[0 1]
[2 3]
[4 5]]
array([[0, 1, 2, 3, 4, 5]])
RESULT
Thus the python program to implement Numpy package is executed successfully.
AIM
`To write a python program to implement matplotlib
ALGORITHM
1. Start the program.
2. It divided the circle into 4 sectors or slices which represents the respective
category(playing, sleeping, eating and working) along with the percentage they hold.
3. Now, if you have noticed these slices adds up to 24 hrs, but the calculation of pie slices is
done automatically .
4. In this way, pie charts are calculates the percentage or the slice of the pie in same way
using area plot etc using matplotlib
5. Display the Result.
6. End the program.
PROGRAM
import [Link] as plt
days = [1,2,3,4,5]
sleeping =[7,8,6,11,7]
eating = [2,3,4,3,2]
working =[7,8,7,2,2]
playing = [8,5,7,8,13]
slices = [7,2,2,13]
activities = ['sleeping','eating','working','playing']
cols = ['c','m','r','b']
[Link](slices,labels=activities, colors=cols, startangle=90,shadow= True,
explode=(0,0.1,0,0), autopct='%1.1f%%')
[Link]('Pie Plot')
[Link]()
OUTPUT
RESULT
Thus the python program to implement Matplotlib is executed successfully.
AIM
To write a python program to implement scipy
ALGORITHM
1. Start the program.
2. The SciPy library consists of a subpackage named [Link] that consists of spline
functions and classes, one-dimensional and multi-dimensional (univariate and
multivariate) interpolation classes, etc.
3. To import the package of np in a program and create x,x1,y,y1 identifier inside that
assign the np function
4. SciPy provides interp1d function that can be utilized to produce univariate interpolation
5. Display the Result.
6. End the program.
PROGRAM
import [Link] as plt
from scipy import interpolate
import numpy as np
x = [Link](5, 20)
y = [Link](x/3.0)
f = interpolate.interp1d(x, y)
x1 = [Link](6, 12)
y1 = f(x1) # use interpolation function returned by `interp1d`
[Link](x, y, 'o', x1, y1, '--')
[Link]()
OUTPUT
RESULT
Thus the python program to implement Scipy is executed successfully.
AIM
To Write a exception handling program using python to depict the voters eligibility
ALGORITHM
1. Start the program.
2. Import the dataset
3. Create a DataFrame df from this dictionary data which has the index labels.
4. Display a summary of the basic information about this DataFrame and its data.
5. Return the first 3 rows of the DataFrame df.
6. Select just the 'animal' and 'age' columns from the DataFrame df.
7. Select only the rows where the number of visits is greater than 2.
8. Check for null values using isnull() function
9. Group the values using groupby() function
10.
11. Sort df first by the values in the 'age' in descending order, then by the value in the 'visit'
column in ascending order.
12. Display the Result.
13. End the program.
PROGRAM
import pandas as pd
data = {'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'],
'age': [2.5, 3, 0.5, [Link], 5, 2, 4.5, [Link], 7, 3],
'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = [Link](data, index=labels)
df
OUTPUT
PROGRAM
[Link]()
OUTPUT
PROGRAM
[Link](3)
OUTPUT
PROGRAM
[Link][[Link][[3, 4, 8]], ['animal', 'age']]
OUTPUT
PROGRAM
df['visits']>2
OUTPUT
a False
b True
c False
d True
e False
f True
g False
h False
i False
j False
Name: visits, dtype: bool
PROGRAM
df[df['age'].isnull()]
OUTPUT
PROGRAM
df[(df['animal']=='cat')&(df['age']<3)]
OUTPUT
PROGRAM
df[df['age'].between(2,4)]
OUTPUT
PROGRAM
[Link]('animal')['age'].mean()
OUTPUT
animal
cat 2.5
dog 5.0
snake 2.5
Name: age, dtype: float64
PROGRAM
df['animal'].value_counts()
OUTPUT
animal
cat 4
dog 4
snake 2
Name: count, dtype: int64
PROGRAM
df.sort_values(by=['age', 'visits'], ascending=[False,True])
OUTPUT
RESULT
Thus the a python program to explore Pandas package is executed successfully.
AIM
To Write a exception handling program using python to depict the voters eligibility
ALGORITHM
1. Start the program.
2. create a list comprising numbers from 0 to 9
3. creating arrays
4. creating a 3 row x 5 column matrix
5. creating a matrix with a predefined value
6. create an array with a set sequence
7. create an array of even space between the given range of values
8. create an array of even space between the given range of values
9. create a 3x3 array with mean 0 and standard deviation 1 in a given dimension
10. create an identity matrix
11. set a random seed
12. Display the Result.
13. End the program.
PROGRAM
import numpy as np
L = list(range(10))
[str(c) for c in L]
OUTPUT
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
PROGRAM
[type(item) for item in L]
OUTPUT
[int, int, int, int, int, int, int, int, int, int]
PROGRAM
[Link](10, dtype='int')
OUTPUT
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
PROGRAM
[Link]((3,5), dtype=float)
OUTPUT:
PROGRAM
[Link]((3,5),1.23)
OUTPUT
array([[ 1.23, 1.23, 1.23, 1.23, 1.23],
[ 1.23, 1.23, 1.23, 1.23, 1.23],
[ 1.23, 1.23, 1.23, 1.23, 1.23]])
PROGRAM
[Link](0, 20, 2)
OUTPUT
array([0, 2, 4, 6, 8,10,12,14,16,18])
PROGRAM
[Link](0, 1, 5)
OUTPUT
array([ 0., 0.25, 0.5 , 0.75, 1.])
PROGRAM
[Link](0, 1, (3,3))
OUTPUT
array([[ 0.72432142, -0.90024075, 0.27363808],
[ 0.88426129, 1.45096856, -1.03547109],
[-0.42930994, -1.02284441, -1.59753603]])
PROGRAM
[Link](3)
OUTPUT
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
PROGRAM
[Link](0)
x1 = [Link](10, size=6) #one dimension
x2 = [Link](10, size=(3,4)) #two dimension
x3 = [Link](10, size=(3,4,5)) #three dimension
print("x3 ndim:", [Link])
print("x3 shape:", [Link])
print("x3 size: ", [Link])
OUTPUT
('x3 ndim:', 3)
('x3 shape:', (3, 4, 5))
('x3 size: ', 60)
RESULT
Thus the python program to implement Numpy package is executed successfully.
Date :
AIM
To write a python program to stimulate elliptical orbits in Pygame
ALGORITHM
1. Import the necessary header files for the implementation of this pygame.
2. Set the display mode for the screen using screen= [Link].set_mode
((700,700))
3. Develop the balls with necessary colors.
white=(255,255,255)
blue=(0,0,255)
yellow=(255,255,0)
gray=(200,200,200)
black=(0,0,0)
4. Set the radius for sun, moon and their orbit.
5. Set the time for the pygame orbit clock=[Link]()
6. Update the earth position.
7. Again update moon position based on earth position.
8. Update the moon and earth angles.
9. Reset the screen and draw the stars, sun, moon and the earth.
10. Set the clock tick as (60) and exit
PROGRAM
import pygame
import random
import math
[Link]()
screen=[Link].set_mode((700,700))
white=(255,255,255)
blue=(0,0,255)
yellow=(255,255,0)
gray=(200,200,200)
black=(0,0,0)
sun_radius=50
center=(350,350)
earth_x=50
earth_y=350 earth_orbit=0
moon_orbit=0
clock=[Link]()
running=True
stars=[([Link](0,699),[Link](0,699)) for x in range(140)]
while running:
for event in [Link]():
if [Link]==[Link]:
running=False
earth_x=[Link](earth_orbit)*300+350
earth_y=-[Link](earth_orbit)*300+350
moon_x=[Link](moon_orbit)*50+earth_x
moon_y=-[Link](moon_orbit)*50+earth_y
earth_orbit+=0.002
moon_orbit+=0.01
[Link](black)
for star in stars:
x,y=star[0],star[1]
[Link](screen,white,(x,y),(x,y))
[Link](screen,yellow,center,sun_radius)
[Link](screen,blue,(int(earth_x),int(earth_y)),15)
[Link](screen,gray,(int(moon_x),int(moon_y)),5)
[Link]()
[Link](60)
[Link]()
OUTPUT
RESULT
Thus the simulation of Elliptical orbits using Pygame has been successfully executed.
Ex No: 11b SIMULATE BOUNCING BALL USING PYGAME
Date :
AIM
To write a python program to simulate bouncing ball using Pygame.
ALGORITHM
1. Import the necessary files for the implementation of this Pygame.
2. Set the display mode for the screen using windowSurface=[Link].set_mode
((500,400),0,32)
3. Now set the display mode for the pygame to bounce [Link].set_caption
(“Bounce”)
4. Develop the balls with necessary colors.
BLACK=(0,0,0)
WHITE=(255,255,255)
RED=(255,0,0)
GREEN=(0,255,0)
BLUE=(0,0,255)
5. Set the display information info=[Link]()
6. Set the initial direction as down.
7. Change the direction from down to up.
8. Then again change the direction from up to down.
9. Set the condition for quit.
10. Exit from the pygame
PROGRAM
import pygame,sys,time
import random [Link]
import * from time
import * [Link]()
windowSurface=[Link].set_mode((500,400),0,32)
[Link].set_caption("Bounce")
BLACK=(0,0,0)
WHITE=(255,255,255)
RED=(255,0,0)
GREEN=(0,255,0)
BLUE=(0,0,255)
info=[Link]()
sw=info.current_w
sh=info.current_h
y=0 direction=1
while True:
[Link](BLACK)
[Link](windowSurface,GREEN,(250,y),13,0)
OUTPUT
RESULT
Thus the bouncing ball using pygame has been successfully executed.
Ex No: 11c
SIMULATE SIMPLE SNAKE PROGRAM
Date :
AIM:
ALGORITHM:
PROGRAM:
import pygame
# --- Globals ---
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# Set the width and height of each snake
segment segment_width = 15
segment_height = 15
# Margin between each segment
segment_margin = 3
# Set initial speed
x_change = segment_width + segment_margin
y_change = 0
class Segment([Link]):
# Class to represent one segment of the snake
def __init (self, x, y):
# Call the parent's constructor
super(). init ()
# Set height, width
[Link] = [Link]([segment_width, segment_height])
[Link](WHITE)
# Make our top-left corner the passed-in location.
[Link] = [Link].get_rect()
[Link].x = x [Link].y =
# Call this function so the Pygame library can initialize itself
[Link]()
# Create an 800x600 sized screen
screen = [Link].set_mode([800, 600])
# Set the title of the window [Link].set_caption('Snake Example')
allspriteslist = [Link]()
# Create an initial snake
snake_segments = []
for i in range(15):
x = 250 - (segment_width + segment_margin) * i
y = 30
segment = Segment(x, y)
snake_segments.append(segment)
[Link](segment)
clock = [Link]()
done = False
while not done:
for event in [Link]():
if [Link] == [Link]:
done = True
# Set the speed based on the key pressed
# We want the speed to be enough that we move a full
# segment, plus the margin.
if [Link] == [Link]:
if [Link] == pygame.K_LEFT:
x_change = (segment_width + segment_margin) * -1
y_change = 0
if [Link] == pygame.K_RIGHT:
x_change = (segment_width + segment_margin)
y_change = 0
if [Link] == pygame.K_UP:
x_change = 0
y_change = (segment_height + segment_margin) * -1
if [Link] == pygame.K_DOWN:
x_change = 0
y_change = (segment_height + segment_margin)
# Get rid of last segment of the snake
# .pop() command removes last item in list
old_segment = snake_segments.pop()
[Link](old_segment)
# Figure out where new segment will be
x = snake_segments[0].rect.x + x_change
y = snake_segments[0].rect.y + y_change
segment = Segment(x, y)
# Insert new segment into the list
snake_segments.insert(0, segment)
[Link](segment)
# -- Draw everything
# Clear screen [Link](BLACK)
[Link](screen)
# Flip screen [Link]()
# Pause [Link](5)
[Link]()
OUTPUT:
RESULT:
Thus the simulation of simple snake program using pygame has been successfully
executed.
Ex No: 12a
Date : Basics functions used in Python programming language
[Link]
Ex No: 12b
Date : Basics Strings used in Python programming language
[Link]