0% found this document useful (0 votes)
6 views

Python Lab 10174

Uploaded by

Naman Roy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Python Lab 10174

Uploaded by

Naman Roy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Laboratory Record

CSE3011
Python Programming

C11 + C12, BL2023240500583


Winter Semester: 2024

Submitted To Dr. Ashish Mohan Yadav


Submitted By Avishi Jain
Registration No. 21BCE10174

VIT Bhopal University, Bhopal, Madhya Pradesh 466114

1
Index

Exp
Title of the Experiment
No.
Write a Python program to print a list of numbers using range and a
1.
for loop.
2. Write a Python program to print the first n prime numbers.

3. Write a Python program to multiply matrices.

Write a Python program to take command-line arguments (word


4.
count).
Write a Python program in which a function is defined, and calling that
5.
function prints 'Hello World'.
Write a Python program to let the user enter some data in a string and
6.
then verify the data and print a welcome to the user.
7. Write a Python program to store strings in a list and then print them.

Write a Python program to find the most frequent words in a text read
8.
from a file.
Write a Python program in which a class is defined, then create an
9. object of that class and call a simple 'print' function defined in the
class.
Write a Python program in which a function (with a single string
10. parameter) is defined, and calling that function prints the string
parameter given to the function.
11. Simulate elliptical orbits in Pygame.

12. Simulate a bouncing ball using Pygame.

2
Experiment 1:
Aim: Write a Python program to print a list of numbers using range and for loop.
Code:
numbers_list = [] # We Create An Empty List To Store Our Numbers
# Then We Loop Through The Range & Append Each Number To The List 1 To 10
for num in range(1, 11): # 1 To 11 As Range Function Outputs Upto Limit N-1
numbers_list.append(num) # Store Numbers In List Using Append Function

# Print The List Of Numbers


print("List of numbers:", numbers_list)

Output:

Variable List:
Sl.
Variable Name Description
No.
1. A list variable initialized as an empty list to store
numbers_list
numbers
2. Loop variable used to iterate through the range
num
of numbers
3. Range object that generates numbers from 1 to
range(1, 11)
10 (inclusive)

3
Experiment 2:
Aim: Write a Python program to print the first n prime numbers.
Code:
# Function To Find If Number Is Prime Or Not
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True

# Function To Find Prime Numbers Upto Range Of First N Numbers


def first_n_primes(n):
primes = [] # List To Store Prime Numbers
num = 2
while len(primes) < n: # Loop To Run Till N Prime Numbers Found
if is_prime(num): # If Number Prime, Then Append To List
primes.append(num)
num += 1
return primes

# Asks Value Of N From User & Prints Results


n = int(input("Enter the value of n: "))
print("First", n, "prime numbers:", first_n_primes(n))

Output:

Variable List:
Sl.
Variable Name Description
No.
Parameter for the function is_prime, represents the
1. num
number to check.
Loop variable used to iterate through numbers to check
2. i
for primality.
3. primes A list variable initialized to store prime numbers.
4. The input variable representing the number of prime
n
numbers to find.

4
Experiment 3:
Aim: Write a Python program to multiply matrices.
Code:
# Function To Multipy Matrix
def matrix_multiply(matrix1, matrix2):
result = []
for i in range(len(matrix1)):
row = []
for j in range(len(matrix2[0])):
value = 0
for k in range(len(matrix2)):
value += matrix1[i][k] * matrix2[k][j]
row.append(value)
result.append(row)
return result

# Inputs Matrix & Displays Output


matrix1 = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]

matrix2 = [[9, 8, 7],


[6, 5, 4],
[3, 2, 1]]

result_matrix = matrix_multiply(matrix1, matrix2)


print("Resultant Matrix:")
for row in result_matrix:
print(row)

Output:

5
Variable List:
Sl.
Variable Name Description
No.
1. matrix1 The first matrix input to the matrix_multiply function.
2. matrix2 The second matrix input to the matrix_multiply function.
A list variable initialized to store the result of matrix
3. result
multiplication.
4. i Loop variable used to iterate through rows of matrix1.
5. j Loop variable used to iterate through columns of matrix2.
Loop variable used to iterate through rows of matrix2 and
6. k
columns of matrix1.
7. row A list variable initialized to store each row of the result matrix.
8. value A variable to store the result of each multiplication operation.
The resulting matrix obtained from the matrix_multiply
9. result_matrix
function.

