0% found this document useful (0 votes)
35 views22 pages

BPP Experiments 1 To 12

The document outlines a series of Python programming experiments, including installing an IDE, writing basic programs for displaying messages, calculating resistances, applying Ohm's law, and checking frequency types. It also covers control loops, patterns, multiplication tables, and palindrome checks. Each experiment includes sample code, expected outputs, and explanations of the concepts involved.

Uploaded by

parthgadekar2736
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views22 pages

BPP Experiments 1 To 12

The document outlines a series of Python programming experiments, including installing an IDE, writing basic programs for displaying messages, calculating resistances, applying Ohm's law, and checking frequency types. It also covers control loops, patterns, multiplication tables, and palindrome checks. Each experiment includes sample code, expected outputs, and explanations of the concepts involved.

Uploaded by

parthgadekar2736
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Subject – Basic Python Programming (BPP-313011)

Experiment Number : 01
a) Install and configure Python IDE.
b) Write Python program to display message on screen.

Program : b)

The print() function prints the specified message to the screen, or other standard output
device.

The message can be a string, or any other object, the object will be converted into a string
before written to the screen.

1) print("Hello", "how are you?")

Output :
Hello how are you?

2) a= "Electronics Department Welcomes you"


print(a)

Output :
Electronics Department Welcomes you

3) x = ("apple", "orange", "cherry")


print(x)
Output :
('apple', 'orange', 'cherry')
Experiment Number : 02

a) Write simple Python program to calculate equivalent registers connected in series and parallel.
Accept values of R1, R2 and R3 from the user.
Program :

R1= float(input("Enter Value of R1:"))


R2= float(input("Enter Value of R2:"))
R3= float(input("Enter Value of R3:"))

Rseries = R1+R2+R3
Rparallel = 1/(1/R1 + 1/R2 + 1/R3)

print("Equivalent Series Resistance is:",Rseries)


print("Equivalent Parallel Resistance is:",Rparallel)

Output :
Enter Value of R1:12.5
Enter Value of R2:13
Enter Value of R3:23
Equivalent Series Resistance is: 48.5
Equivalent Parallel Resistance is: 4.989986648865153

b) Write simple Python program to calculate value of voltage by applying Ohm’s law.
Accept value of Current(I) and Resistance(R) from the user.
Program :

I = float(input("Enter Value of Current:"))


R = float(input("Enter Value of Resistance:"))

V = I*R

print("Voltage=",V)
Output :
Enter Value of Current:12.6
Enter Value of Resistance:30
Voltage= 378.0
Experiment Number : 03
Write program to check whether entered frequency is radio frequency or audio frequency.

Solution :

Audio Frequencies (AF):


These typically range from about 20 Hz to 20 kHz.
Radio Frequencies (RF):
These start from around 3 kHz and go up to several GHz. For simplicity, RF is often considered
to start from 3 kHz and go up to 300 GHz, though in practice, specific bands within this range are
used for different applications.

Here's a simple Python program that checks if the entered frequency falls within the range of
audio frequencies or radio frequencies. For this example, we'll use the following ranges:

 Audio Frequency: 20 Hz to 20,000 Hz (20 kHz)


 Radio Frequency: Above 20 kHz

Program :
freq_input = input("Enter the frequency (in Hz): ")
frequency = float(freq_input)

if frequency <= 20000:

print("Enterd Frequency is Audio Frequency:",frequency)


else:
print("Enterd Frequency is Radio Frequency:",frequency)

Output :
Enter the frequency (in Hz): 23
Enterd Frequency is Audio Frequency: 23.0

Enter the frequency (in Hz): 21000


Enterd Frequency is Radio Frequency: 21000.0
Experiment Number : 04
a) Write program to display various radio frequency bands using if..elseif ladder.

Solution :

To display various radio frequency (RF) bands based on the input frequency, you can use an if...elif
ladder in Python. RF bands typically include:

 VLF (Very Low Frequency): 3 kHz to 30 kHz


 LF (Low Frequency): 30 kHz to 300 kHz
 MF (Medium Frequency): 300 kHz to 3 MHz
 HF (High Frequency): 3 MHz to 30 MHz
 VHF (Very High Frequency): 30 MHz to 300 MHz
 UHF (Ultra High Frequency): 300 MHz to 3 GHz
 SHF (Super High Frequency): 3 GHz to 30 GHz
 EHF (Extremely High Frequency): 30 GHz to 300 GHz

