Python
Python
ASSERT(age)
def check_voting_eligibility(age):
assert age >= 18, "User is not eligible to vote"
print("User is eligible to vote.")
try:
age_input = int(input("Enter your age: "))
check_voting_eligibility(age_input)
except AssertionError as e:
print(e)
(task 1)
def check_positive(num):
assert num > 0, "Number is not positive"
print("The number is positive.")
try:
n = float(input("Enter a number: "))
check_positive(n)
except AssertionError as e:
print(e)
(task 2)
def check_alphanumeric(s):
assert s.isalnum(), "String is not alphanumeric"
print("The string is alphanumeric.")
try:
user_input = input("Enter a string: ")
check_alphanumeric(user_input)
except AssertionError as e:
print(e)
(task 3)
def check_key_in_dict(d, key):
assert key in d, f"Key '{key}' not found in dictionary"
print(f"Key '{key}' exists with value: {d[key]}")
try:
my_dict = {"name": "Alice", "age": 25, "city": "Mumbai"}
key_to_check = input("Enter the key to check: ")
check_key_in_dict(my_dict, key_to_check)
except AssertionError as e:
print(e)
(task 4)
def check_consistent_keys(dict_list):
if not dict_list:
print("The list is empty.")
return
reference_keys = set(dict_list[0].keys())
for i, d in enumerate(dict_list):
assert set(d.keys()) == reference_keys, f"Inconsistent keys at index {i}: expected
{reference_keys}, found {set(d.keys())}"
print("All dictionaries have consistent key names.")
data = [
{"id": 1, "name": "Alice", "age": 25},
{"id": 2, "name": "Bob", "age": 30},
{"id": 3, "name": "Charlie", "age": 28}
]
try:
check_consistent_keys(data)
except AssertionError as e:
print("
", e)
2.DECORATORS(HELLO)
def decorator(func):
def wrapper():
print("Before function execution")
result = func()
print("After function execution")
return result
return wrapper
@decorator
def say_hello():
print("Hello!")
say_hello()
(task 1)
def log_function_call(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with arguments: {args}, {kwargs}")
result = func(*args, **kwargs)
print(f"{func.__name__} returned: {result}")
return result
return wrapper
@log_function_call
def add(a, b):
return a + b
add(2, 3)
(task 2)
def check_permissions(func):
def wrapper(*args, **kwargs):
user = kwargs.get('user')
if user != 'admin':
raise PermissionError("You do not have permission to execute this function.")
return func(*args, **kwargs)
return wrapper
@check_permissions
def delete_record(record_id, user):
print(f"Record {record_id} deleted.")
delete_record(123, user="admin")
(task 3)
def memoize(func):
cache = {}
def wrapper(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return wrapper
@memoize
def slow_function(x):
print("Calculating...")
return x * x
print(slow_function(4))
print(slow_function(4))
(task 4)
import time
def timer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Execution time of {func.__name__}: {end_time - start_time} seconds")
return result
return wrapper
@timer
def slow_function():
time.sleep(2)
return "Function Finished"
print(slow_function())
3.GENERATORS(HELLO)
def simple_generator():
yield "Hello"
yield "World!"
gen = simple_generator()
for value in gen:
print(value)
(task 1)
def fibonacci_first_n(n):
a, b = 0, 1
count = 0
while count < n:
yield a
a, b = b, a + b
count += 1
for num in fibonacci_first_n(10):
print(num)
(task 2)
def even_series_upto_20():
for num in range(0, 21, 2):
yield num
for value in even_series_upto_20():
print(value)
(task 3)
def square_generator_upto_5():
for i in range(1, 6):
yield i * i
for square in square_generator_upto_5():
print(square)
4A.CLASS OBJECT
class Employee:
company_name = "TechCorp"
def __init__(self, name, salary):
self.name = name
self.salary = salary
def display(self):
print(f"Employee Name: {self.name}")
print(f"Salary: {self.salary}")
print(f"Company: {Employee.company_name}")
print("-" * 30)
emp1 = Employee("Alice", 50000)
emp2 = Employee("Bob", 60000)
print("Before modifying class variable:")
emp1.display()
emp2.display()
Employee.company_name = "CodeMasters"
print("After modifying class variable:")
emp1.display()
emp2.display()
emp1.salary = 55000
print("After modifying instance variable (emp1):")
emp1.display()
emp2.display()
4B.INHERITANCE
(task 1)
class Animal:
def speak(self):
print("Animals make sounds")
class Dog(Animal):
def bark(self):
print("Dog barks: Woof Woof!")
dog = Dog()
dog.speak()
dog.bark()
(task 2)
class Father:
def show_father_traits(self):
print("Father: Strong and disciplined")
class Mother:
def show_mother_traits(self):
print("Mother: Caring and loving")
class Child(Father, Mother):
def show_child_traits(self):
print("Child: Combination of both parents")
child = Child()
child.show_father_traits()
child.show_mother_traits()
child.show_child_traits()
(task 3)
class Grandparent:
def show_grandparent_traits(self):
print("Grandparent: Wise and experienced")
class Parent(Grandparent):
def show_parent_traits(self):
print("Parent: Responsible and caring")
class Child(Parent):
def show_child_traits(self):
print("Child: Learns from both")
child = Child()
child.show_grandparent_traits()
child.show_parent_traits()
child.show_child_traits()
(task 4)
class Vehicle:
def show_vehicle_type(self):
print("This is a vehicle")
class Car(Vehicle):
def show_car_details(self):
print("Car: Four wheels and comfortable")
class Bike(Vehicle):
def show_bike_details(self):
print("Bike: Two wheels and fuel-efficient")
car = Car()
bike = Bike()
car.show_vehicle_type()
car.show_car_details()
bike.show_vehicle_type()
bike.show_bike_details()
5.TKINTER
import tkinter as tk
root = tk.Tk()
root.title("Simple GUI Example")
root.geometry("300x200")
label = tk.Label(root, text="Hello, Welcome to GUI!", font=("Arial", 12))
label.pack(pady=10)
entry = tk.Entry(root, width=20)
entry.pack(pady=5)
def show_message():
user_text = entry.get()
label.config(text=f"Hello, {user_text}!")
button = tk.Button(root, text="Click Me", command=show_message)
button.pack(pady=10)
root.mainloop()
(task 1)
import tkinter as tk
from tkinter import messagebox
def login():
username = entry_username.get()
password = entry_password.get()
if username == "admin" and password == "password":
messagebox.showinfo("Login Success", "Welcome!")
else:
messagebox.showerror("Login Failed", "Invalid Username or Password")
root = tk.Tk()
root.title("Login Form")
root.geometry("300x200")
tk.Label(root, text="Username:", font=("Arial", 12)).pack(pady=5)
entry_username = tk.Entry(root, font=("Arial", 12))
entry_username.pack(pady=5)
tk.Label(root, text="Password:", font=("Arial", 12)).pack(pady=5)
entry_password = tk.Entry(root, font=("Arial", 12), show="*")
entry_password.pack(pady=5)
tk.Button(root, text="Login", font=("Arial", 12), command=login).pack(pady=10)
root.mainloop()
(task 2)
import tkinter as tk
def increase_count():
count_var.set(count_var.get() + 1)
root = tk.Tk()
root.title("Click Counter")
count_var = tk.IntVar(value=0)
label = tk.Label(root, textvariable=count_var, font=("Arial", 20))
label.pack(pady=10)
button = tk.Button(root, text="Click Me!", font=("Arial", 14),
command=increase_count)
button.pack(pady=5)
root.mainloop()
6.WIDGET
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("GUI Widgets Example")
root.geometry("400x300")
label = tk.Label(root, text="Enter your name:", font=("Arial", 12))
label.pack(pady=5)
entry = tk.Entry(root, width=30)
entry.pack(pady=5)
def on_submit():
user_text = entry.get()
output_label.config(text=f"Hello, {user_text}!")
submit_button = tk.Button(root, text="Submit", command=on_submit)
submit_button.pack(pady=5)
check_var = tk.IntVar()
check_button = tk.Checkbutton(root, text="Accept Terms", variable=check_var)
check_button.pack(pady=5)
radio_var = tk.StringVar(value="Male")
male_radio = tk.Radiobutton(root, text="Male", variable=radio_var, value="Male")
female_radio = tk.Radiobutton(root, text="Female", variable=radio_var,
value="Female")
male_radio.pack()
female_radio.pack()
combo_label = tk.Label(root, text="Select a Country:")
combo_label.pack(pady=5)
countries = ["USA", "India", "UK", "Canada"]
combo = ttk.Combobox(root, values=countries)
combo.pack(pady=5)
output_label = tk.Label(root, text="", font=("Arial", 12), fg="blue")
output_label.pack(pady=5)
root.mainloop()
(task 1)
import tkinter as tk
root = tk.Tk()
root.title("Listbox Example")
root.geometry("300x200")
tk.Label(root, text="Select a fruit:").pack(pady=5)
listbox = tk.Listbox(root)
fruits = ["Apple", "Banana", "Cherry", "Date"]
for fruit in fruits:
listbox.insert(tk.END, fruit)
listbox.pack()
root.mainloop()
(task 2)
import tkinter as tk
root = tk.Tk()
root.title("Password Entry")
root.geometry("300x150")
tk.Label(root, text="Enter Password:").pack(pady=5)
password_entry = tk.Entry(root, show="*")
password_entry.pack(pady=5)
tk.Button(root, text="Submit", command=lambda: print("Password:",
password_entry.get())).pack()
root.mainloop()
(task 3)
import tkinter as tk
from tkinter import colorchooser
def choose_color():
color = colorchooser.askcolor()[1]
if color:
color_label.config(bg=color)
root = tk.Tk()
root.title("Color Picker")
root.geometry("300x150")
tk.Button(root, text="Choose a Color", command=choose_color).pack(pady=10)
color_label = tk.Label(root, text="Color Preview", width=20, height=2, bg="white")
color_label.pack(pady=10)
root.mainloop()
(task 4)
import tkinter as tk
root = tk.Tk()
root.title("Grid Layout Example")
root.geometry("300x200")
tk.Label(root, text="Name:").grid(row=0, column=0, padx=10, pady=5)
name_entry = tk.Entry(root)
name_entry.grid(row=0, column=1, pady=5)
tk.Label(root, text="Email:").grid(row=1, column=0, padx=10, pady=5)
email_entry = tk.Entry(root)
email_entry.grid(row=1, column=1, pady=5)
tk.Button(root, text="Submit").grid(row=2, column=1, pady=10)
root.mainloop()
7.MULTITHREADING
import threading
import time
def task1():
for i in range(3):
print(f"Task 1 - Step {i+1}")
time.sleep(1)
def task2():
for i in range(3):
print(f"Task 2 - Step {i+1}")
time.sleep(1)
t1 = threading.Thread(target=task1)
t2 = threading.Thread(target=task2)
t1.start()
t2.start()
t1.join()
t2.join()
print("Main thread finished.")
(task 1)
import threading
import time
def print_numbers():
for i in range(1, 6):
print("Number:", i)
time.sleep(0.5)
def print_alphabets():
for ch in ['A', 'B', 'C', 'D', 'E']:
print("Alphabet:", ch)
time.sleep(0.5)
t1 = threading.Thread(target=print_numbers)
t2 = threading.Thread(target=print_alphabets)
t1.start()
t2.start()
t1.join()
t2.join()
print("Done")
(task 2)
import threading
def square(n):
print(f"Square of {n} is {n * n}")
def cube(n):
print(f"Cube of {n} is {n * n * n}")
num = 4
t1 = threading.Thread(target=square, args=(num,))
t2 = threading.Thread(target=cube, args=(num,))
t1.start()
t2.start()
t1.join()
t2.join()
(task 3)
import threading
def print_even():
for i in range(1, 11):
if i % 2 == 0:
print("Even:", i)
def print_odd():
for i in range(1, 11):
if i % 2 != 0:
print("Odd:", i)
t1 = threading.Thread(target=print_even)
t2 = threading.Thread(target=print_odd)
t1.start()
t2.start()
t1.join()
t2.join()
8.NUMPY
import numpy as np
array1 = np.array([1, 2, 3, 4, 5])
array2 = np.array([[1, 2, 3], [4, 5, 6]])
sum_array = array1 + 5
mul_array = array1 * 2
mean_value = np.mean(array1)
median_value = np.median(array1)
std_dev = np.std(array1)
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
dot_product = np.dot(matrix1, matrix2)
matrix_inverse = np.linalg.inv(matrix1)
print("Original 1D Array:", array1)
print("1D Array after Addition:", sum_array)
print("1D Array after Multiplication:", mul_array)
print("Mean:", mean_value)
print("Median:", median_value)
print("Standard Deviation:", std_dev)
print("Matrix Multiplication:\n", dot_product)
print("Matrix Inverse:\n", matrix_inverse)
(task 1)
import numpy as np
arr1 = np.array([10, 20, 30])
arr2 = np.array([1, 2, 3])
result = arr1 + arr2
print("Element-wise Addition:", result)
(task 2)
import numpy as np
arr = np.array([5, 10, 15, 20])
variance = np.var(arr)
print("Variance:", variance)
(task 3)
import numpy as np
random_array = np.random.rand(3, 3)
print("Random Array:\n", random_array)
(task 4)
import numpy as np
A = np.array([[2, 1], [3, 2]])
B = np.array([8, 13])
solution = np.linalg.solve(A, B)
print("Solution [x, y]:", solution)
9.PANDAS MATPLOTLIB
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(42)
data={'Column1':np.random.randint(10,100,50),'Column2':np.random.rand(50)*100}
df=pd.DataFrame(data)
print(df.head())
print(df.info())
print(df.describe())
average_value=df['Column1'].mean()
filtered_data=df[df['Column1']>average_value]
print(average_value)
print(filtered_data)
df['Column1'].hist(bins=10)
plt.title("Distribution of Column1")
plt.xlabel("Values")
plt.ylabel("Frequency")
plt.show()
df.plot(x='Column1',y='Column2',kind='scatter')
plt.title("Column1 vs Column2")
plt.show()
(task 1)
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': [1, np.nan, 3], 'B': [4, 5, np.nan]})
df_filled = df.fillna(0)
df_dropped = df.dropna()
print(df_filled)
print(df_dropped)
(task 2)
import pandas as pd
df = pd.DataFrame({'Column1': [3, 1, 2], 'Column2': ['C', 'A', 'B']})
sorted_df = df.sort_values(by="Column1")
print(sorted_df)
(task 3)
import pandas as pd
df = pd.DataFrame({'Column1': ['A', 'B', 'A'], 'Values': [10, 20, 30]})
grouped = df.groupby('Column1').sum()
print(grouped)
(task 4)
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'Column1': [10, 20, 30, 25, 15, 40, 35]})
df.boxplot(column="Column1")
plt.show()
10.MATPLOTLIB AND SEABORN
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
x = np.arange(1, 11)
y = np.random.randint(10, 100, size=10)
plt.figure(figsize=(6, 4))
plt.plot(x, y, marker='o', linestyle='-', color='b', label="Line Plot")
plt.title("Line Chart Example")
plt.xlabel("X values")
plt.ylabel("Y values")
plt.legend()
plt.show()
plt.figure(figsize=(6, 4))
plt.bar(x, y, color='green', label="Bar Graph")
plt.title("Bar Graph Example")
plt.xlabel("Categories")
plt.ylabel("Values")
plt.legend()
plt.show()
data = np.random.randn(1000)
plt.figure(figsize=(6, 4))
plt.hist(data, bins=30, color='purple', alpha=0.7)
plt.title("Histogram Example")
plt.xlabel("Data Bins")
plt.ylabel("Frequency")
plt.show()
y2 = np.random.randint(10, 100, size=10)
plt.figure(figsize=(6, 4))
plt.scatter(x, y, color='red', label="Dataset 1")
plt.scatter(x, y2, color='blue', label="Dataset 2")
plt.title("Scatter Plot Example")
plt.xlabel("X values")
plt.ylabel("Y values")
plt.legend()
plt.show()
sns.set(style="whitegrid")
plt.figure(figsize=(6, 4))
sns.boxplot(data=[y, y2], palette="coolwarm")
plt.title("Box Plot Example")
plt.xlabel("Dataset")
plt.ylabel("Values")
plt.show()
(task 1)
import matplotlib.pyplot as plt
labels = ['Apple', 'Banana', 'Grapes', 'Orange']
sizes = [25, 30, 20, 25]
colors = ['red', 'yellow', 'purple', 'orange']
plt.figure(figsize=(5, 5))
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90)
plt.title("Fruit Distribution")
plt.show()
(task 2)
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.DataFrame({
'Math': np.random.randint(40, 100, 10),
'Science': np.random.randint(50, 95, 10),
'English': np.random.randint(45, 98, 10),
'History': np.random.randint(50, 90, 10)
})
correlation = data.corr()
sns.heatmap(correlation, annot=True, cmap="YlGnBu")
plt.title("Subject Score Correlation")
plt.show()
(task 3)
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
sns.set(style="darkgrid")
data = sns.load_dataset("iris")
palette = sns.color_palette("mako")
sns.pairplot(data, hue="species", palette=palette)
plt.suptitle("Pair Plot with Mako Palette", y=1.02)
plt.show()
(task 4)
import seaborn as sns
import matplotlib.pyplot as plt
titanic = sns.load_dataset("titanic")
sns.countplot(data=titanic, x="class", hue="survived", palette="Set2")
plt.title("Survival Count by Passenger Class")
plt.show()
sns.histplot(data=titanic, x="age", hue="sex", bins=20, kde=True)
plt.title("Age Distribution by Gender")
plt.show()