6
Experiment 4:
Aim: Write a Python program to take command-line arguments (word count).
Code:
import sys #Import sys Library
if len(sys.argv) == 2: #Count The Words
print("The Number of words:", len(sys.argv[1].split()))
else:
print("Usage: python prg4.py <text>")

Output:

Variable List:
Sl.
Variable Name Description
No.
List containing command-line arguments passed to the
1. sys.argv
Python script.
Module providing access to some variables used or
2. sys maintained by the Python interpreter and to functions that
interact with the interpreter.
Built-in Python function to return the number of items in an
3. len
object.
The string containing the text provided as a command-line
4. text
argument.

7
Experiment 5:
Aim: Write a Python program in which a function is defined, and calling that function prints 'Hello
World'.
Code:
# Defined Function Which Stores The Code To Print Hello World
def print_hello():
print("Hello World")

# Calling The Function


print_hello()

Output:

Variable List:
Sl.
Variable Name Description
No.
The name of the function defined to print
1. print_hello
"Hello World".

8
Experiment 6:
Aim: Write a Python program to let the user enter some data in a string and then verify the data and
print a welcome to the user.
Code:
# Accept Input From User
user_input = input("Enter your name: ")

# Verifying The Input


if user_input.strip(): # Checking If Input Is Not Empty After Removing Whitespace &
Prints Result
print("Welcome to", user_input)
else:
print("You did not enter anything. Please try again.")

Output:

Variable List:
Sl.
Variable Name Description
No.
The variable storing the input received
1. user_input
from the user.

9
Experiment 7:
Aim: Write a Python program to store strings in a list and then print them.
Code:
# Define An Empty List To Store Strings
strings_list = []

# Ask User For Input Strings Till They Enter An Empty String
while True:
string = input("Enter A String (Blank Input To Stop): ")
if string:
strings_list.append(string) # Appends String To List
else:
break

# Print The Strings Stored In The List


print("Strings entered by the user:")
for string in strings_list:
print(string)

Output:

Variable List:
Sl.
Variable Name Description
No.
The list variable initialized to store the input
1. strings_list
strings.
The variable storing each string inputted by the
2. string
user.

10
Experiment 8:
Aim: Write a Python program to find the most frequent words in a text read from a file.
Code:
from collections import Counter

file_path = r'C:\Users\amank\Desktop\Text.txt' # Using Raw String Literal


with open(file_path, 'r') as file: # Opening File In The Specific Location
text = file.read()

# Split The Text Into Words & Counts Their Frequencies


word_freq = Counter(text.split())

# Finding The Most Frequent Word


most_common_words = word_freq.most_common(1) # Changing This Value Will Give Us More
Than 1 Word Which Is Present

print("Most Frequent Word In The Text:") # Prints Result


for word, freq in most_common_words:
print(word, "-", freq, "times")

Output:

Text File:

11
Variable List:
Sl.
Variable Name Description
No.
Class from the collections module used to count the
1. Counter
occurrences of elements in a list or string.
The file path variable representing the location of the text file
2. file_path
to be read.
3. text The string variable storing the contents of the text file.
The Counter object storing the frequencies of each word in
4. word_freq
the text.
A list containing tuples of the most frequent word(s) and their
5. most_common_words
frequency.
The variable storing each word in the most common word(s)
6. word
found.
The variable storing the frequency of the most common
7. freq
word(s).

12
Experiment 9:
Aim: Write a Python program in which a class is defined, then create an object of that class and call a
simple 'print' function defined in the class.
Code:
# Defined Class With Single Print Function
class MyClass:
def print_message(self):
print("Hello from MyClass!")

# Creating An Object Of Class - MyClass


obj = MyClass()

# Calling The print_message Function Of The Object


obj.print_message()

Output:

Variable List:
Sl.
Variable Name Description
No.
1. MyClass The name of the class defined.
2. obj The object created from the class MyClass.

13
Experiment 10:
Aim: Write a Python program in which a function (with a single string parameter) is defined, and calling
that function prints the string parameter given to the function.
Code:
# Single Parameter Function
def print_string(parameter):
print(parameter)

# Calling The Function With A String Parameter


