Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 1. String Functions:
- def Concatenation():
- str1 = "Hello"
- str2 = "World"
- result_plus = str1 + " " + str2
- print("Concatenation Example of Hello + World")
- print(result_plus)
- print("\n")
- def Reverse():
- print("Reverse Example")
- my_str = "Hello!"
- reversed_str = ""
- for char in my_str:
- reversed_str = char + reversed_str
- print(reversed_str)
- print("\n")
- def Replication():
- print("Replication Example")
- my_str = "Py"
- replicated_str = ""
- for _ in range(5):
- replicated_str += my_str
- print(replicated_str)
- print("\n")
- def Slicing():
- print("Slicing Example")
- my_str = "Hello, World!"
- substring = my_str[7:12]
- print(substring)
- print("\n")
- def Equals():
- print("Equals Example")
- str1 = "Hello"
- str2 = "Hello"
- if str1 != str2:
- print("The strings are not equal")
- print("\n")
- else:
- print("The strings are equal")
- print("\n")
- def iterate_string():
- print("Iteration Example")
- my_string = "Hello, world!"
- for char in my_string:
- print(char)
- print("\n")
- def substring():
- print("Substring Example")
- my_string = "Hello, World!"
- substring = ""
- for i in range(6, 10):
- substring += my_string[i]
- print(substring)
- Concatenation()
- Reverse()
- Replication()
- Slicing()
- Equals()
- iterate_string()
- substring()
- print("\nAll actions performed successfully!")
- 2. Regex:
- import re
- print("Matching a pattern")
- pattern = r"apple"
- text = "I like apples and oranges."
- print("Using re.search() to find the first occurrence of the pattern")
- match = re.search(pattern, text)
- if match:
- print(f"Pattern '{pattern}' found at index {match.start()} in the text.")
- else:
- print(f"Pattern '{pattern}' not found in the text.")
- print("\nExtracting matches using groups")
- pattern_with_groups = r"(\w+) (\w+)"
- name_text = "John Doe, Jane Smith"
- print("Using re.findall() to find all occurrences of the pattern with groups")
- matches = re.findall(pattern_with_groups, name_text)
- for match in matches:
- first_name, last_name = match
- print(f"First Name: {first_name}, Last Name: {last_name}")
- print("\nReplacing matches")
- pattern_to_replace = r"apple|orange"
- replacement_text = "fruit"
- print("Using re.sub() to replace all occurrences of the pattern")
- updated_text = re.sub(pattern_to_replace, replacement_text, text)
- print(f"Original Text: {text}")
- print(f"Updated Text: {updated_text}")
- 3. Regex Tkinter:
- import tkinter as tk
- import re
- def validate_phone_number():
- phone = phone_entry.get()
- phone_pattern = r"^\d{10}$"
- if re.match(phone_pattern, phone):
- result_label.config(text="Valid Phone Number", fg="green")
- else:
- result_label.config(text="Invalid Phone Number", fg="red")
- root = tk.Tk()
- root.title("Phone Number Validation Form")
- tk.Label(root, text="Phone Number:").grid(row=0, column=0, sticky="w", padx=10, pady=5)
- phone_entry = tk.Entry(root)
- phone_entry.grid(row=0, column=1, padx=10, pady=5)
- validate_button = tk.Button(root, text="Validate", command=validate_phone_number)
- validate_button.grid(row=1, column=0, columnspan=2, pady=10)
- result_label = tk.Label(root, text="", fg="black")
- result_label.grid(row=2, column=0, columnspan=2, pady=5)
- root.mainloop()
- 4. Tkinter Calculator
- import tkinter as tk
- def on_button_click(value):
- current = entry.get()
- entry.delete(0, tk.END)
- entry.insert(tk.END, current + value)
- def clear_entry():
- entry.delete(0, tk.END)
- def calculate_result():
- try:
- result = eval(entry.get())
- entry.delete(0, tk.END)
- entry.insert(tk.END, str(result))
- except Exception as e:
- entry.delete(0, tk.END)
- entry.insert(tk.END, "Error")
- root = tk.Tk()
- root.title("Simple Calculator")
- entry = tk.Entry(root, width=20, font=('Arial', 16), borderwidth=5)
- entry.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
- buttons = [
- '7', '8', '9', '/',
- '4', '5', '6', '*',
- '1', '2', '3', '-',
- '0', '.', '=', '+'
- ]
- row_val = 1
- col_val = 0
- for button in buttons:
- tk.Button(root, text=button, padx=20, pady=20, font=('Arial', 14),
- command=lambda b=button: on_button_click(b) if b != '=' else calculate_result()).grid(row=row_val, column=col_val)
- col_val += 1
- if col_val > 3:
- col_val = 0
- row_val += 1
- tk.Button(root, text='C', padx=20, pady=20, font=('Arial', 14), command=clear_entry).grid(row=row_val, column=col_val, columnspan=2)
- root.mainloop()
- 5. RW Ops with File
- import urllib.request
- import os
- file_name = "E:\Study\Python\exps\CountryWiseAirport.csv"
- with open(file_name, 'rb') as f:
- binary_data = f.read()
- binary_file_name = "airport.bin"
- with open(binary_file_name, 'wb') as f:
- f.write(binary_data)
- text_file_name = "airport.txt"
- with open(text_file_name, 'w') as f:
- f.write(binary_data.decode('utf-8'))
- def print_file_content(file_path):
- with open(file_path, 'rb') as f:
- content = f.read().decode('utf-8')
- print(content)
- print("Initial Binary File Content:")
- print_file_content(binary_file_name)
- print("\nInitial Text File Content:")
- print_file_content(text_file_name)
- with open(binary_file_name, 'ab') as f:
- f.write(b"\nThis is an appended line for binary file.")
- print("\nThe binary file has been appended.")
- with open(text_file_name, 'a') as f:
- f.write("\nThis is an appended line for text file.")
- print("\nThe text file has been appended.")
- print("\nBinary File Content after Append:")
- print_file_content(binary_file_name)
- print("\nText File Content after Append:")
- print_file_content(text_file_name)
- new_binary_data = b"This is new binary data."
- with open(binary_file_name, 'wb') as f:
- f.write(new_binary_data)
- print("\nThe file has been written.")
- new_text_data = "This is new text data."
- with open(text_file_name, 'w') as f:
- f.write(new_text_data)
- print("\nThe file has been written.")
- print("\nBinary File Content after Write:")
- print_file_content(binary_file_name)
- print("\nText File Content after Write:")
- print_file_content(text_file_name)
- 6. Collect data to CSV:
- import csv
- def collect_marks():
- marks_data = []
- for i in range(3):
- student_name = input(f"\nEnter name for student {i+1}: ")
- marks = [student_name]
- for j in range(3):
- subject = input(f"Enter marks for subject {j+1}: ")
- marks.append(subject)
- marks_data.append(marks)
- return marks_data
- def write_to_csv(data):
- file = open('student_marks1.csv', 'w', newline='')
- writer = csv.writer(file)
- writer.writerow(["Student Name"] + [f"Subject {i}" for i in range(1, 6)])
- for marks in data:
- writer.writerow(marks)
- file.close()
- def read_from_csv():
- file = open('student_marks1.csv', newline='')
- reader = csv.reader(file)
- for row in reader:
- print(row)
- file.close()
- marks_data = collect_marks()
- write_to_csv(marks_data)
- read_from_csv()
- 7. CRUD Ops:
- import mysql.connector
- import csv
- mydb = mysql.connector.connect(
- host='localhost',
- user='root',
- password='rootpw',
- database='student'
- )
- cur = mydb.cursor()
- cur.execute('''create table if not exists student_mark(
- name VARCHAR(25),
- subject1 int,
- subject2 int,
- subject3 int,
- subject4 int,
- subject5 int)'''
- )
- def im_csv_to_my(file_path):
- with open(file_path, newline='') as csvf:
- reader = csv.reader(csvf)
- next(reader)
- for row in reader:
- name, subject1, subject2, subject3, subject4, subject5 = row
- cur.execute('''
- insert into student_mark(name, subject1, subject2, subject3, subject4, subject5)
- values(%s,%s,%s,%s,%s,%s)
- ''', (name, int(subject1), int(subject2), int(subject3), int(subject4), int(subject5))
- )
- mydb.commit()
- im_csv_to_my('E:\\Study\\Python\\exps\\student_marks.csv')
- cur.execute('select * from student_mark')
- rows = cur.fetchall()
- for row in rows:
- print(row)
- def update_marks(name, subject1, subject2, subject3, subject4, subject5):
- cur.execute('''
- update student_mark set subject1=%s, subject2=%s, subject3=%s, subject4=%s, subject5=%s
- where name=%s
- ''', (subject1, subject2, subject3, subject4, subject5, name))
- print(f"\nUpdate successful for student {name}")
- mydb.commit()
- update_marks('Rishi', 58, 95, 85, 85, 54)
- cur.execute('select * from student_mark')
- rows = cur.fetchall()
- for row in rows:
- print(row)
- def del_marks(name):
- try:
- dquery = 'delete from student_mark where name=%s'
- cur.execute(dquery, (name,))
- print(f"\nDeleted marks for student {name}")
- except mysql.connector.Error as err:
- print(f"\nFailed to delete marks for student {name}:{err}")
- mydb.commit()
- del_marks('Rishi')
- cur.execute('select * from student_mark')
- rows = cur.fetchall()
- for row in rows:
- print(row)
- 8. Inner Join:
- import mysql.connector
- import csv
- mydb = mysql.connector.connect(
- host='localhost',
- user='root',
- password='rootpw',
- database='student'
- )
- cur=mydb.cursor()
- cur.execute('''
- create table if not exists student_details
- (name varchar(25),age int,grade varchar(10))
- ''')
- def inner_join_students():
- 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
- FROM student_mark
- INNER JOIN student_details ON student_mark.name = student_details.name'''
- cur.execute(query)
- rows = cur.fetchall()
- for row in rows:
- print(row)
- inner_join_students()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement