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

Python

The document contains Python programs and code snippets for a variety of tasks including: 1) Calculating the average of numbers in a list 2) Creating a GUI with labels and buttons 3) Handling exceptions in a function

Uploaded by

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

Python

The document contains Python programs and code snippets for a variety of tasks including: 1) Calculating the average of numbers in a list 2) Creating a GUI with labels and buttons 3) Handling exceptions in a function

Uploaded by

asavari
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

1 . Python Program to Calculate the Average of Numbers in a Given List.

2. Write a program based on GUI, window with a label and two buttons

import tkinter as tk

def button1_click():
label.config(text="Button 1 clicked")

def button2_click():
label.config(text="Button 2 clicked")

# Create the main window


root = tk.Tk()

# Set the window title


root.title("GUI Example")

# Create a label
label = tk.Label(root, text="Welcome to the GUI")

# Create two buttons


button1 = tk.Button(root, text="Button 1", command=button1_click)
button2 = tk.Button(root, text="Button 2", command=root.destroy)

# Pack the label and buttons into the window


label.pack()
button1.pack()
button2.pack()

# Start the main event loop


root.mainloop()

3. Write a program to Catch exception in a function.

4. Python Program to check if a Number is an Armstrong Number


num = int(input("Enter a number: "))
sum = 0
count = 0
temp = num
while temp > 0:
count += 1
temp //= 10
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** count
temp //= 10
if num == sum:
print(num, "is an Armstrong number")
else:
print(num, "is not an Armstrong number")
5. Python Program to check if a Substring is Present in a Given String.

6. Write a program to Creating a simple dialog.

7. Python Program to Create a Class Which Performs Basic Calculator Operations.

class calculator_implementation():
def __init__(self,in_1,in_2):
self.a=in_1
self.b=in_2
def add_vals(self):
return self.a+self.b
def multiply_vals(self):
return self.a*self.b
def divide_vals(self):
return self.a/self.b
def subtract_vals(self):
return self.a-self.b
input_1 = int(input("Enter the first number: "))
input_2 = int(input("Enter the second number: "))
print("The entered first and second numbers are : ")
print(input_1, input_2)
my_instance = calculator_implementation(input_1,input_2)
choice=1
while choice!=0:
print("0. Exit")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
choice=int(input("Enter your choice... "))
if choice==1:
print("The computed addition result is : ",my_instance.add_vals())
elif choice==2:
print("The computed subtraction result is : ",my_instance.subtract_vals())
elif choice==3:
print("The computed product result is : ",my_instance.multiply_vals())
elif choice==4:
print("The computed division result is : ",round(my_instance.divide_vals(),2))
elif choice==0:
print("Exit")
else:
print("Sorry, invalid choice!")
print()

8. Python Program to Map Two Lists into a Dictionary.

9. WAP to Handle multiple exceptions.

11. Python Program to Find the Factorial/fibonacci of a Number Using Recursion.

# Factorial of a number using recursion

def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)

num = 7

# check if the number is negative


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))

# Python program to display the Fibonacci sequence

def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))

nterms = 10

# check if the number of terms is valid


if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))

12. Python Program to Create a Class and Compute the Area and the Perimeter of the a.
Circle(with interfaces)

import math
class circle_compute():
def __init__(self,my_radius):
self.radius=my_radius
def area_calculate(self):
return math.pi*(self.radius**2)
def perimeter_calculate(self):
return 2*math.pi*self.radius
my_result = int(input("Enter the radius of circle..."))
my_instance = circle_compute(my_result)
print("The radius entered is :")
print(my_result)
print("The computed area of circle is ")
print(round(my_instance.area_calculate(),2))
print("The computed perimeter of circle is :")
print(round(my_instance.perimeter_calculate(),2))

13. Python Program to Concatenate Two Dictionaries into One

14. WAP to Creating Class and Object in Python

15. Python Program to Print an Inverted Star Pattern.

16. Python Program to Count the Number of Words/letters in a Text File.

17. . Python Program to Copy the Contents of One File into Another.

# In read mode, open the first file say samplefile1.txt.


samplefile1="C:\\Users\\sbhel\\OneDrive\\Desktop\\first year ENGG\\sem3\\
certificate\\sem4\\python\\eg.txt"
samplefile2="C:\\Users\\sbhel\\OneDrive\\Desktop\\first year ENGG\\sem3\\
certificate\\sem4\\python\\py.txt"
with open(samplefile1) as file1:
# In write mode, open the second file say samplefile2.txt.
with open(samplefile2, "w") as file2:
# Using for loop, go over the lines in the first file.
for iline in file1:
# Copy the ith line of the first file to the second file using the
write function.
file2.write(iline)

18. Python Program to Swap the First and Last Value of a List

19. Python Program to read a .CSV file and remove duplicate values

21. Python Program on Constructor.

22.. Python Program on Inheritance.

23. Python Program to Take in the Marks of 5 Subjects and Display the Grade.

24. Python Program to Count Number of Lowercase Characters in a String a. Python Program to
plot a histogram for any chosen data.

25. Python Program to Sum All the Items in a Dictionary


my_dict = {'a': 100, 'b': 200, 'c': 300}
total = sum(my_dict.values())
print("The sum of all items in the dictionary is:", total)

26. Python Program to plot a 4 subplots for any chosen data. (scatterplot)

27. Python program to create a class with two methods to demonstrate method overloading

28. Python program to read a file whether it exists if yes add some text to the file or create a file
and add some text.

import os

file_path = "example.txt"
text_to_add = "This is some sample text to add to the file."

if os.path.isfile(file_path):
with open(file_path, "a") as f:
f.write("\n" + text_to_add)
else:
with open(file_path, "w") as f:
f.write(text_to_add)

In this program, the variable file_path contains the name and path of the file you want
to create or modify, and text_to_add contains the text you want to add to the file.

First, the os.path.isfile function checks if the file exists. If it does, the program opens
the file in "append" mode using the open function with the "a" argument. This allows
the program to add text to the end of the file without overwriting any existing text.
The with statement ensures that the file is properly closed after writing.

If the file does not exist, the program opens a new file with the same name using the
open function with the "w" argument. This creates a new empty file. The program then
writes the text_to_add to the file using the write function.

Note that in the with statement, the open function returns a file object that is
automatically closed when the with block is exited. This is a safer and more efficient
way to handle file I/O in Python, as it ensures that the file is always closed even if an
error

29. Python Program to create a hello world flask application

30. Python program to create two threads where one thread will print odd numbers and other will
print even numbers,
Code:
import threading
def print_odd():
for i in range(1, 10, 2):
print(i)
def print_even():
for i in range(2, 10, 2):
print(i)
t1 = threading.Thread(target=print_odd)
t2 = threading.Thread(target=print_even)
t1.start()
t2.start()
t1.join()
t2.join()
print("Printing Complete!")

31. Python Program to demonstrate SciPy for linear algebra.

32. Python Program that Displays which Letters are Present in Both the Strings

String1=int(input(“string1”))

String2=int(input(“string2”))

Set1=set(string1)

Set2=set(string2)

Common=set1.intersection(set2)

If common==0:

Print(“No common”)

Else:

For I in common:
Print(char)

33. Python Program to Create a Class in which One Method Accepts a String from the User and
Another Prints it

# creating a class
class stringClass():
# use the constructor to initialize the class's values(here it is a string).
def __init__(self):
self.string = ""
# Creating two methods inside the class.
# getString: which scans the value of the given string
def getString(self):
# using input() function to scan the value of the string.
self.string = input("Enter some random string = ")
# putString: Which prints the value of the given string.
def putString(self):
# printing the string
print("The string =", self.string)
# Create an object to represent the class.
stringobj = stringClass()
# Call both methods with the object created above.
# calling getString method which scans the value of string
stringobj.getString()
# calling putString method which prints the value of the string
stringobj.putString()

35. Create an employee database and insert records using sqlite database connectivity

36. Demonstrate database connectivity and display records from a table of ur choice

37. Demonstrate to delete records from a student table using sqlite database connectivity

38. Create a database using sqlite and insert record

You might also like