print_string("This Is A Test String 21BCE10501")

Output:

Variable List:
Sl.
Variable Name Description
No.
The name of the function defined to print a string
1. print_string
parameter.
The parameter variable representing the string
2. parameter
passed to the function.

14
Experiment 11:
Aim: Simulate elliptical orbits in Pygame.
Code:
import pygame
import math
pygame.init() # Initializing Pygame
width, height = 800, 600 # Setting Up The Display
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Elliptical Orbits")

# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)

# Ellipse Parameters
semi_major_axis = 200
semi_minor_axis = 150
center_x, center_y = width // 2, height // 2

# Main Loop
clock = pygame.time.Clock()
angle = 0

running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

# Clearing The Screen


screen.fill(BLACK)

# Calculating The Position Of The Object


x = center_x + semi_major_axis * math.cos(math.radians(angle))
y = center_y + semi_minor_axis * math.sin(math.radians(angle))

# Drawing The Ellipse & Object


pygame.draw.ellipse(screen, WHITE, (center_x - semi_major_axis, center_y -
semi_minor_axis, 2 * semi_major_axis, 2 * semi_minor_axis), 1)
pygame.draw.circle(screen, RED, (int(x), int(y)), 5)

# Incrementing The Angle To Simulate Orbit Motion

15
angle += 1
if angle >= 360:
angle = 0

# Updating The Display


pygame.display.flip()

# Capping The Frame Refresh Rate


clock.tick(60)
pygame.quit()

Output:

16
Variable List:
Sl.
Variable Name Description
No.
Module providing access to the Pygame library
1. pygame
functions.
2. math Module providing access to mathematical functions.
3. width The width of the Pygame display.
4. height The height of the Pygame display.
5. screen The Pygame surface representing the display screen.
6. WHITE Constant representing the color white.
7. BLACK Constant representing the color black.
8. RED Constant representing the color red.
9. semi_major_axis The semi-major axis length of the ellipse.
10. semi_minor_axis The semi-minor axis length of the ellipse.
11. center_x The x-coordinate of the center of the ellipse.
12. center_y The y-coordinate of the center of the ellipse.
13. clock Pygame clock object used to control the frame rate.
14. angle The angle variable used to simulate the orbit motion.
Boolean variable to control the main loop of the
15. running
program.
16. event Pygame event object representing user events.
17. x The x-coordinate of the object's position on the ellipse.
18. y The y-coordinate of the object's position on the ellipse.

17
Experiment 12:
Aim: Simulate a bouncing ball using Pygame.
Code:
import pygame
pygame.init() # Initializing Pygame
width, height = 800, 600 # Setting up the display
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Bouncing Ball")
# Assigning Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)

# Assigning Ball Parameters


ball_radius = 20
ball_x, ball_y = width // 2, height // 2
velocity_x, velocity_y = 5, 5

# Main Loop
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

# Moving The Ball


ball_x += velocity_x
ball_y += velocity_y

# Bouncing Off The Walls


if ball_x + ball_radius >= width or ball_x - ball_radius <= 0:
velocity_x *= -1
if ball_y + ball_radius >= height or ball_y - ball_radius <= 0:
velocity_y *= -1

# Clearing The Screen


screen.fill(BLACK)

# Drawing The Ball


pygame.draw.circle(screen, RED, (int(ball_x), int(ball_y)), ball_radius)

# Updating The Display

18
pygame.display.flip()

# Capping The Frame Refresh Rate


clock.tick(60)
pygame.quit()

Output:

19
Variable List:
Sl.
Variable Name Description
No.
Module providing access to the Pygame library
1. pygame
functions.
2. width The width of the Pygame display.
3. height The height of the Pygame display.
The Pygame surface representing the display
4. screen
screen.
5. WHITE Constant representing the color white.
6. BLACK Constant representing the color black.
7. RED Constant representing the color red.
8. ball_radius The radius of the bouncing ball.
9. ball_x The x-coordinate of the ball's position.
10. ball_y The y-coordinate of the ball's position.
11. velocity_x The velocity of the ball along the x-axis.
12. velocity_y The velocity of the ball along the y-axis.
13. clock Pygame clock object used to control the frame rate.
Boolean variable to control the main loop of the
14. running
program.
15. event Pygame event object representing user events.

20

You might also like