Program :
freq_input = input("Enter the frequency (in Hz): ")
frequency = float(freq_input)

if 3000 <= frequency < 30000:


print("Very Low Frequency (VLF)")

elif 30000 <= frequency < 300000:


print("Low Frequency (LF)")

elif 300000 <= frequency < 3000000:


print("Medium Frequency (MF)")

elif 3000000 <= frequency < 30000000:


print("High Frequency (HF)")

elif 30000000 <= frequency < 300000000:


print("Very High Frequency (VHF)")

elif 300000000 <= frequency < 3000000000:


print("Ultra High Frequency (UHF)")

elif 3000000000 <= frequency < 30000000000:


print("Super High Frequency (SHF)")

elif 30000000000 <= frequency <= 300000000000:


print("Extremely High Frequency (EHF)")

else:
print("Frequency out of defined RF bands range.")
Output :
Enter the frequency (in Hz): 70000000000
Extremely High Frequency (EHF)

Enter the frequency (in Hz): 20


Frequency out of defined RF bands range.
Experiment Number: 04
b) Write program to display resistor color code using switch statement.

Solution : Resistor Color Code Table


4b) Program:

# using color codes


def findResistance(a, b, c, d):

color_digit = {'black': '0', 'brown': '1', 'red': '2',


'orange': '3', 'yellow': '4', 'green' : '5', 'blue' : '6',
'violet' : '7', 'grey' : '8', 'white': '9'}

multiplier = {'black': '1', 'brown': '10', 'red': '100',


'orange': '1k', 'yellow': '10k', 'green' : '100k',
'blue' : '1M', 'violet' : '10M', 'grey' : '100M',
'white': '1G'}

tolerance = {'brown': '+/- 1 %', 'red' : '+/- 2 %', 'green': "+/- 0.5 %",
'blue': '+/- 0.25 %', 'violet' : '+/- 0.1 %', 'gold': '+/- 5 %',
'silver' : '+/- 10 %', 'none': '+/-20 %'}

x = color_digit.get(a)
y = color_digit.get(b)
z = multiplier.get(c)
a = tolerance.get(d)
print("Resistance = " + x + y + " x " + z + " ohms " + a)

# Driver Code
if __name__ == "__main__":
a = input("enter 1st color: ")
b = input("enter 2nd color: ")
c = input("enter 3rd color: ")
d = input("enter 4th color: ")

# Function Call
findResistance(a, b, c, d)

Output :
enter 1st color: orange
enter 2nd color: green
enter 3rd color: blue
enter 4th color: silver

Resistance = 35 x 1M ohms +/- 10 %


Experiment Number: 05
5a) Write a simple Python program to demonstrate use of control loops: i) while

Solution:- i) Using while

1) Program : Write a Program for counter to count 0 to 3

count=0
while count <= 3:
print("count=",count)
count=count+1

Output
count= 0
count= 1
count= 2
count= 3

2) Program : Write a Program to print Hello All 5 times

i=0
while i<=5:
print("Hello All")
i=i+1

Output
Hello All
Hello All
Hello All
Hello All
Hello All

3) Program : Write a Program to find sum of 1 to num numbers

print("Enter a Value:")
num = int(input())
sum=0
i=1
while i<=num:
sum = sum + i
i=i+1
print("sum is:",sum)

Output
Enter a Value:
5
sum is: 15
5a) Write a simple Python program to demonstrate use of control loops: ii) do while

Solution:- ii) Using do while

In Python, there is no construct defined for do while loop. Python loops only include for loop and while
loop but we can modify the while loop to work as do while as in any other languages such as C++ and Java.

Do/While Loop in C
The do/while loop is a variant of the while loop. This loop will execute the code block once, before
checking if the condition is true, then it will repeat the loop as long as the condition is true.

Syntax
do {
// code block to be executed
}
while (condition);

