PYTHON LAB MANUAL EEE DEPT

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

UCEST 105-PYTHON LAB

INDEX
Page
TOPIC Number

Syllabus 3

Course Outcome 4

List Of Experiments

LIST OF PROGRAMS

1. Program to find the largest of three numbers. 5

2. Convert temperature values back and forth between Celsius (c), and Fahrenheit (f). 6

3. Simple desktop calculator using Python. Only the five basic arithmetic operators.. 7

4. Create, concatenate, and print a string and access a sub-string from a given string 9

5. Familiarize time and date in various formats 10

6. Write a program to create, append, and remove elements in lists 11

7. Program to construct patterns of stars (*), using a nested for loop. 14


A program that prints prime numbers less than N.
8. 16

9. Program to find the factorial of a number using Recursion. 17


Recursive function to add two positive numbers.
10. 18
Recursive function to multiply two positive numbers.
11. 19

12. Recursive function to find the greatest common divisor of two positive numbers 20
A program that accepts the lengths of three sides of a triangle as inputs. The program
should output whether or not the triangle is a right triangle (Recall from the
13. Pythagorean Theorem that in a right triangle, the square of one side equals the sum 21
of the squares of the other two sides). Implement using functions.

Program to define a module to find Fibonacci Numbers and import the module to
14. 22
another program.
Program to check whether the given number is a valid mobile number or not using
15. 23
functions.

1
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

Program to merge and sort list


16. 24

17. Program to play stick games 25

18. Monty hall probelm 27

2
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

SYLLABUS
LAB EXPERIMENTS:

1. Demonstrate about Basics of Python Programming


2. Demonstrate about fundamental Data types in Python Programming. (i.e., int,
float, complex, bool and string types)
3. Demonstrate different Arithmetic Operations on numbers in Python.
4. Create, concatenate, and print a string and access a sub-string from a given
string.
5. Familiarize time and date in various formats (Eg. “Sun May 29 02:26:23 IST
2017”)

6. Write a program to create, append, and remove lists in Python using numPy.
7. Programs to find the largest of three numbers.
8. Convert temperatures to and from Celsius, and Fahrenheit. [Formula: c/5 = f-
32/9]
9. Program to construct the stars (*) pattern, using a nested for loop
10. Program that prints prime numbers less than 20.
11. Program to find the factorial of a number using Recursion.
12. Recursive function to add two positive numbers.
13. Recursive function to multiply two positive numbers
14. Recursive function to the greatest common divisor of two positive numbers.
15. Program that accepts the lengths of three sides of a triangle as inputs. The
program output should indicate whether or not the triangle is a right triangle
(Recall from the Pythagorean Theorem that in a right triangle, the square of
one side equals the sum of the squares of the other two sides).
Implement using functions.
16. Program to define a module to find Fibonacci Numbers and import the module
to another program.
17. Program to define a module and import a specific function in that module to
another program.
18. Program to check whether the given number is a valid mobile number or not
using functions?

3
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

COURSE OUTCOMES
Course Objectives:

1. To provide students with a thorough understanding of algorithmic thinking and


its practical applications in solving real-world problems.
2. To explore various algorithmic paradigms, including brute force, divide-and-
conquer, dynamic programming, and heuristics, in addressing and solving
complex problems.

Bloom’s
Course Outcome Knowledge
Level (KL)
Utilize computing as a model for solving real-world problems.
CO1
K2
Articulate a problem before attempting to solve it and prepare a
CO2
clear and accurate model to represent the problem. K3

Utilize effective algorithms to solve the formulated models and


CO3
translate algorithms into executable programs. K3
Interpret the problem-solving strategies, a systematic approach
CO4 to solving computational problems, and essential Python
programming skills K2

Note: K1- Remember, K2- Understand, K3- Apply, K4- Analyse, K5- Evaluate, K6-
Create

Mapping of course outcomes with program outcomes

PO PO PO PO PO PO PO PO PO PO PO PO
1 2 3 4 5 6 7 8 9 10 11 12

CO 1 3 3 2 3

CO 2 3 3 3
3

CO 3 3 3 3 3

CO 4 3 3 3 3

4
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

PROG-1
Program to find the largest of three numbers..

AIM
To find the largest of three numbers.
PROGRAM
# Input three numbers from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))

# Determine the largest number


