0% found this document useful (0 votes)
3K views9 pages

Python Lab Programs for BCA301A

This document contains 13 Python programming exercises that demonstrate various concepts like: 1) Writing a program to check if a number is even or odd. 2) Generating the Fibonacci series up to a given number of terms. 3) Printing elements of a list that are less than 5. 4) Checking if two lists have any common members. 5) Implementing exception handling. 6) Converting Celsius to Fahrenheit using a GUI program with widgets.

Uploaded by

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

Python Lab Programs for BCA301A

This document contains 13 Python programming exercises that demonstrate various concepts like: 1) Writing a program to check if a number is even or odd. 2) Generating the Fibonacci series up to a given number of terms. 3) Printing elements of a list that are less than 5. 4) Checking if two lists have any common members. 5) Implementing exception handling. 6) Converting Celsius to Fahrenheit using a GUI program with widgets.

Uploaded by

Anuradha Patnala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
  • Introduction to Python Programming Lab: Introduces basic Python programming tasks focusing on odd/even number determination and Fibonacci sequence generation.
  • List Element Filter: Explains how to create a program that filters list elements based on a given condition.
  • Common Members in Lists: Describes a task for checking common elements in two lists using Python.
  • List Comprehension with Arrays: Explains using list comprehension to handle arrays in Python.
  • Clone or Copy a List: Covers the creation of a program that demonstrates cloning or copying a list in Python.
  • Sort Dictionary by Value: Instructions on writing a Python program to sort dictionaries by their values in ascending or descending order.
  • Sum of Values in Dictionary: Task involves summing all values in a dictionary using Python.
  • Character Type Count: Details a Python program that counts different types of characters in a string.
  • Read Text File: Describes a task to write a Python program that reads a complete text file.
  • Exception Handling: Covers the implementation of exception handling in Python applications.
  • Append Text to File: Guidelines for creating a Python program that appends text to an existing file.
  • Celsius to Fahrenheit Converter: Instructions to create a Python GUI application to convert Celsius to Fahrenheit.
  • Program Output: Displays the output of the Celsius to Fahrenheit converter program developed in the previous task.

Introduction to Python Programming Lab

1. Enter the number from the user and depending on whether the number is even or odd,
print out an appropriate message to the user.
Program:
n=int(input("enter a number "))
if(n % 2 ==0):
print("given number %d is even" %n)
else:
print("given number %d is odd" %n)

Output:

2. Write a program to generate the Fibonacci series.


Program:
nterms = int(input("How many terms? "))
n1, n2 = 0, 1
count = 0
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
Output:

3. Write a program that prints out all the elements of the given list that are less than 5.
Program:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
for i in a:
if i < 5:
print(i)

Output:

4. Write a program that takes two lists and returns true if they have at least one common
member
Program:
def test_includes_any(nums, lsts):
for x in lsts:
if x in nums:
return True
return False
print(test_includes_any([10, 20, 30, 40, 50, 60], [22, 42]))
print(test_includes_any([10, 20, 30, 40, 50, 60], [20, 80]))

Output:

5. Write a python program to clone or copy a list.


Program:
original_list = [10, 22, 44, 23, 4]
new_list = list(original_list)
print(original_list)
print(new_list)

Output:
6. Write a python program to demonstrate arrays with list comprehension.
Program:
import array
arr = array.array('i', [300,200,100])
arr.insert(2, 150)
print(arr)
List = []
for item in arr:
List.append(item)
print(List)

Output:

7. Write python program script to sort (ascending and descending) a dictionary by value.
Program:
marks={'carl':40,'alan':20,'bob':50,'danny':30}
l=list(marks.items())
l.sort()
print('Ascending order is',l)
l=list(marks.items())
l.sort(reverse=True) #sort in reverse order
print('Descending order is',l)
dict=dict(l)
print("Dictionary",dict)

Output:
8. Write a python program to sum all the items in a dictionary.
Program:
d={'A':100,'B':540,'C':239}
print("Total sum of values in the dictionary:")
print(sum(d.values()))

Output:

9. Write a python program with a function that accepts a string and returns number of
vowels, consonants and special symbols in it
Program:
def countCharacterType(str):
vowels = 0
consonant = 0
specialChar = 0
digit = 0
for i in range(0, len(str)):
ch = str[i]
if ( (ch >= 'a' and ch <= 'z') or
(ch >= 'A' and ch <= 'Z') ):
# To handle upper case letters
ch = ch.lower()
if (ch == 'a' or ch == 'e' or ch == 'i'
or ch == 'o' or ch == 'u'):
vowels += 1
else:
consonant += 1
elif (ch >= '0' and ch <= '9'):
digit += 1
else:
specialChar += 1
print("Vowels:", vowels)
print("Consonant:", consonant)
print("Digit:", digit)
print("Special Character:", specialChar)
# Driver function.
str = "Aditya school of computer science"
countCharacterType(str)

Output:

10. Write a python program to read an entire text file.


Program:
def file_read(fname):
txt = open(fname)
print(txt.read())
file_read('test.txt')

Output:
11. Write a python program to append text to a file and display the text.
Program:
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
# Writing to file
with open("myfile.txt", "w") as file1:
file1.write("Hello \n")
file1.writelines(L)
with open("myfile.txt", 'a') as file1:
file1.write("Today")
with open("myfile.txt", "r+") as file1:
print(file1.read())

Output:

12. Write a program to implement exception handling.


Program:
def fun(a):
if a < 4:
b = a/(a-3)
# throws NameError if a >= 4
print("Value of b = ", b)
try:
fun(3)
fun(5)
# multiple exceptions
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")

Output:

13. Write a GUI program that converts Celsius to fahrein heat temperature using widgets.
Program:
from tkinter import *
def convert_temperature():
temp = float(entry.get())
temp = 9/5 * temp+32
output_label.configure(text = ' Converted to Fahrenheit: {:.1f} ' .format(temp))
main_window = Tk()
main_window.title("Temperature Convertor")
message_label = Label(text= ' Enter a temperature in Celsius ' ,
font=( ' Verdana ' , 12))
output_label = Label(font=( ' Verdana ' , 12))
entry = Entry(font=( ' Verdana ' , 12), width=4)
calc_button = Button(text= ' Convert C to F ' , font=( ' Verdana ' , 12),
command=convert_temperature)
message_label.grid(row=0, column=0)
entry.grid(row=0, column=1)
calc_button.grid(row=0, column=2)
output_label.grid(row=1, column=0, columnspan=3)
mainloop()

Output:

You might also like