The example below uses a do/while loop. The loop will always be executed at least once, even if the
condition is false, because the code block is executed before the condition is tested:

int i = 0;
do {
printf("%d\n", i);
i++;
}
while (i < 5);

In Python, we can simulate the behavior of a do-while loop using a while loop with a condition that is
initially True and then break out of the loop when the desired condition is met.
Program :
# Simple do-while loop simulation in Python
number = int(input("Enter a Number:")) # Initialize a variable
while True: # Use a while loop to simulate do-while
print("The current number is:”,number) # Execute the loop body
number += 1 # Increment the number
if number >= 5: # Check the condition
break # Exit the loop if the condition is met
Output

(i) Enter a Number:0


The current number is: 0
The current number is: 1
The current number is: 2
The current number is: 3
The current number is: 4

(ii) Enter a Number:2


The current number is: 2
The current number is: 3
The current number is: 4

(iii) Enter a Number:5


The current number is: 5
5b) Create a simple program, to demonstrate use of: for loop in Python
(e.g.: various pattern building, printing multiplication table, checking palindrome number etc.)
Solution:-

Simple Python programs that demonstrate how to use a for loop to build different patterns.

(i) Right-angled triangle pattern

Program :
n = int(input("Enter a Number:")) # Number of rows

for i in range(1, n + 1): # The variable i represents the current row number.

print('*' * i) # The expression '*' * i creates a string of i stars.


# For example, if i is 3, it evaluates to ***.
Output
Enter a Number:5
*
**
***
****
*****

(ii) Inverted triangle pattern

Program :
n = int(input("Enter a Number:")) # Number of rows

for i in range(n, 0, -1): # range(n,0,-1) generates a sequence starting from n down to 1

print('*' * i)

Output
Enter a Number:5
*****
****
***
**
*
(iii) Pyramid pattern

Program :
n = int(input("Enter a Number:")) # Number of rows

for i in range(n): # The for loop iterates over a range of n, his means i will take the values 0 to n-1
print(' ' * (n - i - 1), end='') # Print spaces
print('*' * (2 * i + 1)) # Print stars

Explanation: # Print spaces


print(' ' * (n - i - 1), end='')

 This line prints spaces before the stars to align them properly in a pyramid shape.
 The expression (n - i - 1) calculates the number of spaces needed for the current row:

 For i = 0 (first row): n - 0 - 1→5 - 0 - 1 → 4 spaces.


 For i = 1 (second row): n - 1 - 1→5 - 1 - 1 → 3 spaces.
 For i = 2 (third row): n - 2 - 1→5 - 2 - 1 → 2 spaces.
 For i = 3 (fourth row): n - 3 - 1→5 - 3 - 1 → 1 space.
 For i = 4 (fifth row): n - 4 - 1→5 - 4 - 1 → 0 spaces.

 The end='' parameter prevents a newline after printing spaces, allowing the stars to be printed on the same
line.
Explanation: # Print stars
print('*' * (2 * i + 1))

 This line prints the stars for the current row.


 The expression (2 * i + 1) determines how many stars to print:

 For i = 0: 2 * 0 + 1 → 1 star.
 For i = 1: 2 * 1 + 1 → 3 stars.
 For i = 2: 2 * 2 + 1 → 5 stars.
 For i = 3: 2 * 3 + 1 → 7 stars.
 For i = 4: 2 * 4 + 1 → 9 stars.

Output

Enter a Number: 5
*
***
*****
*******
*********
(iv) Multiplication Table

Program :
# Function to print multiplication table
def print_multiplication_table(number, up_to=10):
print("Multiplication Table for number:", number)
for i in range(1, up_to + 1):
result = number * i
print(number, "x", i, "=" , result)

# Input from the user


number = int(input("Enter a number to print its multiplication table: "))
print_multiplication_table(number)

Explaination: def print_multiplication_table(number, up_to=10):

 This line defines a function named print_multiplication_table.


 It takes two parameters:

 number: the number for which the multiplication table will be printed.
 up_to: optional parameter that defaults to 10. It specifies how far the multiplication table should go
(i.e., from 1 to up_to).

Output

Enter a number to print its multiplication table: 5


Multiplication Table for number: 5
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
(V) checking palindrome number

Palindrome comes from Greek palindromos, meaning "running back again,"


The word “dad” and the number “1881” are palindromes.

Program :
def is_palindrome(number): # Function to check if a number is a palindrome

str_num = str(number) # Convert the number to string

return str_num == str_num[::-1] # Check if the string is equal to its reverse

num = int(input("Enter a number to check if it is a palindrome: ")) # Input from the user

if is_palindrome(num): # Check and display the result

print(num, “is a palindrome.")

else:

print(num, “is not a palindrome.")

Output

Enter a number to check if it is a palindrome: 121


121 is a palindrome.

Enter a number to check if it is a palindrome: 122


122 is not a palindrome.
Experiment Number: 06
Write Python program to perform following operations on List:
a) Create b) Access c) Update d) Delete elements from list.

Solution:-
Program :

# a) Create a list
my_list = [10, 20, 30, 40, 50]
print("Initial List:", my_list)

# b) Access elements from the list


print("Accessing elements:")
print("First element:", my_list[0]) # Accessing the first element
print("Second element:", my_list[1]) # Accessing the second element
print("Last element:", my_list[-1]) # Accessing the last element

# c) Update an element in the list


print("\nUpdating the third element (30) to 35...")
my_list[2] = 35 # Updating the third element
print("Updated List:", my_list)

# d) Delete elements from the list


print("\nDeleting the first element (10)...")
del my_list[0] # Deleting the first element
print("List after deletion:", my_list)

print("\nDeleting the last element...")


my_list.pop() # Deleting the last element
print("List after deletion:", my_list)

print("\nDeleting the element 40...")


my_list.remove(40) # Deleting the element with value 40
print("List after deletion:", my_list)

Output
Initial List: [10, 20, 30, 40, 50]
Accessing elements:
First element: 10
Second element: 20
Last element: 50

Updating the third element (30) to 35...


Updated List: [10, 20, 35, 40, 50]

Deleting the first element (10)...


List after deletion: [20, 35, 40, 50]

Deleting the last element...


List after deletion: [20, 35, 40]

Deleting the element 40...


List after deletion: [20, 35]
Experiment Number: 07
Develop Python program to perform following operations on Tuples:
a) Create b) Access c) Update d) Delete Tuple elements

Solution:-
Program :

# a) Create a tuple
my_tuple = (10, 20, 30, 40, 50)
print("Initial Tuple:", my_tuple)

# b) Access elements from the tuple


print("\nAccessing elements:")
print("First element:", my_tuple[0]) # Accessing the first element
print("Second element:", my_tuple[1]) # Accessing the second element
print("Last element:", my_tuple[-1]) # Accessing the last element

# c) Update (Create a new tuple based on an existing one)


print("\nUpdating the third element (30) to 35...")
# Creating a new tuple with the updated value
updated_tuple = my_tuple[:2] + (35,) + my_tuple[3:]
print("Updated Tuple:", updated_tuple)

# d) Delete (Create a new tuple without specific elements)


print("\nDeleting the element 10...")
# Creating a new tuple without the first element
deleted_tuple = my_tuple[1:] # Removes the first element
print("Tuple after deletion:", deleted_tuple)

print("\nDeleting the element 50...")


# Creating a new tuple without the last element
deleted_tuple_50 = my_tuple[:-1] # Removes the last element
print("Tuple after deletion:", deleted_tuple_50)

Output
Initial Tuple: (10, 20, 30, 40, 50)

Accessing elements:
First element: 10
Second element: 20
Last element: 50

Updating the third element (30) to 35...


Updated Tuple: (10, 20, 35, 40, 50)

Deleting the element 10...


Tuple after deletion: (20, 30, 40, 50)

Deleting the element 50...


Tuple after deletion: (10, 20, 30, 40)
Experiment Number: 08
Write Python program to perform following operations on Set:
a) Create b) Access c) Update d) Delete Access Set elements

Solution:- Program :
# a) Create a set
my_set = {10, 20, 30, 40, 50}
print("Initial Set:", my_set)

# b) Access elements from the set


print("\nAccessing elements:")
# Sets do not support indexing, so we can only check for membership or convert to a list to access elements
if 30 in my_set:
print("30 is present in the set.")
else:
print("30 is not present in the set.")

# Accessing all elements


print("All elements in the set:")
for element in my_set:
print(element)

# c) Update the set


print("\nUpdating the set...")
# Adding an element
my_set.add(60)
print("Set after adding 60:", my_set)

# Updating by removing an element and adding a new one


my_set.discard(20) # Discarding an element (does not raise an error if not found)
my_set.add(25) # Adding a new element
print("Set after updating (removing 20 and adding 25):", my_set)

# d) Delete elements from the set


print("\nDeleting elements from the set...")
my_set.remove(10) # Removing an element (will raise an error if not found)
print("Set after deleting 10:", my_set)

# Safely remove an element (without raising an error if not found)


my_set.discard(40)
print("Set after deleting 40 using discard:", my_set)

Output
Initial Set: {50, 20, 40, 10, 30}

Accessing elements:
30 is present in the set.
All elements in the set:
50
20
40
10
30
Updating the set...
Set after adding 60: {50, 20, 40, 10, 60, 30}
Set after updating (removing 20 and adding 25): {50, 40, 25, 10, 60, 30}

Deleting elements from the set...


Set after deleting 10: {50, 40, 25, 60, 30}
Set after deleting 40 using discard: {50, 25, 60, 30}
Experiment Number: 09
Create a program to perform following operations on Dictionaries in Python:
a) Create b) Access c) Update d) Delete e) Looping through Dictionary

Solution:-
Program :

# a) Create a dictionary
my_dict = {
'name': 'Alice',
'age': 30,
'city': 'New York'
}

print("Created Dictionary:", my_dict)

# b) Access a value by key


key_to_access = 'name'
accessed_value = my_dict.get(key_to_access, 'Key not found')
print("Accessed Value (key: 'key_to_access'): accessed_value")

# c) Update a value
key_to_update = 'age'
new_value = 31
my_dict[key_to_update] = new_value
print("Updated Dictionary:", my_dict)

# d) Delete a key
key_to_delete = 'city'
if key_to_delete in my_dict:
del my_dict[key_to_delete]
print("Dictionary after deletion of key:", key_to_delete, "->", my_dict)
else:
print("Key 'key_to_delete' not found for deletion.")

# e) Looping through the dictionary


print("Looping through Dictionary:")
for key, value in my_dict.items():
print(key,value)

Output

Created Dictionary: {'name': 'Alice', 'age': 30, 'city': 'New York'}


Accessed Value (key: 'key_to_access'): accessed_value
Updated Dictionary: {'name': 'Alice', 'age': 31, 'city': 'New York'}
Dictionary after deletion of key: city -> {'name': 'Alice', 'age': 31}
Looping through Dictionary:
name Alice
age 31
Experiment Number: 10
a) Create python program to demonstrate use of math built-in function.
b) Create python program to demonstrate use of string built-in function.

Solution:-
Program :
a) Create python program to demonstrate use of math built-in function.

import math

def demonstrate_math_functions():
# Example values
number = 16
angle_degrees = 45
angle_radians = math.radians(angle_degrees) # Convert degrees to radians

# Calculate square root


sqrt_value = math.sqrt(number)
print("The square root of", number, "is",sqrt_value)

# Calculate factorial
factorial_value = math.factorial(5) # Factorial of 5
print("The factorial of 5 is",factorial_value)

# Calculate sine and cosine


sine_value = math.sin(angle_radians)
cosine_value = math.cos(angle_radians)
print("The sine of",angle_degrees, "degrees", "is",sine_value)
print("The cosine of",angle_degrees, "degrees", "is", cosine_value)

# Calculate exponential
exponent_value = math.exp(2) # e^2
print("The value of e^2 is", exponent_value)

# Calculate natural logarithm


log_value = math.log(10) # Natural log of 10
print("The natural logarithm of 10 is", log_value)

if __name__ == "__main__":
demonstrate_math_functions()

Output

