Advertisement
fsoc131y

phinal

Apr 4th, 2024
831
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.96 KB | Source Code | 0 0
  1. 1. String Functions:
  2. def Concatenation():
  3.     str1 = "Hello"
  4.     str2 = "World"
  5.     result_plus = str1 + " " + str2
  6.     print("Concatenation Example of Hello + World")
  7.     print(result_plus)
  8.     print("\n")
  9.  
  10. def Reverse():
  11.     print("Reverse Example")
  12.     my_str = "Hello!"
  13.     reversed_str = ""
  14.     for char in my_str:
  15.         reversed_str = char + reversed_str
  16.     print(reversed_str)
  17.     print("\n")
  18.  
  19. def Replication():
  20.     print("Replication Example")
  21.     my_str = "Py"
  22.     replicated_str = ""
  23.     for _ in range(5):
  24.         replicated_str += my_str
  25.     print(replicated_str)
  26.     print("\n")
  27.  
  28. def Slicing():
  29.     print("Slicing Example")
  30.     my_str = "Hello, World!"
  31.     substring = my_str[7:12]
  32.     print(substring)
  33.     print("\n")
  34.  
  35. def Equals():
  36.     print("Equals Example")
  37.     str1 = "Hello"
  38.     str2 = "Hello"
  39.     if str1 != str2:
  40.         print("The strings are not equal")
  41.         print("\n")
  42.     else:
  43.         print("The strings are equal")
  44.         print("\n")
  45.  
  46. def iterate_string():
  47.     print("Iteration Example")
  48.     my_string = "Hello, world!"
  49.     for char in my_string:
  50.         print(char)
  51.     print("\n")
  52.  
  53. def substring():
  54.     print("Substring Example")
  55.     my_string = "Hello, World!"
  56.     substring = ""
  57.     for i in range(6, 10):
  58.         substring += my_string[i]
  59.     print(substring)
  60.  
  61. Concatenation()
  62. Reverse()
  63. Replication()
  64. Slicing()
  65. Equals()
  66. iterate_string()
  67. substring()
  68. print("\nAll actions performed successfully!")
  69.  
  70.  
  71. 2. Regex:
  72. import re
  73.  
  74. print("Matching a pattern")
  75. pattern = r"apple"
  76. text = "I like apples and oranges."
  77.  
  78. print("Using re.search() to find the first occurrence of the pattern")
  79. match = re.search(pattern, text)
  80. if match:
  81.     print(f"Pattern '{pattern}' found at index {match.start()} in the text.")
  82. else:
  83.     print(f"Pattern '{pattern}' not found in the text.")
  84.  
  85. print("\nExtracting matches using groups")
  86. pattern_with_groups = r"(\w+) (\w+)"
  87. name_text = "John Doe, Jane Smith"
  88.  
  89. print("Using re.findall() to find all occurrences of the pattern with groups")
  90. matches = re.findall(pattern_with_groups, name_text)
  91. for match in matches:
  92.     first_name, last_name = match
  93.     print(f"First Name: {first_name}, Last Name: {last_name}")
  94.  
  95. print("\nReplacing matches")
  96. pattern_to_replace = r"apple|orange"
  97. replacement_text = "fruit"
  98.  
  99. print("Using re.sub() to replace all occurrences of the pattern")
  100. updated_text = re.sub(pattern_to_replace, replacement_text, text)
  101. print(f"Original Text: {text}")
  102. print(f"Updated Text: {updated_text}")
  103.  
  104. 3. Regex Tkinter:
  105. import tkinter as tk
  106. import re
  107.  
  108. def validate_phone_number():
  109.     phone = phone_entry.get()
  110.     phone_pattern = r"^\d{10}$"
  111.     if re.match(phone_pattern, phone):
  112.         result_label.config(text="Valid Phone Number", fg="green")
  113.     else:
  114.         result_label.config(text="Invalid Phone Number", fg="red")
  115.  
  116. root = tk.Tk()
  117. root.title("Phone Number Validation Form")
  118.  
  119. tk.Label(root, text="Phone Number:").grid(row=0, column=0, sticky="w", padx=10, pady=5)
  120. phone_entry = tk.Entry(root)
  121. phone_entry.grid(row=0, column=1, padx=10, pady=5)
  122.  
  123. validate_button = tk.Button(root, text="Validate", command=validate_phone_number)
  124. validate_button.grid(row=1, column=0, columnspan=2, pady=10)
  125.  
  126. result_label = tk.Label(root, text="", fg="black")
  127. result_label.grid(row=2, column=0, columnspan=2, pady=5)
  128.  
  129. root.mainloop()
  130.  
  131. 4. Tkinter Calculator
  132. import tkinter as tk
  133.  
  134. def on_button_click(value):
  135.     current = entry.get()
  136.     entry.delete(0, tk.END)
  137.     entry.insert(tk.END, current + value)
  138.  
  139. def clear_entry():
  140.     entry.delete(0, tk.END)
  141.  
  142. def calculate_result():
  143.     try:
  144.         result = eval(entry.get())
  145.         entry.delete(0, tk.END)
  146.         entry.insert(tk.END, str(result))
  147.     except Exception as e:
  148.         entry.delete(0, tk.END)
  149.         entry.insert(tk.END, "Error")
  150.  
  151. root = tk.Tk()
  152. root.title("Simple Calculator")
  153.  
  154. entry = tk.Entry(root, width=20, font=('Arial', 16), borderwidth=5)
  155. entry.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
  156.  
  157. buttons = [
  158.     '7', '8', '9', '/',
  159.     '4', '5', '6', '*',
  160.     '1', '2', '3', '-',
  161.     '0', '.', '=', '+'
  162. ]
  163.  
  164. row_val = 1
  165. col_val = 0
  166. for button in buttons:
  167.     tk.Button(root, text=button, padx=20, pady=20, font=('Arial', 14),
  168.               command=lambda b=button: on_button_click(b) if b != '=' else calculate_result()).grid(row=row_val, column=col_val)
  169.     col_val += 1
  170.     if col_val > 3:
  171.         col_val = 0
  172.         row_val += 1
  173.  
  174. tk.Button(root, text='C', padx=20, pady=20, font=('Arial', 14), command=clear_entry).grid(row=row_val, column=col_val, columnspan=2)
  175.  
  176. root.mainloop()
  177.  
  178. 5. RW Ops with File
  179. import urllib.request
  180. import os
  181.  
  182. file_name = "E:\Study\Python\exps\CountryWiseAirport.csv"
  183.  
  184. with open(file_name, 'rb') as f:
  185.     binary_data = f.read()
  186.  
  187. binary_file_name = "airport.bin"
  188. with open(binary_file_name, 'wb') as f:
  189.     f.write(binary_data)
  190.  
  191. text_file_name = "airport.txt"
  192. with open(text_file_name, 'w') as f:
  193.     f.write(binary_data.decode('utf-8'))
  194.  
  195. def print_file_content(file_path):
  196.     with open(file_path, 'rb') as f:
  197.         content = f.read().decode('utf-8')
  198.         print(content)
  199.  
  200. print("Initial Binary File Content:")
  201. print_file_content(binary_file_name)
  202. print("\nInitial Text File Content:")
  203. print_file_content(text_file_name)
  204.  
  205. with open(binary_file_name, 'ab') as f:
  206.     f.write(b"\nThis is an appended line for binary file.")
  207.     print("\nThe binary file has been appended.")
  208.  
  209. with open(text_file_name, 'a') as f:
  210.     f.write("\nThis is an appended line for text file.")
  211.     print("\nThe text file has been appended.")
  212.  
  213. print("\nBinary File Content after Append:")
  214. print_file_content(binary_file_name)
  215. print("\nText File Content after Append:")
  216. print_file_content(text_file_name)
  217.  
  218. new_binary_data = b"This is new binary data."
  219. with open(binary_file_name, 'wb') as f:
  220.     f.write(new_binary_data)
  221.     print("\nThe file has been written.")
  222.  
  223. new_text_data = "This is new text data."
  224. with open(text_file_name, 'w') as f:
  225.     f.write(new_text_data)
  226.     print("\nThe file has been written.")
  227.  
  228. print("\nBinary File Content after Write:")
  229. print_file_content(binary_file_name)
  230. print("\nText File Content after Write:")
  231. print_file_content(text_file_name)
  232.  
  233. 6. Collect data to CSV:
  234. import csv
  235.  
  236. def collect_marks():
  237.     marks_data = []
  238.     for i in range(3):
  239.         student_name = input(f"\nEnter name for student {i+1}: ")
  240.         marks = [student_name]
  241.         for j in range(3):
  242.             subject = input(f"Enter marks for subject {j+1}: ")
  243.             marks.append(subject)
  244.         marks_data.append(marks)
  245.     return marks_data
  246.  
  247. def write_to_csv(data):
  248.     file = open('student_marks1.csv', 'w', newline='')
  249.     writer = csv.writer(file)
  250.     writer.writerow(["Student Name"] + [f"Subject {i}" for i in range(1, 6)])
  251.     for marks in data:
  252.         writer.writerow(marks)
  253.     file.close()
  254.  
  255. def read_from_csv():
  256.     file = open('student_marks1.csv', newline='')
  257.     reader = csv.reader(file)
  258.     for row in reader:
  259.         print(row)
  260.     file.close()
  261.  
  262. marks_data = collect_marks()
  263.  
  264. write_to_csv(marks_data)
  265.  
  266. read_from_csv()
  267.  
  268. 7. CRUD Ops:
  269. import mysql.connector
  270. import csv
  271.  
  272. mydb = mysql.connector.connect(
  273.     host='localhost',
  274.     user='root',
  275.     password='rootpw',
  276.     database='student'
  277. )
  278. cur = mydb.cursor()
  279. cur.execute('''create table if not exists student_mark(
  280.        name VARCHAR(25),
  281.        subject1 int,
  282.        subject2 int,
  283.        subject3 int,
  284.        subject4 int,
  285.        subject5 int)'''
  286.             )
  287.  
  288.  
  289. def im_csv_to_my(file_path):
  290.     with open(file_path, newline='') as csvf:
  291.         reader = csv.reader(csvf)
  292.         next(reader)
  293.         for row in reader:
  294.             name, subject1, subject2, subject3, subject4, subject5 = row
  295.             cur.execute('''
  296.                        insert into student_mark(name, subject1, subject2, subject3, subject4, subject5)
  297.                        values(%s,%s,%s,%s,%s,%s)
  298.                        ''', (name, int(subject1), int(subject2), int(subject3), int(subject4), int(subject5))
  299.                         )
  300.     mydb.commit()
  301.  
  302. im_csv_to_my('E:\\Study\\Python\\exps\\student_marks.csv')
  303. cur.execute('select * from student_mark')
  304. rows = cur.fetchall()
  305. for row in rows:
  306.     print(row)
  307.  
  308.  
  309. def update_marks(name, subject1, subject2, subject3, subject4, subject5):
  310.     cur.execute('''
  311.                update student_mark set subject1=%s, subject2=%s, subject3=%s, subject4=%s, subject5=%s
  312.                where name=%s
  313.                ''', (subject1, subject2, subject3, subject4, subject5, name))
  314.     print(f"\nUpdate successful for student {name}")
  315.     mydb.commit()
  316.  
  317. update_marks('Rishi', 58, 95, 85, 85, 54)
  318. cur.execute('select * from student_mark')
  319. rows = cur.fetchall()
  320. for row in rows:
  321.     print(row)
  322.  
  323.  
  324. def del_marks(name):
  325.     try:
  326.         dquery = 'delete from student_mark where name=%s'
  327.         cur.execute(dquery, (name,))
  328.         print(f"\nDeleted marks for student {name}")
  329.     except mysql.connector.Error as err:
  330.         print(f"\nFailed to delete marks for student {name}:{err}")
  331.     mydb.commit()
  332.  
  333. del_marks('Rishi')
  334. cur.execute('select * from student_mark')
  335. rows = cur.fetchall()
  336. for row in rows:
  337.     print(row)
  338.  
  339. 8. Inner Join:
  340. import mysql.connector
  341. import csv
  342.  
  343. mydb = mysql.connector.connect(
  344.     host='localhost',
  345.     user='root',
  346.     password='rootpw',
  347.     database='student'
  348. )
  349. cur=mydb.cursor()
  350. cur.execute('''
  351.            create table if not exists student_details
  352.            (name varchar(25),age int,grade varchar(10))
  353.            ''')
  354. def inner_join_students():
  355.     query = '''SELECT student_mark.name, student_mark.subject1, student_mark.subject2, student_mark.subject3, student_mark.subject4, student_mark.subject5, student_details.age, student_details.grade
  356.               FROM student_mark
  357.               INNER JOIN student_details ON student_mark.name = student_details.name'''
  358.     cur.execute(query)
  359.     rows = cur.fetchall()
  360.     for row in rows:
  361.         print(row)
  362.  
  363. inner_join_students()
  364.  
  365.  
  366.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement