1.
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 [Link](), "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([Link]()) == reference_keys, f"Inconsistent keys at index {i}: expected
{reference_keys}, found {set([Link]())}"
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)
[Link](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 = [Link]('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 = [Link]()
result = func(*args, **kwargs)
end_time = [Link]()
print(f"Execution time of {func.__name__}: {end_time - start_time} seconds")
return result
return wrapper
@timer
def slow_function():
[Link](2)
return "Function Finished"
print(slow_function())
[Link](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)
[Link] OBJECT
class Employee:
company_name = "TechCorp"
def __init__(self, name, salary):
[Link] = name
[Link] = salary
def display(self):
print(f"Employee Name: {[Link]}")
print(f"Salary: {[Link]}")
print(f"Company: {Employee.company_name}")
print("-" * 30)
emp1 = Employee("Alice", 50000)
emp2 = Employee("Bob", 60000)
print("Before modifying class variable:")
[Link]()
[Link]()
Employee.company_name = "CodeMasters"
print("After modifying class variable:")
[Link]()
[Link]()
[Link] = 55000
print("After modifying instance variable (emp1):")
[Link]()
[Link]()
[Link]
(task 1)
class Animal:
def speak(self):
print("Animals make sounds")
class Dog(Animal):
def bark(self):
print("Dog barks: Woof Woof!")
dog = Dog()
[Link]()
[Link]()
(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()
[Link]
import tkinter as tk
root = [Link]()
[Link]("Simple GUI Example")
[Link]("300x200")
label = [Link](root, text="Hello, Welcome to GUI!", font=("Arial", 12))
[Link](pady=10)
entry = [Link](root, width=20)
[Link](pady=5)
def show_message():
user_text = [Link]()
[Link](text=f"Hello, {user_text}!")
button = [Link](root, text="Click Me", command=show_message)
[Link](pady=10)
[Link]()
(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":
[Link]("Login Success", "Welcome!")
else:
[Link]("Login Failed", "Invalid Username or Password")
root = [Link]()
[Link]("Login Form")
[Link]("300x200")
[Link](root, text="Username:", font=("Arial", 12)).pack(pady=5)
entry_username = [Link](root, font=("Arial", 12))
entry_username.pack(pady=5)
[Link](root, text="Password:", font=("Arial", 12)).pack(pady=5)
entry_password = [Link](root, font=("Arial", 12), show="*")
entry_password.pack(pady=5)
[Link](root, text="Login", font=("Arial", 12), command=login).pack(pady=10)
[Link]()
(task 2)
import tkinter as tk
def increase_count():
count_var.set(count_var.get() + 1)
root = [Link]()
[Link]("Click Counter")
count_var = [Link](value=0)
label = [Link](root, textvariable=count_var, font=("Arial", 20))
[Link](pady=10)
button = [Link](root, text="Click Me!", font=("Arial", 14),
command=increase_count)
[Link](pady=5)
[Link]()
[Link]
import tkinter as tk
from tkinter import ttk
root = [Link]()
[Link]("GUI Widgets Example")
[Link]("400x300")
label = [Link](root, text="Enter your name:", font=("Arial", 12))
[Link](pady=5)
entry = [Link](root, width=30)
[Link](pady=5)
def on_submit():
user_text = [Link]()
output_label.config(text=f"Hello, {user_text}!")
submit_button = [Link](root, text="Submit", command=on_submit)
submit_button.pack(pady=5)
check_var = [Link]()
check_button = [Link](root, text="Accept Terms", variable=check_var)
check_button.pack(pady=5)
radio_var = [Link](value="Male")
male_radio = [Link](root, text="Male", variable=radio_var, value="Male")
female_radio = [Link](root, text="Female", variable=radio_var,
value="Female")
male_radio.pack()
female_radio.pack()
combo_label = [Link](root, text="Select a Country:")
combo_label.pack(pady=5)
countries = ["USA", "India", "UK", "Canada"]
combo = [Link](root, values=countries)
[Link](pady=5)
output_label = [Link](root, text="", font=("Arial", 12), fg="blue")
output_label.pack(pady=5)
[Link]()
(task 1)
import tkinter as tk
root = [Link]()
[Link]("Listbox Example")
[Link]("300x200")
[Link](root, text="Select a fruit:").pack(pady=5)
listbox = [Link](root)
fruits = ["Apple", "Banana", "Cherry", "Date"]
for fruit in fruits:
[Link]([Link], fruit)
[Link]()
[Link]()
(task 2)
import tkinter as tk
root = [Link]()
[Link]("Password Entry")
[Link]("300x150")
[Link](root, text="Enter Password:").pack(pady=5)
password_entry = [Link](root, show="*")
password_entry.pack(pady=5)
[Link](root, text="Submit", command=lambda: print("Password:",
password_entry.get())).pack()
[Link]()
(task 3)
import tkinter as tk
from tkinter import colorchooser
def choose_color():
color = [Link]()[1]
if color:
color_label.config(bg=color)
root = [Link]()
[Link]("Color Picker")
[Link]("300x150")
[Link](root, text="Choose a Color", command=choose_color).pack(pady=10)
color_label = [Link](root, text="Color Preview", width=20, height=2, bg="white")
color_label.pack(pady=10)
[Link]()
(task 4)
import tkinter as tk
root = [Link]()
[Link]("Grid Layout Example")
[Link]("300x200")
[Link](root, text="Name:").grid(row=0, column=0, padx=10, pady=5)
name_entry = [Link](root)
name_entry.grid(row=0, column=1, pady=5)
[Link](root, text="Email:").grid(row=1, column=0, padx=10, pady=5)
email_entry = [Link](root)
email_entry.grid(row=1, column=1, pady=5)
[Link](root, text="Submit").grid(row=2, column=1, pady=10)
[Link]()
[Link]
import threading
import time
def task1():
for i in range(3):
print(f"Task 1 - Step {i+1}")
[Link](1)
def task2():
for i in range(3):
print(f"Task 2 - Step {i+1}")
[Link](1)
t1 = [Link](target=task1)
t2 = [Link](target=task2)
[Link]()
[Link]()
[Link]()
[Link]()
print("Main thread finished.")
(task 1)
import threading
import time
def print_numbers():
for i in range(1, 6):
print("Number:", i)
[Link](0.5)
def print_alphabets():
for ch in ['A', 'B', 'C', 'D', 'E']:
print("Alphabet:", ch)
[Link](0.5)
t1 = [Link](target=print_numbers)
t2 = [Link](target=print_alphabets)
[Link]()
[Link]()
[Link]()
[Link]()
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 = [Link](target=square, args=(num,))
t2 = [Link](target=cube, args=(num,))
[Link]()
[Link]()
[Link]()
[Link]()
(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 = [Link](target=print_even)
t2 = [Link](target=print_odd)
[Link]()
[Link]()
[Link]()
[Link]()
[Link]
import numpy as np
array1 = [Link]([1, 2, 3, 4, 5])
array2 = [Link]([[1, 2, 3], [4, 5, 6]])
sum_array = array1 + 5
mul_array = array1 * 2
mean_value = [Link](array1)
median_value = [Link](array1)
std_dev = [Link](array1)
matrix1 = [Link]([[1, 2], [3, 4]])
matrix2 = [Link]([[5, 6], [7, 8]])
dot_product = [Link](matrix1, matrix2)
matrix_inverse = [Link](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 = [Link]([10, 20, 30])
arr2 = [Link]([1, 2, 3])
result = arr1 + arr2
print("Element-wise Addition:", result)
(task 2)
import numpy as np
arr = [Link]([5, 10, 15, 20])
variance = [Link](arr)
print("Variance:", variance)
(task 3)
import numpy as np
random_array = [Link](3, 3)
print("Random Array:\n", random_array)
(task 4)
import numpy as np
A = [Link]([[2, 1], [3, 2]])
B = [Link]([8, 13])
solution = [Link](A, B)
print("Solution [x, y]:", solution)
[Link] MATPLOTLIB
import pandas as pd
import numpy as np
import [Link] as plt
[Link](42)
data={'Column1':[Link](10,100,50),'Column2':[Link](50)*100}
df=[Link](data)
print([Link]())
print([Link]())
print([Link]())
average_value=df['Column1'].mean()
filtered_data=df[df['Column1']>average_value]
print(average_value)
print(filtered_data)
df['Column1'].hist(bins=10)
[Link]("Distribution of Column1")
[Link]("Values")
[Link]("Frequency")
[Link]()
[Link](x='Column1',y='Column2',kind='scatter')
[Link]("Column1 vs Column2")
[Link]()
(task 1)
import pandas as pd
import numpy as np
df = [Link]({'A': [1, [Link], 3], 'B': [4, 5, [Link]]})
df_filled = [Link](0)
df_dropped = [Link]()
print(df_filled)
print(df_dropped)
(task 2)
import pandas as pd
df = [Link]({'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 = [Link]({'Column1': ['A', 'B', 'A'], 'Values': [10, 20, 30]})
grouped = [Link]('Column1').sum()
print(grouped)
(task 4)
import pandas as pd
import [Link] as plt
df = [Link]({'Column1': [10, 20, 30, 25, 15, 40, 35]})
[Link](column="Column1")
[Link]()
[Link] AND SEABORN
import [Link] as plt
import seaborn as sns
import pandas as pd
import numpy as np
x = [Link](1, 11)
y = [Link](10, 100, size=10)
[Link](figsize=(6, 4))
[Link](x, y, marker='o', linestyle='-', color='b', label="Line Plot")
[Link]("Line Chart Example")
[Link]("X values")
[Link]("Y values")
[Link]()
[Link]()
[Link](figsize=(6, 4))
[Link](x, y, color='green', label="Bar Graph")
[Link]("Bar Graph Example")
[Link]("Categories")
[Link]("Values")
[Link]()
[Link]()
data = [Link](1000)
[Link](figsize=(6, 4))
[Link](data, bins=30, color='purple', alpha=0.7)
[Link]("Histogram Example")
[Link]("Data Bins")
[Link]("Frequency")
[Link]()
y2 = [Link](10, 100, size=10)
[Link](figsize=(6, 4))
[Link](x, y, color='red', label="Dataset 1")
[Link](x, y2, color='blue', label="Dataset 2")
[Link]("Scatter Plot Example")
[Link]("X values")
[Link]("Y values")
[Link]()
[Link]()
[Link](style="whitegrid")
[Link](figsize=(6, 4))
[Link](data=[y, y2], palette="coolwarm")
[Link]("Box Plot Example")
[Link]("Dataset")
[Link]("Values")
[Link]()
(task 1)
import [Link] as plt
labels = ['Apple', 'Banana', 'Grapes', 'Orange']
sizes = [25, 30, 20, 25]
colors = ['red', 'yellow', 'purple', 'orange']
[Link](figsize=(5, 5))
[Link](sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90)
[Link]("Fruit Distribution")
[Link]()
(task 2)
import seaborn as sns
import pandas as pd
import numpy as np
import [Link] as plt
data = [Link]({
'Math': [Link](40, 100, 10),
'Science': [Link](50, 95, 10),
'English': [Link](45, 98, 10),
'History': [Link](50, 90, 10)
})
correlation = [Link]()
[Link](correlation, annot=True, cmap="YlGnBu")
[Link]("Subject Score Correlation")
[Link]()
(task 3)
import seaborn as sns
import [Link] as plt
import numpy as np
[Link](style="darkgrid")
data = sns.load_dataset("iris")
palette = sns.color_palette("mako")
[Link](data, hue="species", palette=palette)
[Link]("Pair Plot with Mako Palette", y=1.02)
[Link]()
(task 4)
import seaborn as sns
import [Link] as plt
titanic = sns.load_dataset("titanic")
[Link](data=titanic, x="class", hue="survived", palette="Set2")
[Link]("Survival Count by Passenger Class")
[Link]()
[Link](data=titanic, x="age", hue="sex", bins=20, kde=True)
[Link]("Age Distribution by Gender")
[Link]()