The square root of 16 is 4.0


The factorial of 5 is 120
The sine of 45 degrees is 0.7071067811865476
The cosine of 45 degrees is 0.7071067811865476
The value of e^2 is 7.38905609893065
The natural logarithm of 10 is 2.302585092994046
Solution:-
Program :
b) Create python program to demonstrate use of string built-in function

def demonstrate_string_functions():
# Example string
original_string = " Hello, World! This is a Python string demonstration. "

# 1. Strip whitespace
stripped_string = original_string.strip()
print("Stripped string:",stripped_string)

# 2. Convert to uppercase
upper_string = stripped_string.upper()
print("Uppercase string:", upper_string)

# 3. Convert to lowercase
lower_string = stripped_string.lower()
print("Lowercase string:",lower_string)

# 4. Replace substring
replaced_string = stripped_string.replace("Python", "awesome")
print("Replaced string:",replaced_string)

# 5. Split the string into words


words = stripped_string.split()
print("List of words:",words)

# 6. Join the words back into a string


joined_string = ' '.join(words)
print("Joined string:",joined_string)

# 7. Find a substring
position = stripped_string.find("World")
print("Position of 'World':",position)

# 8. Check if the string starts with a specific substring


starts_with_hello = stripped_string.startswith("Hello")
print("Starts with 'Hello':", starts_with_hello)

# 9. Check if the string ends with a specific substring


ends_with_demo = stripped_string.endswith("demonstration.")
print("Ends with 'demonstration.':", ends_with_demo)

if __name__ == "__main__":
demonstrate_string_functions()
Output
Stripped string: Hello, World! This is a Python string demonstration.
Uppercase string: HELLO, WORLD! THIS IS A PYTHON STRING DEMONSTRATION.
Lowercase string: hello, world! this is a python string demonstration.
Replaced string: Hello, World! This is a awesome string demonstration.
List of words: ['Hello,', 'World!', 'This', 'is', 'a', 'Python', 'string', 'demonstration.']
Joined string: Hello, World! This is a Python string demonstration.
Position of 'World': 7
Starts with 'Hello': True
Ends with 'demonstration.': True
Experiment Number: 11
Write python programs to define function with arguments.
a) Calculate factorial of a number
b) Swapping of two variables

Solution:-
Program : a) Calculate factorial of a number

def get_factorial(num):
f=1
i=1
while i<= num:
f=f*i
i=i+1
return f

f1=get_factorial(5)
print("factoril of 5 is:",f1)

f2=get_factorial(7)
print("factoril of 7 is:",f2)

Output

factorial of 5 is: 120


factorial of 7 is: 5040

Solution:-
Program : b) Swapping of two variables

def swap_variables(a, b):


"""Swap two variables and return them."""
return b, a

def main():
# Get user input
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Swap the variables


swapped_num1, swapped_num2 = swap_variables(num1, num2)

# Display the results


print("After swapping: First number =", swapped_num1, "Second number =",swapped_num2)

if __name__ == "__main__":
main()
Output
Enter the first number: 32.5
Enter the second number: 56
After swapping: First number = 56.0 Second number = 32.5
Experiment Number: 12
Write programs to define function with default arguments.

Solution:-
Program :

def calculate_area(length=5, width=3):


"""Calculate the area of a rectangle with default length and width."""
area = length * width
return area

def main():
# Get user input for length and width

user_length = input("Enter the length of the rectangle (or press Enter to use default 5):")
user_width = input("Enter the width of the rectangle (or press Enter to use default 3):")

# Use default values if input is empty


length = float(user_length) if user_length else 5
width = float(user_width) if user_width else 3

# Calculate area
area = calculate_area(length, width)
print("The area of the rectangle is:",area)

if __name__ == "__main__":
main()

Output-1

Enter the length of the rectangle (or press Enter to use default 5):
Enter the width of the rectangle (or press Enter to use default 3):
The area of the rectangle is: 15

Output-2

Enter the length of the rectangle (or press Enter to use default 5):4.2
Enter the width of the rectangle (or press Enter to use default 3):6
The area of the rectangle is: 25.200000000000003

You might also like