Python is a general purpose programming language that is often applied in scripting roles.So, Python is programming language as well as scripting language. Python is also called as Interpreted language.
Lets start with question no 1 python assignment.
1. Write a program to create a class, constructor and functions to accept and display the values.
#!/usr/bin/python3 class Atul: def __init__(self): self.x = input("Enter firstname ") self.y = input("Enter lastname ") def show(self): print("Your firstname is : " , self.x) print("Your lastname is : " , self.y) obj = Atul() obj.show()
2.
WAP using Dictionary to store userid and password and validate the user
based on userid and password.
┌──(hackerboy㉿KumarAtulJaiswal)-[~/Desktop/rnc-university-mca/mca-3rdsem-python] └─$ cat second.py #!/usr/bin/python3 from getpass import getpass import time a = input("Enter username ") b = getpass("Enter password ") #key = [1, 2, 3] #value = {"java", "android", "web development"} stored = dict.fromkeys({a},b) #print(stored) username = input("Enter username : ") if username in stored: password = input("Enter password : ") if stored[username] == password : print("Please wait a seond for checking userid and password...") time.sleep(2) print("Username and password match") else: print("user entered the wrong password") else: print("your username is not registered") ┌──(hackerboy㉿KumarAtulJaiswal)-[~/Desktop/rnc-university-mca/mca-3rdsem-python] └─$
3.
Write a program to create a user defined exception in python and handle the
exception using user defined class.
┌──(hackerboy㉿KumarAtulJaiswal)-[~/Desktop/rnc-university-mca/mca-3rdsem-python] └─$ cat third3.py class ValueError(Exception): pass try: age= 10 print("Age is:") print(age) if age<=0: raise ValueError yearOfBirth= 2021-age print("Year of Birth is:") print(yearOfBirth) except ValueError: print("Input Correct age.") ┌──(hackerboy㉿KumarAtulJaiswal)-[~/Desktop/rnc-university-mca/mca-3rdsem-python] └─$
4.
Write a program to start different executable files of system such as
calculator, notepad, msword etc.
┌──(hackerboy㉿KumarAtulJaiswal)-[~/Desktop/rnc-university-mca/mca-3rdsem-python] └─$ cat fourth2.py #!/usr/bin/python3 import os import subprocess def Exitapp(): exit() application = [] while(True): print("1 for notepad.exe ") print("2 for calc.exe ") print("3 for notepad.exe ") print("4 for cmd.exe ") print("5 for exit ") name = int(input("Enter your choice")) if(num == 1): os.system(application) elseif(num == 2): os.system(application) elseif(num == 3): os.system(application) elseif(num == 4): os.system(application) elseif(num == 5): Exitapp() ┌──(hackerboy㉿KumarAtulJaiswal)-[~/Desktop/rnc-university-mca/mca-3rdsem-python] └─$
5.
Write a menu-driven program to find the area of a circle, square and
rectangle in python.
┌──(hackerboy㉿KumarAtulJaiswal)-[~/Desktop/rnc-university-mca/mca-3rdsem-python] └─$ cat fifth.py #!/usr/bin/python3 import sys import os from colorama import Fore, Back, Style print("\n****************************************") print("Menu Driven Program") print(Fore.LIGHTWHITE_EX + "1 For Area of Circle") print(Fore.LIGHTGREEN_EX + "2 For Area of Square") print(Fore.LIGHTWHITE_EX + "3 For Area of Rectangle") print(Fore.LIGHTGREEN_EX + "4 For Quit") print("****************************************\n") num=int(input("Enter your choice:")) if num==1: radius=int(input("Enter radius of Circle:")) print("Area of Circle",3.14*radius*radius) elif num==2: length=int(input("Enter length of Rectangle:")) breadth=int(input("Enter breadth of Rectangle:")) print("Area of Rectangle:",length*breadth) elif num==3: side=int(input("Enter side of Square:")) print("Area:",side*side) elif num==4: sys.exit() #break else: print("Wrong Choice") repeat=input("Do you want to continue? (y/n)") if repeat=='n'or repeat=='N': sys.exit() #break else: os.system("python3 fifth.py") ┌──(hackerboy㉿KumarAtulJaiswal)-[~/Desktop/rnc-university-mca/mca-3rdsem-python] └─$
6.
Write a program to insert, update, delete and display the values using
dictionary in python.
┌──(hackerboy㉿KumarAtulJaiswal)-[~/Desktop/rnc-university-mca/mca-3rdsem-python] └─$ cat sixth.py #!/usr/bin/python3 import time a = input("Enter the key attribute : ") b = input("Enter the value of key attribute : ") dict = {} #for insert an element dict_append = ({a,b}) #key = [a, a, a] #print(dict_append, key) print(dict_append) print("Please wait a second") time.sleep(2) print("Now we will use update") #for update an element stored = dict.update({a:b}) dict['salary'] = 1000 print("Updated Dict is: ", dict) print(stored) #for delete an element sixMonths = {1:31, 2:28, 3:31, 4:30, 5:31, 6:"joker"} print(sixMonths.popitem()) print(sixMonths) ┌──(hackerboy㉿KumarAtulJaiswal)-[~/Desktop/rnc-university-mca/mca-3rdsem-python] └─$
7. Create a Digital clock using tkinter in python.
┌──(hackerboy㉿KumarAtulJaiswal)-[~/Desktop/rnc-university-mca/mca-3rdsem-python] └─$ cat seventh.py #!/usr/bin/python3 from tikinter import * import time win = Tk() win.title("Digital Clock") win.geometry("400 x 150") label = label(win.font="Arial", 60, "bold", bg="yellow", font="red", col=25) label.grid(row=0, column=1) def clock(): t1.time.strftime("%H:%M%S") label.config(text=t1) label.after(1000, clock) clock() win.mainloop() ┌──(hackerboy㉿KumarAtulJaiswal)-[~/Desktop/rnc-university-mca/mca-3rdsem-python] └─$
8.
Write a program to insert, delete and displaying elements in ascending and
descending order using List data type in python.
# List implementation to perform insert, delete and display operations in ascending and descending order # function to insert elements in the list def insert_elements(my_list, element): my_list.append(element) print("Element inserted successfully.") # function to delete elements from the list def delete_element(my_list, element): if element in my_list: my_list.remove(element) print("Element deleted successfully.") else: print("Element not found in the list.") # function to display elements in ascending order def display_ascending_order(my_list): my_list.sort() print("Elements in ascending order:") print(*my_list) # function to display elements in descending order def display_descending_order(my_list): my_list.sort(reverse=True) print("Elements in descending order:") print(*my_list) # main function def main(): my_list = [] while True: print("1. Insert elements") print("2. Delete elements") print("3. Display elements in ascending order") print("4. Display elements in descending order") print("5. Exit") choice = int(input("Enter your choice: ")) if choice == 1: element = int(input("Enter the element to be inserted: ")) insert_elements(my_list, element) elif choice == 2: element = int(input("Enter the element to be deleted: ")) delete_element(my_list, element) elif choice == 3: display_ascending_order(my_list) elif choice == 4: display_descending_order(my_list) elif choice == 5: break else: print("Invalid choice.") # driver code if __name__ == '__main__': main()
9.
Write a program to create a PhoneBook using Dictionary for adding,
updating, searching and deleting phone Numbers.
# PhoneBook using Dictionary # function to add a new contact to the phonebook def add_contact(phonebook, name, number): phonebook[name] = number print("Contact added successfully.") # function to update an existing contact in the phonebook def update_contact(phonebook, name, number): if name in phonebook: phonebook[name] = number print("Contact updated successfully.") else: print("Contact not found.") # function to search for a contact in the phonebook def search_contact(phonebook, name): if name in phonebook: print(name, ":", phonebook[name]) else: print("Contact not found.") # function to delete a contact from the phonebook def delete_contact(phonebook, name): if name in phonebook: del phonebook[name] print("Contact deleted successfully.") else: print("Contact not found.") # main function def main(): phonebook = {} while True: print("1. Add Contact") print("2. Update Contact") print("3. Search Contact") print("4. Delete Contact") print("5. Exit") choice = int(input("Enter your choice: ")) if choice == 1: name = input("Enter name: ") number = input("Enter phone number: ") add_contact(phonebook, name, number) elif choice == 2: name = input("Enter name: ") number = input("Enter phone number: ") update_contact(phonebook, name, number) elif choice == 3: name = input("Enter name: ") search_contact(phonebook, name) elif choice == 4: name = input("Enter name: ") delete_contact(phonebook, name) elif choice == 5: break else: print("Invalid choice.") # driver code if __name__ == '__main__': main()
10. WAP in python to store students details in csv file.
#!/usr/bin/python import csv header = ['sname', 'class', 'roll no', 'subject'] data = [['Atul', 'MCA', 67], ['Khushboo', 'MCA', 64], ['Priya', 'MCA', 64], ['Tinki', 'MCA', 14], ['Umesh', 'MCA', 66], ['Muskan', 'MCA', 8], ['Sweta', 'MCA', 9]] filename = 'student_data.csv' with open(filename, 'w') as file: for header in header: file.write(str(header) + ', ') file.write('\n') for row in data: for x in row: file.write(str(x) + ',') file.write('\n')
11. WAP in python to create a decorator and decorate a function.
┌──(hackerboy㉿KumarAtulJaiswal)-[~/Desktop/rnc-university-mca/mca-3rdsem-python] └─$ cat eleventh.py 1 ⚙ #!/usr/bin/python3 def decorator_function(func): def wrapper_function(*args, **kwargs): print("Wrapper function executed before {}".format(func.__name__)) result = func(*args, **kwargs) print("Wrapper function executed after {}".format(func.__name__)) return result return wrapper_function @decorator_function def display_info(name, age): print("Displaying information:") print("Name: {}".format(name)) print("Age: {}".format(age)) display_info("Atul", 30) ┌──(hackerboy㉿KumarAtulJaiswal)-[~/Desktop/rnc-university-mca/mca-3rdsem-python] └─$ 1 ⚙
12.
WAP in python to insert, update, display and delete data in mysql
database.
import mysql.connector # Connect to the database conn = mysql.connector.connect( host="hostname", user="username", password="password", database="database_name" ) # Create a cursor to execute SQL commands cursor = conn.cursor() # Insert data sql_insert = "INSERT INTO table_name (column1, column2) VALUES (%s, %s)" val = ("value1", "value2") cursor.execute(sql_insert, val) conn.commit() # Display data sql_select = "SELECT * FROM table_name" cursor.execute(sql_select) rows = cursor.fetchall() for row in rows: print(row) # Update data sql_update = "UPDATE table_name SET column1 = %s WHERE column2 = %s" val = ("new_value1", "value2") cursor.execute(sql_update, val) conn.commit() # Delete data sql_delete = "DELETE FROM table_name WHERE column2 = %s" val = ("value2",) cursor.execute(sql_delete, val) conn.commit() # Close the cursor and connection cursor.close() conn.close()
Disclaimer
All tutorials are for informational and educational purposes only and have been made using our own routers, servers, websites and other vulnerable free resources. we do not contain any illegal activity. We believe that ethical hacking, information security and cyber security should be familiar subjects to anyone using digital information and computers. Hacking Truth is against misuse of the information and we strongly suggest against it. Please regard the word hacking as ethical hacking or penetration testing every time this word is used. We do not promote, encourage, support or excite any illegal activity or hacking.