if num1 >= num2 and num1 >= num3:
largest = num1
elif num2 >= num1 and num2 >= num3:
largest = num2
else:
largest = num3

# Print the largest number


print("The largest number is:", largest)
RESULT
The largest of three numbers are obtained.

5
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

PROG-2
Convert temperature values back and forth between Celsius (C), and
Fahrenheit (F)
AIM
To Convert temperature values back and forth between Celsius (C), and Fahrenheit (F).
PROGRAM
print("\nTemperature Conversion:")
print("1. Convert Celsius to Fahrenheit")
print("2. Convert Fahrenheit to Celsius")
choice = input("Enter your choice (1/2): ")

if choice == '1':
# Convert Celsius to Fahrenheit
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C is equal to {fahrenheit}°F")

elif choice == '2':


# Convert Fahrenheit to Celsius
fahrenheit = float(input("Enter temperature in Fahrenheit: "))
celsius = (fahrenheit - 32) * 5/9
print(f"{fahrenheit}°F is equal to {celsius}°C")

else:
print("Invalid choice. Please enter 1 or 2")

RESULT
The program for temperature conversion is obtained.

6
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

PROG-3
Simple desktop calculator using Python. Only the five basic arithmetic
operators.

AIM

To implement a desktop calculator using python

PROGRAM

METHOD 1

print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Modulus")

choice = input("Enter choice (1/2/3/4/5): ")

if choice in ['1', '2', '3', '4', '5']:


num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

if choice == '1':
result = num1 + num2
print(f"{num1} + {num2} = {result}")
elif choice == '2':
result = num1 - num2
print(f"{num1} - {num2} = {result}")
elif choice == '3':
result = num1 * num2
print(f"{num1} * {num2} = {result}")
elif choice == '4':
if num2 != 0:
result = num1 / num2
print(f"{num1} / {num2} = {result}")
else:
print("Error! Division by zero.")
elif choice == '5':
result = num1 % num2
print(f"{num1} % {num2} = {result}")
else:

7
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

print("Invalid input. Please select a valid operation.")

METHOD 2
(Using match-case)

print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Modulus")

choice = input("Enter choice (1/2/3/4/5): ")

if choice in ['1', '2', '3', '4', '5']:


num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

match choice:
case '1':
result = num1 + num2
print(f"{num1} + {num2} = {result}")
case '2':
result = num1 - num2
print(f"{num1} - {num2} = {result}")
case '3':
result = num1 * num2
print(f"{num1} * {num2} = {result}")
case '4':
if num2 != 0:
result = num1 / num2
print(f"{num1} / {num2} = {result}")
else:
print("Error! Division by zero.")
case '5':
result = num1 % num2
print(f"{num1} % {num2} = {result}")
else:
print("Invalid input. Please select a valid operation.")

RESULT
Implemented a desktop calculator using python with 5 basic operations

8
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

PROG-4
Create, concatenate, and print a string and access a sub-string from a given
string.
AIM

To Create, concatenate, and print a string and access a sub-string from a given string.

PROGRAM

# Read a string from the user


user_string = input("Enter a string: ")
# Create another string
additional_string = " - This is an additional string."
# Concatenate the two strings
concatenated_string = user_string + additional_string
# Print the concatenated string
print("Concatenated String:", concatenated_string)
# Access and print a substring from the user's string
# Example: Let's extract the first 5 characters from the user's string
substring = user_string[:5]
print("Substring (first 5 characters):", substring)

RESULT
Various operations on string has been excecuted

9
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

PROG -5

Familiarize time and date in various formats.

AIM:
To Familiarize time and date in various formats

PROGRAM:

from datetime import datetime


# Get the current date and time
now = datetime.now()
# Format the date and time to match the required format
formatted_date = now.strftime("%a %b %d %H:%M:%S IST %Y")
# Print the formatted date
print(formatted_date)

RESULT:

The time and date in various formats were obtained.

10
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

PROG :6

Program to create, append, and remove elements in lists


AIM:

Write a program to create, append, and remove elements in lists ,using numpy also.

PROGRAM
# 1. Creating a List
my_list = [10, 20, 30, 40, 50]
print("Original List:", my_list)

# 2. Appending Elements to the List


# Appending a single element
my_list.append(60)
print("List after appending 60:", my_list)

# Appending multiple elements (using extend to


add multiple elements)
my_list.extend([70, 80, 90])
print("List after appending [70, 80, 90]:", my_list)

# 3. Removing Elements from the List


# Removing an element by value
my_list.remove(30) # Removes the first
occurrence of 30
print("List after removing the element 30:",
my_list)

# Removing an element by index (using pop)


removed_element = my_list.pop(0) # Removes the
element at index 0
print(f"List after removing the element at index 0
({removed_element}):", my_list)

# Removing multiple elements by slicing


11
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

del my_list[0:2] # Removes the first two elements


print("List after removing the first two elements:",
my_list)
#########################################
#####################
import numpy as np
# 1. Creating a NumPy array
# Create a NumPy array (which is similar to a list in
Python)
array = np.array([10, 20, 30, 40, 50])
print("Original Array:", array)

# 2. Appending Elements to the List


# NumPy doesn't have an append method like
Python lists, but we can use np.append
# Appending a single element
array = np.append(array, 60)
print("Array after appending 60:", array)

# Appending multiple elements


array = np.append(array, [70, 80, 90])
print("Array after appending [70, 80, 90]:", array)

# 3. Removing Elements from the List


# NumPy doesn't have a remove method like
Python lists, but we can use np.delete
# Removing an element by index
array = np.delete(array, 2) # Removes the element
at index 2 (30 in this case)
print("Array after removing the element at index
2:", array)

# Removing multiple elements by indices


array = np.delete(array, [0, 1]) # Removes elements
at index 0 and 1
print("Array after removing elements at indices 0
12
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

and 1:", array)

RESULT.

The program to create, append, and remove elements in lists has been
obtained.

13
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

PROG-7
Program to construct patterns of stars (*), using a nested for loop.
AIM
Write a Program to construct patterns of stars (*), using a nested for loop..
PROGRAM
1.Square Pattern:
*****
*****
*****
*****
*****

2.Right-Angled Triangle Pattern:


*
**
***
****
*****

3.Pyramid Pattern:
*
***
*****
*******
*********
# 1. Square Pattern
size = 5
print("Square Pattern:")
for i in range(size):

14
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

for j in range(size):
print('*', end=' ')
print()

print() # Add an empty line for separation

# 2. Right-Angled Triangle Pattern


print("Right-Angled Triangle Pattern:")
for i in range(1, size + 1):
for j in range(i):
print('*', end=' ')
print()

print() # Add an empty line for separation

# 3. Pyramid Pattern
print("Pyramid Pattern:")
for i in range(size):
# Print leading spaces
for j in range(size - i - 1):
print(' ', end=' ')
# Print stars
for k in range(2 * i + 1):
print('*', end=' ')
print()
RESULT
The various patterns have been obtained.

15
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

PROG-8
A program that prints prime numbers less than N.
AIM
Write a Program to that prints prime numbers less than N
PROGRAM
n = int(input("Enter a range: "))

print(f"Prime numbers less than {n}:")

# Iterate through all numbers from 2 to n-1


for num in range(2, n):
is_prime = True
# Check if num is divisible by any number from 2 to sqrt(num)
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
# Print num if it is prime
if is_prime:
print(num, end=' ')
RESULT
The primes numbers less than N is obtained

16
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

PROG-9
Program to find the factorial of a number using Recursion.
AIM
Program to find the factorial of a number using Recursion.
PROGRAM
# Recursive function to calculate factorial
def factorial(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
else:
# Recursive case: n * factorial of (n - 1)
return n * factorial(n - 1)

# Input the number


number = int(input("Enter a number: "))

# Calculate factorial
result = factorial(number)

# Print the result


print(f"The factorial of {number} is {result}")
RESULT
The factorial of a number is obtained using recursion.

17
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

PROG-10
Recursive function to add two positive numbers.
AIM
Recursive function to add two positive numbers.
PROGRAM
# Recursive function to add two positive numbers
def add_positive_numbers(a, b):
# Base case: if one of the numbers is zero
if b == 0:
return a
# Recursive case: increment a and decrement b
return add_positive_numbers(a + 1, b - 1)

# Input two positive numbers


num1 = int(input("Enter the first positive number: "))
num2 = int(input("Enter the second positive number: "))

# Ensure both numbers are positive


if num1 < 0 or num2 < 0:
print("Both numbers must be positive.")
else:
# Calculate the sum using recursion
result = add_positive_numbers(num1, num2)
# Print the result
print(f"The sum of {num1} and {num2} is {result}")
RESULT
Recursive function to add two positive numbers is obtained.

18
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

PROG-11
Recursive function to multiply two positive numbers..
AIM
Recursive function to multiply two positive numbers.
PROGRAM
# Recursive function to multiply two numbers
def multiply(a, b):
# Base case: if one of the numbers is zero
if b == 0:
return 0
# Recursive case: multiply by adding a to the result of multiplying a with (b - 1)
return a + multiply(a, b - 1)

# Input two numbers


num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

# Calculate the product using recursion


result = multiply(num1, num2)

# Print the result


print(f"The product of {num1} and {num2} is {result}")
RESULT
Recursive function to multiply two positive numbers is obtained

19
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

PROG-12
Recursive function to find the greatest common divisor of two positive
numbers.(Euclid's Algorithm)
AIM
Write a program using Recursive function to find the greatest common divisor of two positive
numbers.(Euclid's Algorithm)
PROGRAM
# Recursive function to find GCD using Euclid's algorithm
def gcd(a, b):
# Base case: if b is 0, gcd is a
if b == 0:
return a
# Recursive case: call gcd with b and a % b
return gcd(b, a % b)

# Input two numbers


num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

# Calculate the GCD using recursion


result = gcd(num1, num2)

# Print the result


print(f"The GCD of {num1} and {num2} is {result}")
RESULT
The Recursive function to find the greatest common divisor of two positive numbers.(Euclid's
Algorithm)is obtained.

20
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

PROG-13
A program to check whether a triangle is right angled or not.
AIM
A program that accepts the lengths of three sides of a triangle as inputs. The program should
output whether or not the triangle is a right triangle (Recall from the Pythagorean Theorem
that in a right triangle, the square of one side equals the sum of the squares of the other two
sides). Implement using functions.
PROGRAM
# Function to check if the given sides form a right triangle
def is_right_triangle(a, b, c):
# Sort the sides to ensure that c is the largest side
sides = sorted([a, b, c])
# Apply the Pythagorean Theorem
return sides[2] ** 2 == sides[0] ** 2 + sides[1] ** 2

# Input lengths of the three sides of the triangle


side1 = float(input("Enter the length of the first side: "))
side2 = float(input("Enter the length of the second side: "))
side3 = float(input("Enter the length of the third side: "))

# Check if the sides form a right triangle


if is_right_triangle(side1, side2, side3):
print("The triangle is a right triangle.")
else:
print("The triangle is not a right triangle.")
RESULT
The program to check whether a triangle is right angled or not is obtained.

21
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

PROG-14
Program to define a module to find Fibonacci Numbers and import the
module to another program.
AIM
Program to define a module to find Fibonacci Numbers and import the module to another
program.
PROGRAM
fib.py # module
# Function to return the nth Fibonacci number
def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
###############
import fib

# Input: Number of terms in the Fibonacci series


n= int(input("Enter the number of terms in the Fibonacci series: "))

# Print the Fibonacci series

for i in range(n):
print(fib.fibonacci(i), end=" ")
RESULT
The Program to define a module and import the module to another program is obtained.

22
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

PROG-15
Program to check whether the given number is a valid mobile number or
not using functions.
AIM
Program to check whether the given number is a valid mobile number or not using functions.
Rules:
1. Every number should contain exactly 10 digits.
2. The first digit should be 7 or 8 or 9
PROGRAM
# Function to check if the given number is a valid mobile number
def is_valid_mobile_number(number):
# Check if the number contains exactly 10 digits
if len(number) == 10 and number.isdigit():
# Check if the first digit is 7, 8, or 9
if number[0] in ['7', '8', '9']:
return True
return False

# Input: Mobile number as a string


mobile_number = input("Enter the mobile number: ")

# Check if the mobile number is valid


if is_valid_mobile_number(mobile_number):
print("The mobile number is valid.")
else:
print("The mobile number is not valid.")
RESULT
The program to check whether a given mobile number is valid or not is obtained.

23
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

PROG-16
Program to Merge and sort the Lists
AIM
Input two lists from the user. Merge these lists into a third list such that in the merged list, all
even numbers occur first followed by odd numbers. Both the even numbers and odd numbers
should be in sorted order.
PROGRAM
# Input: Two lists from the user
list1 = list(map(int, input("Enter the elements of the first list separated by spaces: ").split()))
list2 = list(map(int, input("Enter the elements of the second list separated by spaces:
").split()))

# Merge the two lists


merged_list = list1 + list2

# Sort the merged list with a custom key:


# - First, sort by whether the number is even (even numbers come first)
# - Then sort by the number itself for the even and odd parts
sorted_list = sorted(merged_list, key=lambda x: (x % 2, x))

# Print the resulting list


print("Merged and sorted list with even numbers first, followed by odd numbers:")
print(sorted_list)
RESULT
The program to merge and sort the list is obtained.

24
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

PROG-17
A program to play stick games.
AIM
Write a program to play a sticks game in which there are 16 sticks. Two players take turns to
play the game. Each player picks one set of sticks (needn’t be adjacent) during his turn. A set
contains 1, 2, or 3 sticks. The player who takes the last stick is the loser. The number of sticks
in the set is to be input.
PROGRAM
# Initial number of sticks
total_sticks = 16

# Game loop
while total_sticks > 0:
# Player 1's turn
print(f"There are {total_sticks} sticks left.")
player1_choice = int(input("Player 1, pick 1, 2, or 3 sticks: "))

# Validate player 1's choice


while player1_choice < 1 or player1_choice > 3 or player1_choice > total_sticks:
print("Invalid choice. You can only pick 1, 2, or 3 sticks.")
player1_choice = int(input("Player 1, pick 1, 2, or 3 sticks: "))

# Subtract the chosen number of sticks


total_sticks -= player1_choice

# Check if player 1 loses


if total_sticks == 0:
print("Player 1 has taken the last stick. Player 1 loses!")
break

# Player 2's turn


print(f"There are {total_sticks} sticks left.")
player2_choice = int(input("Player 2, pick 1, 2, or 3 sticks: "))

# Validate player 2's choice


while player2_choice < 1 or player2_choice > 3 or player2_choice > total_sticks:
print("Invalid choice. You can only pick 1, 2, or 3 sticks.")
player2_choice = int(input("Player 2, pick 1, 2, or 3 sticks: "))

# Subtract the chosen number of sticks

25
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

total_sticks -= player2_choice

# Check if player 2 loses


if total_sticks == 0:
print("Player 2 has taken the last stick. Player 2 loses!")
break
RESULT
The program to play stick games is obtained.

26
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

PROG-18
Monty Hall problem
AIM
Suppose you're on a game show, and you are given the choice of three doors: Behind one
door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows
what is behind the doors, opens another door, say No. 3, which has a goat. He then asks, "Do
you want to pick door No. 2?"Is it to your advantage to switch your choice?

PROGRAM
# Function to simulate the Monty Hall problem
def monty_hall_simulation(num_trials):
stay_wins = 0
switch_wins = 0

for _ in range(num_trials):
# Randomly place the car behind one of the three doors
doors = [0, 0, 0]
car_position = random.randint(0, 2)
doors[car_position] = 1

# Player makes an initial choice


player_choice = random.randint(0, 2)

# Host opens one of the remaining doors with a goat


remaining_doors = [i for i in range(3) if i != player_choice and doors[i] == 0]
door_opened_by_host = random.choice(remaining_doors)

# Determine the door the player can switch to


switch_choice = [i for i in range(3) if i != player_choice and i !=
door_opened_by_host][0]

# If the player stays with the initial choice


if doors[player_choice] == 1:
stay_wins += 1

# If the player switches to the other door


if doors[switch_choice] == 1:
switch_wins += 1

return stay_wins, switch_wins


27
GOVERNMENT MODEL ENGINEERING COLLEGE
UCEST 105-PYTHON LAB

# Number of trials to simulate


num_trials = 10000

# Simulate the Monty Hall problem


stay_wins, switch_wins = monty_hall_simulation(num_trials)

# Print the results


print(f"Out of {num_trials} trials:")
print(f"Staying with the initial choice won {stay_wins} times
({(stay_wins/num_trials)*100:.2f}%).")
print(f"Switching to the other door won {switch_wins} times
({(switch_wins/num_trials)*100:.2f}%).")
RESULT
The program for monty hall probelm is obtained.

28
GOVERNMENT MODEL ENGINEERING COLLEGE

You might also like