Python All Combined
Python All Combined
import tkinter as tk
from tkinter import messagebox
class InventoryGUI:
def _init_(self, master):
self.master = master
self.master.title("Inventory Management System")
self.inventory = [] # Initialize inventory as an empty list
# GUI Elements
self.label_item = tk.Label(master, text="Item:")
self.label_quantity = tk.Label(master, text="Quantity:")
self.entry_item = tk.Entry(master)
self.entry_quantity = tk.Entry(master)
self.button_add = tk.Button(master, text="Add Item", command=self.add_item)
self.button_remove = tk.Button(master, text="Remove Item",
command=self.remove_item)
self.button_display = tk.Button(master, text="Display Inventory",
command=self.display_inventory)
# Layout
self.label_item.grid(row=0, column=0, padx=10, pady=5)
self.entry_item.grid(row=0, column=1, padx=10, pady=5)
self.label_quantity.grid(row=1, column=0, padx=10, pady=5)
self.entry_quantity.grid(row=1, column=1, padx=10, pady=5)
self.button_add.grid(row=2, column=0, padx=10, pady=5)
self.button_remove.grid(row=2, column=1, padx=10, pady=5)
self.button_display.grid(row=3, columnspan=2, padx=10, pady=5)
def add_item(self):
item_name = self.entry_item.get()
quantity = self.entry_quantity.get()
if item_name and quantity:
try:
quantity = int(quantity)
if quantity > 0:
for item in self.inventory:
if item['name'] == item_name:
item['quantity'] += quantity
break
else:
self.inventory.append({'name': item_name, 'quantity': quantity})
messagebox.showinfo("Success", f"{quantity} {item_name}(s) added to
inventory.")
self.clear_entries()
else:
messagebox.showwarning("Invalid Quantity", "Quantity must be a positive
integer.")
except ValueError:
messagebox.showerror("Error", "Quantity must be a number.")
else:
messagebox.showwarning("Empty Fields", "Please fill in both item and quantity.")
def remove_item(self):
item_name = self.entry_item.get()
quantity = self.entry_quantity.get()
if item_name and quantity:
try:
quantity = int(quantity)
if quantity > 0:
for item in self.inventory:
if item['name'] == item_name:
if item['quantity'] >= quantity:
item['quantity'] -= quantity
messagebox.showinfo("Success", f"{quantity} {item_name}(s) removed
from inventory.")
self.clear_entries()
else:
messagebox.showwarning("Insufficient Stock", f"Not enough {item_name}
in stock.")
break
else:
messagebox.showwarning("Item Not Found", f"{item_name} not found in
inventory.")
else:
messagebox.showwarning("Invalid Quantity", "Quantity must be a positive
integer.")
except ValueError:
messagebox.showerror("Error", "Quantity must be a number.")
else:
messagebox.showwarning("Empty Fields", "Please fill in both item and quantity.")
def display_inventory(self):
if self.inventory:
inventory_str = "Current Inventory:\n"
for item in self.inventory:
inventory_str += f"{item['name']}: {item['quantity']}\n"
messagebox.showinfo("Inventory", inventory_str)
else:
messagebox.showinfo("Empty Inventory", "Inventory is empty.")
def clear_entries(self):
self.entry_item.delete(0, tk.END)
self.entry_quantity.delete(0, tk.END)
# Create the main window
root = tk.Tk()
app = InventoryGUI(root)
root.mainloop()
2. Count the occurence of character in sentence and store using dictonary
def count_characters(sentence):
# Initialize an empty dictionary to store character counts
char_count = {}
# Loop through each character in the sentence
for char in sentence:
# Check if the character is already in the dictionary
if char in char_count:
# Increment the count if the character is already present
char_count[char] += 1
else:
# Add the character to the dictionary with count 1 if it's not already present
char_count[char] = 1
return char_count
# Example usage
sentence = "Hello, world!"
character_counts = count_characters(sentence)
# Display the character counts
for char, count in character_counts.items():
print(f"'{char}' occurs {count} times in the sentence.")
import time
def execution_time(func):
def wrapper(*args, **kwargs):
start_time = time.time() # Get the current time before executing the function
result = func(*args, **kwargs) # Execute the function
end_time = time.time() # Get the current time after executing the function
elapsed_time = end_time - start_time # Calculate the elapsed time
print(f"Execution time of {func._name_}: {elapsed_time:.6f} seconds")
return result
return wrapper
# Example usage
@execution_time
def my_function(n):
total = 0
for i in range(1, n+1):
total += i
return total
result = my_function(1000000)
print("Result:", result)
def convert_to_data_type(data_type):
def decorator(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs) # Execute the function
try:
return data_type(result) # Convert the result to the specified data type
except ValueError:
print(f"Error: Cannot convert result to {data_type._name_}")
return None # Return None if conversion fails
return wrapper
return decorator
# Example usage
@convert_to_data_type(float)
def divide(a, b):
return a / b
result = divide(10, 3)
print("Result (float):", result)
@convert_to_data_type(int)
def concatenate(a, b):
return str(a) + str(b)
result = concatenate(123, 456)
print("Result (int):", result)
import numpy as np
# Create a 2D NumPy array
arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Transpose the array
transposed_arr = np.transpose(arr)
# Reverse the rows of the transposed array
reversed_transposed_arr = transposed_arr[::-1]
print("Original Array:")
print(arr)
print("\nTransposed Array:")
print(transposed_arr)
print("\nReversed Transposed Array:")
print(reversed_transposed_arr)
import pandas as pd
# Create a DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 30, 35, 40],
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston']}
df = pd.DataFrame(data)
# Convert the 'Name' column to a Series
name_series = df['Name']
print("Original DataFrame:")
print(df)
print("\nName Series:")
print(name_series)
decimal_number = 42
# Convert decimal to binary
binary_number = bin(decimal_number)
# Convert decimal to octal
octal_number = oct(decimal_number)
def is_palindrome(input_str):
# Remove spaces and convert to lowercase for case-insensitive comparison
clean_str = input_str.replace(" ", "").lower()
# Check if the string is equal to its reverse
return clean_str == clean_str[::-1]
# Example usage
input_string = "A man a plan a canal Panama"
if is_palindrome(input_string):
print(f"'{input_string}' is a palindrome.")
else:
print(f"'{input_string}' is not a palindrome.")
9. Perform arithmetic operations on pandas series and check the elements of two series are same
or not
import pandas as pd
# Create two pandas Series
series1 = pd.Series([10, 20, 30, 40])
series2 = pd.Series([5, 10, 15, 20])
# Perform arithmetic operations on the Series
addition_result = series1 + series2
subtraction_result = series1 - series2
multiplication_result = series1 * series2
division_result = series1 / series2
# Check if the elements of two Series are the same
elements_same = (addition_result == subtraction_result) & (multiplication_result ==
division_result)
print("Series 1:")
print(series1)
print("\nSeries 2:")
print(series2)
print("\nAddition Result:")
print(addition_result)
print("\nSubtraction Result:")
print(subtraction_result)
print("\nMultiplication Result:")
print(multiplication_result)
print("\nDivision Result:")
print(division_result)
print("\nElements Same:")
print(elements_same)
def log_arguments_and_return(func):
def wrapper(*args, **kwargs):
# Log the arguments
print(f"Arguments: {args}, {kwargs}")
# Call the original function
result = func(*args, **kwargs)
# Log the return value
print(f"Return Value: {result}")
return result
return wrapper
# Example usage
@log_arguments_and_return
def add_numbers(a, b):
return a + b
result = add_numbers(10, 20)
print("Result:", result)
11. Create a class for a bank and create methods to add clients and to perform transactions
class Bank:
def _init_(self):
self.clients = {} # Dictionary to store clients and their balances
def add_client(self, client_name, initial_balance=0):
if client_name not in self.clients:
self.clients[client_name] = initial_balance
print(f"Client '{client_name}' added with initial balance: {initial_balance}")
else:
print(f"Client '{client_name}' already exists.")
def perform_transaction(self, client_name, amount):
if client_name in self.clients:
current_balance = self.clients[client_name]
new_balance = current_balance + amount
self.clients[client_name] = new_balance
print(f"Transaction successful: Client '{client_name}' new balance: {new_balance}")
else:
print(f"Client '{client_name}' does not exist.")
def display_clients(self):
print("Clients and Balances:")
for client, balance in self.clients.items():
print(f"{client}: {balance}")
# Example usage
bank = Bank()
bank.add_client("Alice", 1000)
bank.add_client("Bob", 500)
bank.add_client("Alice") # Existing client
bank.perform_transaction("Alice", -200)
bank.perform_transaction("Bob", 300)
bank.perform_transaction("Charlie", 200) # Non-existent client
bank.display_clients()
def decimal_to_binary(decimal_num):
if decimal_num <= 1:
return str(decimal_num)
else:
# Recursive call to convert quotient to binary
return decimal_to_binary(decimal_num // 2) + str(decimal_num % 2)
# Example usage
decimal_number = 42
binary_number = decimal_to_binary(decimal_number)
print(f"Decimal Number: {decimal_number}")
print(f"Binary Number: {binary_number}")
13. Sorting a list of tuples where each tuple has 2 elements and sorting the tuples based on second
element
print("Original List:")
print(list1)
print("\nSorted List based on second element:")
print(sorted_list)
import tkinter as tk
from tkinter import messagebox
def file_new():
messagebox.showinfo("New File", "Creating a new file.")
def file_open():
messagebox.showinfo("Open File", "Opening a file.")
def file_save():
messagebox.showinfo("Save File", "Saving the file.")
def help_about():
messagebox.showinfo("About", "This is a simple Tkinter GUI example.")
# Create the main window
root = tk.Tk()
root.title("Menu Bar Example")
# Create a menu bar
menubar = tk.Menu(root)
root.config(menu=menubar)
# Create File menu and add menu items
file_menu = tk.Menu(menubar, tearoff=0)
file_menu.add_command(label="New", command=file_new)
file_menu.add_command(label="Open", command=file_open)
file_menu.add_command(label="Save", command=file_save)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=file_menu)
# Create Help menu and add menu item
help_menu = tk.Menu(menubar, tearoff=0)
help_menu.add_command(label="About", command=help_about)
menubar.add_cascade(label="Help", menu=help_menu)
# Run the main loop
root.mainloop()
def count_and_print_lowercase(input_str):
lowercase_count = 0
lowercase_chars = []
for char in input_str:
if char.islower():
lowercase_count += 1
lowercase_chars.append(char)
print(f"Lowercase Characters Count: {lowercase_count}")
print("Lowercase Characters:", ', '.join(lowercase_chars))
# Example usage
input_string = "Hello, World! This is a Test String."
count_and_print_lowercase(input_string)
16. Sort the list - [(English , 91)] Aise list rahega depending upon marks sort karo
import tkinter as tk
from tkinter import messagebox
def login():
username = entry_username.get()
password = entry_password.get()
# Dummy username and password for demonstration
dummy_username = "user123"
dummy_password = "password123"
if username == dummy_username and password == dummy_password:
messagebox.showinfo("Login Successful", "Welcome, User!")
else:
messagebox.showerror("Login Failed", "Invalid username or password.")
# Create the main window
root = tk.Tk()
root.title("Login Form")
# Create labels, entries, and button widgets
label_username = tk.Label(root, text="Username:")
label_password = tk.Label(root, text="Password:")
entry_username = tk.Entry(root)
entry_password = tk.Entry(root, show="*") # Show asterisks for password input
button_login = tk.Button(root, text="Login", command=login)
# Layout widgets using grid
label_username.grid(row=0, column=0, padx=10, pady=5, sticky=tk.E)
label_password.grid(row=1, column=0, padx=10, pady=5, sticky=tk.E)
entry_username.grid(row=0, column=1, padx=10, pady=5)
entry_password.grid(row=1, column=1, padx=10, pady=5)
button_login.grid(row=2, columnspan=2, padx=10, pady=10)
# Run the main loop
root.mainloop()
18. Area of a rectangle using reduce and basic maths
try:
# Open the file
with open("filename.txt", "r") as file:
# Perform operations on the file
# For demonstration purposes, let's read and print the file contents
file_contents = file.read()
print("File contents:")
print(file_contents)
except FileNotFoundError:
print("File not found!")
def reverse_string_method(input_str):
reversed_str = input_str[::-1]
return reversed_str
def reverse_string_slicing(input_str):
reversed_str = ''.join(reversed(input_str))
return reversed_str
# Example usage
#Using methods
input_string = "Hello, World!"
reversed_string = reverse_string_method(input_string)
print("Original String:", input_string)
print("Reversed String (using method):", reversed_string)
#using slicing
input_string = "Hello, World!"
reversed_string = reverse_string_slicing(input_string)
print("Original String:", input_string)
print("Reversed String (using slicing):", reversed_string)
# Example usage
input_sentence = input("Enter a sentence to append to the file: ")
append_to_file(input_sentence)
print("Sentence appended to the file successfully!")
plt.show()
def count_words_ending_with_e(file_name):
try:
with open(file_name, 'r') as file:
# Read the entire content of the file
content = file.read()
# Split the content into words
words = content.split()
# Count words ending with 'e'
count = sum(1 for word in words if word.endswith('e'))
return count
except FileNotFoundError:
print(f"File '{file_name}' not found.")
return -1 # Return -1 for error
# Example usage
file_name = "source.txt"
word_count = count_words_ending_with_e(file_name)
if word_count != -1:
print(f"Number of words ending with 'e' in '{file_name}': {word_count}")
# Example usage
file_name = "source.txt"
word_to_count = "the"
occurrences_count = count_word_occurrences(file_name, word_to_count)
if occurrences_count != -1:
print(f"Occurrences of '{word_to_count}' in '{file_name}': {occurrences_count}")
25. Make bar graph using given data, add xlabel, ylabel and title
26. Mean, median, std deviation, quartile analysis using pandas by reading given dataset
import pandas as pd
# Read the dataset into a Pandas DataFrame
df = pd.read_csv('data.csv')
# Calculate mean, median, std deviation, and quartiles
mean_value = df['Value'].mean()
median_value = df['Value'].median()
std_deviation = df['Value'].std()
quartiles = df['Value'].quantile([0.25, 0.5, 0.75])
# Print the results
print(f"Mean: {mean_value}")
print(f"Median: {median_value}")
print(f"Standard Deviation: {std_deviation}")
print(f"Quartiles (25%, 50%, 75%):\n{quartiles}")
27. If else loop for marks and gui for button label
import tkinter as tk
# Function to update button label based on marks
def update_label(marks):
if marks >= 90:
label.config(text="Grade: A")
elif marks >= 80:
label.config(text="Grade: B")
elif marks >= 70:
label.config(text="Grade: C")
elif marks >= 60:
label.config(text="Grade: D")
else:
label.config(text="Grade: F")
# Create the main window
root = tk.Tk()
root.title("Marks Grading")
# Create a label and button in the window
label = tk.Label(root, text="Grade: -")
label.pack()
button = tk.Button(root, text="Update Grade", command=lambda: update_label(int(entry.get())))
button.pack()
entry = tk.Entry(root)
entry.pack()
# Run the main loop
root.mainloop()
def count_chars(string):
letters = 0
digits = 0
specials = 0
# Example usage
input_string = "Hello, World! 123 #$%"
letters_count, digits_count, specials_count = count_chars(input_string)
import tkinter as tk
def do_nothing():
pass
# Create a menubar
menubar = tk.Menu(root)
root.config(menu=menubar)
def lowercase_count_with_print(string):
lowercase_count = 0
lowercase_chars = []
# Example usage
input_string = "Hello, World! This is a Test String."
lowercase_count_with_print(input_string)
33. Initialise a string “python programming something” and print the substring from index 7 to 18
# Initialize the string
string = "python programming something"
34. Write, read, append in file and handle IOError and filenotfounderror
# Example usage
file_name = "example.txt"
initial_content = "Initial content."
new_content = "\nNew content appended."
35. Take number from user, and print if the number is even or odd.
def find_longest_word(text):
words = text.split() # Split the text into words
longest_word = max(words, key=len) # Find the longest word using max() and len()
return longest_word
# Example text
text = "Python is a versatile programming language with a wide range of applications."
# Add title
plt.title('Market Share Distribution')
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Parent class 1
class ParentClass1:
def method1(self):
print("Method 1 from ParentClass1")
# Parent class 2
class ParentClass2:
def method2(self):
print("Method 2 from ParentClass2")
# Example usage
try:
get_valid_input()
except CustomInputError as e:
print("CustomInputError:", e.message)
43. print the sum of all elements in list using recursive function
def recursive_sum(lst):
if not lst:
return 0 # Base case: if the list is empty, return 0
else:
return lst[0] + recursive_sum(lst[1:]) # Add the first element to the sum of the rest
# Example list
numbers = [1, 2, 3, 4, 5]
# Calculate the sum using the recursive function
result = recursive_sum(numbers)
print("Sum of elements in the list:", result)
import tkinter as tk
# Create the main window
root = tk.Tk()
root.title("Colored Window")
# Set the background color of the window
root.configure(bg='lightblue')
# Run the main event loop
root.mainloop()
45. Apply string slicing and then reverse the sliced string. (SSome string will be given)
# Given string
# Print the original string, sliced string, and reversed sliced string
46. implement a program by filtering out even numbers from a list using filter and lambda function
# List of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Use filter and lambda function to filter out even numbers
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
# Print the filtered even numbers
print("Original list:", numbers)
print("Even numbers:", even_numbers)
47. Filter one list from another list and print the new list.
class Person:
def _init_(self, name, age):
self.name = name
self.age = age
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")
# Creating instances of the Person class
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
# Calling the display_info method for each instance
person1.display_info()
person2.display_info()
def generate_multiplication_table(num):
print(f"Multiplication Table for {num}:")
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
def is_prime(number):
if number <= 1:
return False
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return False
return True
# Generate and display multiplication table for a given number
number_for_table = 7
generate_multiplication_table(number_for_table)
50. give input in text file and calc sum of all given no. also throw value error if any
def calculate_sum_from_file(file_name):
total_sum = 0
try:
with open(file_name, 'r') as file:
for line in file:
try:
number = int(line.strip())
total_sum += number
except ValueError:
print(f"ValueError: '{line.strip()}' is not a valid number.")
except FileNotFoundError:
print(f"Error: File '{file_name}' not found.")
else:
print("Sum of numbers in the file:", total_sum)
def count_words_in_file(file_name):
try:
with open(file_name, 'r') as file:
content = file.read()
words = content.split()
word_count = len(words)
return word_count
except FileNotFoundError:
print(f"Error: File '{file_name}' not found.")
return None
# Provide the file name as input
file_name = "sample.txt"
word_count = count_words_in_file(file_name)
if word_count is not None:
print(f"Number of words in '{file_name}': {word_count}")
def read_file(file_name):
try:
with open(file_name, 'r') as file:
content = file.read()
return content
except FileNotFoundError:
print(f"Error: File '{file_name}' not found.")
return None
except IOError:
print(f"Error: Unable to read file '{file_name}'.")
return None
# Provide the file name as input
file_name = "sample.txt"
file_content = read_file(file_name)
if file_content is not None:
print(f"Content of '{file_name}':\n{file_content}")
53. make a GUI using tkinter and create a label and change its text font, size and make it bold
import tkinter as tk
root = tk.Tk()
root.title("Custom Label")
label.pack(padx=20, pady=20)
root.mainloop()
54. ZeroDivisionError and ValueError
# Example usage
division_operation(10, 2) # Normal division
division_operation(5, 0) # Division by zero (ZeroDivisionError)
division_operation("abc", 2) # Invalid input (ValueError)
55. Raise exception using decorator & type checking using decorator
def type_check(*types):
def decorator(func):
return wrapper
return decorator
@type_check(int, str)
greet(25, "Alice")
greet("Bob", 30)
1. 2Write a Python program to draw a scatter plot with empty circles taking a random distribution in X
and Y and plotted against each other.
2. Write a Python program to draw a scatter plot using random distributions to generate balls of
different sizes.
3. Write a Python program to draw a scatter plot comparing two subject marks of Mathematics
and Science. Use marks of 10 students.
Sample data:math_marks = [88, 92, 80, 89, 100, 80, 60, 100, 80, 34]science_marks = [35, 79, 79, 48,
100, 88, 32, 45, 20, 30]marks_range
= [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
5. Write a Python script to check whether a given key already exists in a dictionary.
6. Write a Python script to generate and print a dictionary that contains a number (between 1 and
n) in the form (x, x*x).Sample Dictionary
( n = 5) : Expected Output : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
def generate_dict(n):
return {x: x*x for x in range(1, n+1)}
# Test the function
n=5
print(generate_dict(n))
10. Write a Python program to create a dictionary from a string. Note: Track the count of the
letters from the string.
def string_to_dict(s):
return {char: s.count(char) for char in set(s)}
# Test the function
s = "hello world"
print(string_to_dict(s))
11. Write a program that takes a sentence as an input parameter where each word in the sentence
is separated by a space. Then replace each blank with a hyphen and then print the modified
sentence.
def replace_spaces_with_hyphens(sentence):
modified_sentence = sentence.replace(' ', '-')
print(modified_sentence)
# Test the function
sentence = "This is a test sentence."
replace_spaces_with_hyphens(sentence)
12. Write a program to randomly select 10 integer elements from range 100 to 200 and find the
smallest among all.
import random
def find_smallest_random():
numbers = random.sample(range(100, 201), 10)
print(f"Randomly selected numbers: {numbers}")
smallest = min(numbers)
print(f"Smallest number: {smallest}")
# Run the function
find_smallest_random()
13. Create a dictionary of 5 countries with their currency details and display them.
Print as below
First line
Second line
Third Line
def create_country_currency_dict():
country_currency = {
"USA": "Dollar",
"UK": "Pound Sterling",
"Japan": "Yen",
"India": "Rupee",
"Australia": "Australian Dollar"
}
print("First line: USA, Currency: " + country_currency["USA"])
print("Second line: UK, Currency: " + country_currency["UK"])
print("Third line: Japan, Currency: " + country_currency["Japan"])
# Run the function
create_country_currency_dict()
14. Declare complex number , find data type, real part, imaginary part, complex conjugate,
absolute value of a number
def complex_number_operations():
# Declare a complex number
num = 3 + 4j
# Find and print data type
print(f"Data type: {type(num)}")
# Find and print real part
print(f"Real part: {num.real}")
# Find and print imaginary part
print(f"Imaginary part: {num.imag}")
# Find and print complex conjugate
print(f"Complex conjugate: {num.conjugate()}")
# Find and print absolute value
print(f"Absolute value: {abs(num)}")
# Run the function
complex_number_operations()
15. Change string hello to help ,remove white spaces before word if s=” hello ”
def modify_string(s):
s = s.strip() # Remove leading and trailing white spaces
s = s.replace('hello', 'help') # Replace 'hello' with 'help'
print(s)
# Test the function
s = " hello "
modify_string(s)
16. Write a program to randomly select 10 integer elements from range 100 to 200 and find the
smallest among all.
import random
def find_smallest_random():
numbers = random.sample(range(100, 201), 10)
print(f"Randomly selected numbers: {numbers}")
smallest = min(numbers)
print(f"Smallest number: {smallest}")
# Run the function
find_smallest_random()
def swap_first_last(s):
if len(s) < 2:
return s
return s[-1] + s[1:-1] + s[0]
# Test the function
s = "hello"
print(swap_first_last(s))
def replace_spaces_with_hyphens(sentence):
modified_sentence = sentence.replace(' ', '-')
print(modified_sentence)
# Test the function
sentence = "This is a test sentence."
replace_spaces_with_hyphens(sentence)
def is_palindrome(s):
return s == s[::-1]
# Test the function
s = "radar"
print(is_palindrome(s))
21. WAP to capitalize the first character of each words from a given sentence (example: all the
best All The Best)
def capitalize_first_char(sentence):
capitalized_sentence = ' '.join(word.capitalize() for word in sentence.split())
print(capitalized_sentence)
# Test the function
sentence = "all the best"
capitalize_first_char(sentence)
22. WAP to count the frequency of occurrence of a given character in a given line of text
23. Create a dictionary of 4 states with their capital details & add one more pair to the same
def create_state_capital_dict():
state_capital = {
"California": "Sacramento",
"Texas": "Austin",
"Florida": "Tallahassee",
"New York": "Albany"
}
# Add one more pair
state_capital["Washington"] = "Olympia"
print(state_capital)
# Run the function
create_state_capital_dict()
24. To count number digits, special symbols from the given sentence. Also count number of
vowels and consonants
def count_elements(sentence):
digits = sum(c.isdigit() for c in sentence)
special_symbols = sum(c.isalnum() == False and c.isspace() == False for c in sentence)
vowels = sum(c.lower() in 'aeiou' for c in sentence)
consonants = sum(c.isalpha() and c.lower() not in 'aeiou' for c in sentence)
print(f"Number of digits: {digits}")
print(f"Number of special symbols: {special_symbols}")
print(f"Number of vowels: {vowels}")
print(f"Number of consonants: {consonants}")
# Test the function
sentence = "Hello, World! 123"
count_elements(sentence)
25. Write a program to accept any string up to 15 characters. Display the elements of string with
their element nos
def display_elements():
s = input("Enter a string (up to 15 characters): ")
if len(s) > 15:
print("The string is too long.")
else:
for i, char in enumerate(s, start=1):
print(f"Element {i}: {char}")
# Run the function
display_elements()
import numpy as np
def create_ones_array(shape):
ones_array = np.ones(shape)
print(ones_array)
# Test the function
shape = (3, 3)
create_ones_array(shape)
import numpy as np
def contains_row(matrix, row):
return any((matrix == row).all(1))
# Test the function
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
row = np.array([4, 5, 6])
print(contains_row(matrix, row))
28. Compute mathematical operations on Array, Add & Multiply two matrices
import numpy as np
def matrix_operations():
# Create two matrices
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
# Add the matrices
sum_matrix = np.add(matrix1, matrix2)
print(f"Sum of matrices:\n{sum_matrix}")
# Multiply the matrices
product_matrix = np.dot(matrix1, matrix2)
print(f"Product of matrices:\n{product_matrix}")
# Run the function
matrix_operations()
import numpy as np
from scipy import stats
def most_frequent_value(arr):
mode = stats.mode(arr)
if np.isscalar(mode.mode):
print(f"Most frequent value: {mode.mode}")
else:
print(f"Most frequent value: {mode.mode[0]}")
# Test the function
arr = np.array([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])
most_frequent_value(arr)
import numpy as np
def flatten_array(arr):
flattened_array = arr.flatten()
print(flattened_array)
# Test the function
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
flatten_array(arr)
import numpy as np
def sum_columns(arr):
column_sums = np.sum(arr, axis=0)
print(column_sums)
# Test the function
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
sum_columns(arr)
32. Calculate the average, variance and standard deviation in Python using NumPy
import numpy as np
def calculate_statistics(arr):
average = np.mean(arr)
variance = np.var(arr)
standard_deviation = np.std(arr)
print(f"Average: {average}")
print(f"Variance: {variance}")
print(f"Standard Deviation: {standard_deviation}")
# Test the function
arr = np.array([1, 2, 3, 4, 5])
calculate_statistics(arr)
33. Insert a space between characters of all the elements of a given NumPy array ['Python' 'is'
'easy'] ['P y t h o n' 'i s' 'e a s y']
import numpy as np
def insert_spaces(arr):
spaced_arr = [' '.join(list(word)) for word in arr]
print(spaced_arr)
# Test the function
arr = np.array(['Python', 'is', 'easy'])
insert_spaces(arr)
import numpy as np
import matplotlib.pyplot as plt
# Create a NumPy array
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
# Plot the array
plt.plot(arr)
plt.title('Line graph from NumPy array')
plt.xlabel('Index')
plt.ylabel('Value')
plt.show()
def reverse_number(n):
reversed_number = int(str(n)[::-1])
return reversed_number
# Test the function
n = 12345
print(f"Original number: {n}")
print(f"Reversed number: {reverse_number(n)}")
36. WAP to read number N and print natural numbers summation pattern
def print_summation_pattern(n):
for i in range(1, n+1):
print(' + '.join(str(j) for j in range(1, i+1)), "=", sum(range(1, i+1)))
# Test the function
N=5
print_summation_pattern(N)
def find_pythagorean_triplets(limit):
triplets = []
for a in range(1, limit+1):
for b in range(a, limit+1):
c = (a*2 + b2)*0.5
if c.is_integer() and c <= limit:
triplets.append((a, b, int(c)))
return triplets
# Test the function
limit = 20
print(f"Pythagorean triplets up to {limit}:")
for triplet in find_pythagorean_triplets(limit):
print(triplet)
38. WAP, You are given a number A which contains only digits 0's and 1's. Your task is to make
all digits same by just flipping one digit (i.e.0 to 1 or 1 to 0 ) only. If it is possible to make all
the digits same by just flipping one digit then print 'YES' else print 'NO'.
def can_flip_to_same_digits(A):
digit_str = str(A)
zero_count = digit_str.count('0')
one_count = digit_str.count('1')
if zero_count == 1 or one_count == 1:
print('YES')
else:
print('NO')
# Test the function
A = 101
can_flip_to_same_digits(A)
39. Given a list A of N distinct integer numbers, you can sort the list by moving an element to the
end of the list. Find the minimum number of moves required to sort the list using this method
in ascending order
def min_moves_to_sort(A):
sorted_A = sorted(A)
i=j=0
max_len = 0
while i < len(A) and j < len(A):
if A[i] == sorted_A[j]:
i += 1
j += 1
max_len = max(max_len, j)
else:
i += 1
return len(A) - max_len
# Test the function
A = [1, 3, 2, 4, 5]
print(f"Minimum number of moves to sort the list: {min_moves_to_sort(A)}")
42. Check how many times a given number can be divided by 6 before it is less than or equal to
10.
def count_divisions_by_six(n):
count = 0
while n > 10:
n /= 6
count += 1
return count
# Test the function
n = 720
print(f"Number of times {n} can be divided by 6 before it is less than or equal to 10:
{count_divisions_by_six(n)}")
43. Python program to read a file and Capitalize the first letter of every word in the file.
def capitalize_words_in_file(filename):
with open(filename, 'r') as file:
lines = file.readlines()
capitalized_lines = [' '.join(word.capitalize() for word in line.split()) for line in lines]
with open(filename, 'w') as file:
file.writelines(capitalized_lines)
# Test the function
# Please replace 'test.txt' with your actual file name
capitalize_words_in_file('q2.py')
44. Python program that reads a text file and counts number of times certain letter appears in the
text file.
45. Write a program to write content to file & append data to file.
def read_file_contents(filename):
with open(filename, 'r') as file:
contents = file.read()
return contents
# Test the function
# Please replace 'test.txt' with your actual file name
filename = 'test.txt'
print(read_file_contents(filename))
48. WAP to accept name and roll number of students and store it in file. Read and display the
stored data. Also check if file exists or not
import os
def store_and_display_student_data(filename):
# Accept student data
name = input("Enter student's name: ")
roll_number = input("Enter student's roll number: ")
# Store student data in file
with open(filename, 'w') as file:
file.write(f"Name: {name}\nRoll Number: {roll_number}\n")
# Check if file exists
if not os.path.exists(filename):
print(f"File {filename} does not exist.")
return
# Read and display the stored data
with open(filename, 'r') as file:
contents = file.read()
print(f"Stored data:\n{contents}")
# Test the function
# Please replace 'student_data.txt' with your actual file name
filename = 'student_data.txt'
store_and_display_student_data(filename)
49. WAP to copy contents of 1 file to another Let user specify name of source and destination
files
def copy_file_contents():
# Get source and destination filenames from user
source_filename = input("Enter the name of the source file: ")
destination_filename = input("Enter the name of the destination file: ")
# Copy contents from source file to destination file
with open(source_filename, 'r') as source_file:
contents = source_file.read()
with open(destination_filename, 'w') as destination_file:
destination_file.write(contents)
print(f"Contents of {source_filename} have been copied to {destination_filename}.")
copy_file_contents()
def read_file_word_by_word(filename):
with open(filename, 'r') as file:
for line in file:
for word in line.split():
print(word)
# Test the function
# Please replace 'test.txt' with your actual file name
filename = 'test.txt'
read_file_word_by_word(filename)
def read_file_char_by_char(filename):
with open(filename, 'r') as file:
while True:
char = file.read(1)
if not char:
break
print(char)
# Test the function
# Please replace 'test.txt' with your actual file name
filename = 'test.txt'
read_file_char_by_char(filename)
52. Python – Get number of characters, words, spaces and lines in a file
def get_file_stats(filename):
num_chars = num_words = num_spaces = num_lines = 0
with open(filename, 'r') as file:
for line in file:
num_lines += 1
num_chars += len(line)
num_words += len(line.split())
num_spaces += line.count(' ')
print(f"Number of characters: {num_chars}")
print(f"Number of words: {num_words}")
print(f"Number of spaces: {num_spaces}")
print(f"Number of lines: {num_lines}")
# Test the function
# Please replace 'test.txt' with your actual file name
filename = 'test.txt'
get_file_stats(filename)
53. Make your exception class “InvalidMarks” which is thrown when marks obtained by student
exceeds 100
class InvalidMarks(Exception):
pass
def check_marks(marks):
if marks > 100:
raise InvalidMarks("Marks cannot exceed 100.")
# Test the function
# Please replace 105 with the actual marks obtained by the student
marks = 105
try:
check_marks(marks)
except InvalidMarks as e:
print(e)
54. WAP that accepts the values of a, b, c and d. Calculate and display ((a+d) + (b*c))/ (b*d).
create user defined exception to display proper message when value of (b*d) is zero
class DivisionByZeroError(Exception):
pass
def calculate_expression(a, b, c, d):
if b * d == 0:
raise DivisionByZeroError("The value of (b*d) cannot be zero.")
return ((a + d) + (b * c)) / (b * d)
# Test the function
# Please replace 1, 2, 3, 4 with your actual values for a, b, c, d
a, b, c, d = 1, 2, 3, 0
try:
result = calculate_expression(a, b, c, d)
print(result)
except DivisionByZeroError as e:
print(e)
55. Ask user to input an age. Raise an exception for age less than 18 , print message “ age is not
valid ” & “age is valid ” if age entered is more than 18
class InvalidAgeError(Exception):
pass
def check_age():
age = int(input("Enter your age: "))
if age < 18:
raise InvalidAgeError("Age is not valid.")
else:
print("Age is valid.")
# Test the function
try:
check_age()
except InvalidAgeError as e:
print(e)
def read_file(filename):
try:
with open(filename, 'r') as file:
print(file.read())
except FileNotFoundError:
print(f"The file '{filename}' does not exist.")
# Test the function
# Please replace 'non_existent_file.txt' with your actual file name
filename = 'non_existent_file.txt'
read_file(filename)
def check_string(x):
if not isinstance(x, str):
raise TypeError("The input must be a string.")
# Test the function
# Please replace 123 with your actual input
x = 123
try:
check_string(x)
except TypeError as e:
print(e)
58. Create class Complex , define two methods init to take real & imaginary number & method
add to add real & imaginary part of complex number . print addition of real part & addition of
imaginary part.
class Complex:
def _init_(self, real, imag):
self.real = real
self.imag = imag
def add(self, other):
real_sum = self.real + other.real
imag_sum = self.imag + other.imag
return real_sum, imag_sum
# Test the class
# Please replace 1, 2, 3, 4 with your actual real and imaginary numbers
c1 = Complex(1, 2)
c2 = Complex(3, 4)
real_sum, imag_sum = c1.add(c2)
print(f"Addition of real parts: {real_sum}")
print(f"Addition of imaginary parts: {imag_sum}")
59. Create class Triangle, Create object from it . The objects will have 3 attributes named a,b,c
that represent sides of triangle .Triangle class will have two methods init method to initialize
the sides & method to calculate perimeter of triangle from its sides . Perimeter of triangle
should be printed from outside the class
class Triangle:
def _init_(self, a, b, c):
self.a = a
self.b = b
self.c = c
def calculate_perimeter(self):
return self.a + self.b + self.c
# Test the class
# Please replace 3, 4, 5 with your actual side lengths
t = Triangle(3, 4, 5)
perimeter = t.calculate_perimeter()
print(f"Perimeter of the triangle: {perimeter}")
60. Python program to append ,delete and display elements of a list using classe
class MyList:
def _init_(self):
self.my_list = []
def append_element(self, element):
self.my_list.append(element)
def delete_element(self, element):
if element in self.my_list:
self.my_list.remove(element)
def display_elements(self):
return self.my_list
# Test the class
my_list = MyList()
my_list.append_element(1)
my_list.append_element(2)
my_list.append_element(3)
print(f"List after appending elements: {my_list.display_elements()}")
my_list.delete_element(2)
print(f"List after deleting an element: {my_list.display_elements()}")
61. Write a program to create a class which performs basic calculator operations
class Calculator:
def add(self, a, b):
return a + b
def subtract(self, a, b):
return a - b
def multiply(self, a, b):
return a * b
def divide(self, a, b):
if b == 0:
return "Error: Division by zero is not allowed."
return a / b
# Test the class
calculator = Calculator()
print(f"Addition: {calculator.add(5, 3)}")
print(f"Subtraction: {calculator.subtract(5, 3)}")
print(f"Multiplication: {calculator.multiply(5, 3)}")
print(f"Division: {calculator.divide(5, 3)}")
62. Write a Python class named Student with two attributes student_id, student_name. Add a new
attribute student_class. Create a function to display the entire attribute and their values in
Student class.
class Student:
def _init_(self, student_id, student_name, student_class):
self.student_id = student_id
self.student_name = student_name
self.student_class = student_class
def display_attributes(self):
return f"ID: {self.student_id}, Name: {self.student_name}, Class: {self.student_class}"
# Test the class
# Please replace 1, 'John Doe', '10th Grade' with your actual student details
student = Student(1, 'John Doe', '10th Grade')
print(student.display_attributes())
class StringReverser:
def reverse_words(self, s):
return ' '.join(reversed(s.split()))
# Test the class
# Please replace 'Hello World' with your actual string
string_reverser = StringReverser()
print(string_reverser.reverse_words('Hello World'))
64. Write a Python class which has two methods get_String and print_String. get_String accept a
string from the user and print_String print the string in upper case
class StringHandler:
def _init_(self):
self.str1 = ""
def get_string(self, user_input):
self.str1 = user_input
def print_string(self):
print(self.str1.upper())
# Test the class
# Please replace 'Hello World' with your actual string
string_handler = StringHandler()
string_handler.get_string('Hello World')
string_handler.print_string()
65. Write a Python class named Circle constructed by a radius and two methods which will
compute the area and the perimeter of a circle.
import math
class Circle:
def _init_(self, radius):
self.radius = radius
def compute_area(self):
return math.pi * (self.radius ** 2)
def compute_perimeter(self):
return 2 * math.pi * self.radius
# Test the class
# Please replace 5 with your actual radius
circle = Circle(5)
print(f"Area: {circle.compute_area()}")
print(f"Perimeter: {circle.compute_perimeter()}")
66. Write a Python program to create a Vehicle class with max_speed and mileage instance
attributes. Create a child class Bus that will inherit all of the variables and methods of the
Vehicle class
class Vehicle:
def _init_(self, max_speed, mileage):
self.max_speed = max_speed
self.mileage = mileage
class Bus(Vehicle):
pass
# Test the classes
# Please replace 120, 10 with your actual max speed and mileage
bus = Bus(120, 10)
print(f"Max Speed: {bus.max_speed}")
print(f"Mileage: {bus.mileage}")
67. Load a dataset using pandas : perform basic operations , data visualization using
matplotlib ,seaborn etc
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Load the dataset
# Please replace 'your_dataset.csv' with your actual dataset file path
df = pd.read_csv('ds.csv')
# Perform basic operations
print(df.head()) # Print the first 5 rows
print(df.describe()) # Generate descriptive statistics
# Data visualization using matplotlib
df.hist(figsize=(10, 10)) # Plot histograms for all columns
plt.show()
# Data visualization using seaborn
sns.pairplot(df) # Plot pairwise relationships in the dataset
plt.show()
68. WAPP to push all zeros to the end of a given list. The order of elements should not change:
Input: 0 2 3 4 6 7 9 0
Output:2 3 4 6 7 9 0 0
def push_zeros_to_end(lst):
result = [i for i in lst if i != 0] + [i for i in lst if i == 0]
return result
# Test the function
# Please replace [0, 2, 3, 4, 6, 7, 9, 0] with your actual list
print(push_zeros_to_end([0, 2, 3, 4, 6, 7, 9, 0]))
69. Write a program that accepts a comma separated sequence of words as input and prints the
words in a comma separated sequence after sorting them alphabetically.
Input: without, hello,bag, world
Output: bag,hello,without,world
def sort_words(input_words):
words = [word.strip() for word in input_words.split(',')]
words.sort()
return ','.join(words)
# Test the function
# Please replace 'without, hello, bag, world' with your actual sequence of words
print(sort_words('without, hello, bag, world'))
70. WAP that calculates & prints value accoridng to given formula:
Q=Square root of [(2*C*D)/H]
C is 50 , H is 30. D is variable whose values should be input to program in comma
separated sequence.
Input: 100,150,180
Output:18,22,24
import math
def calculate_values(D_values):
C = 50
H = 30
Q_values = [round(math.sqrt((2*C*D)/H)) for D in D_values]
return Q_values
# Test the function
# Please replace [100, 150, 180] with your actual D values
print(calculate_values([100, 150, 180]))
71. With given list L of integers , write a program that prints this L after removing duplicate
values with original order preserved.
Input: 12 24 35 24 88 120 155 88 120 155
Output: 12 24 35 88 120 155
def remove_duplicates(lst):
seen = set()
result = []
for item in lst:
if item not in seen:
seen.add(item)
result.append(item)
return result
# Test the function
# Please replace [12, 24, 35, 24, 88, 120, 155, 88, 120, 155] with your actual list
print(remove_duplicates([12, 24, 35, 24, 88, 120, 155, 88, 120, 155]))
72. Given ab integer number n , define function named printDict(),which can print a dictionary
where keys are numbers between 1 to n (both included) and values are square of keys .
Function printDict(), does not take any arguments.
def printDict():
n = int(input("Enter a number: "))
d = {i: i**2 for i in range(1, n+1)}
print(d)
# Test the function
printDict()
73. Python program to find the sum of the digits of an integer using while loop
def sum_of_digits(n):
sum = 0
while n > 0:
digit = n % 10
sum += digit
n //= 10
return sum
# Test the function
# Please replace 12345 with your actual integer
print(sum_of_digits(12345))
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
def generate_primes(N):
primes = []
for num in range(1, N + 1):
if is_prime(num):
primes.append(num)
return primes
N = int(input("Enter the value of N: "))
prime_numbers = generate_primes(N)
print("Prime numbers from 1 to", N, "are:", prime_numbers)
75. Python program to print the numbers from a given number n till 0 using recursion
def print_numbers(n):
if n >= 0:
print(n)
print_numbers(n - 1)
# Test the function
# Please replace 10 with your actual number
print_numbers(10)
76. Write a Python function student_data () which will print the id of a student (student_id). If the
user passes an argument student_name or student_class the function will print the student
name and class.
class RomanConverter:
def _init_(self):
self.roman_to_int = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
def convert_to_int(self, roman_numeral):
result = 0
prev_value = 0
for char in roman_numeral[::-1]:
value = self.roman_to_int[char]
if value < prev_value:
result -= value
else:
result += value
prev_value = value
return result
# Example usage
converter = RomanConverter()
roman_numeral = 'XLII'
integer_value = converter.convert_to_int(roman_numeral)
print(integer_value)
78. Write a Python class to get all possible unique subsets from a set of distinct integers
class SubsetGenerator:
def _init_(self, nums):
self.nums = nums
def generate_subsets(self):
subsets = [[]]
for num in self.nums:
subsets += [subset + [num] for subset in subsets]
return subsets
# Example usage
nums = [1, 2, 3]
generator = SubsetGenerator(nums)
all_subsets = generator.generate_subsets()
print(all_subsets)
79. Write a Python class to find a pair of elements (indices of the two numbers) from a given
array whose sum equals a specific target number
class PairFinder:
def find_pair(self, nums, target):
num_dict = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_dict:
return [num_dict[complement], i]
num_dict[num] = i
return None
# Example usage
nums = [2, 7, 11, 15]
target = 9
pair_finder = PairFinder()
result = pair_finder.find_pair(nums, target)
if result:
print(f"Pair found at indices {result[0]} and {result[1]}")
else:
print("No pair found")
class Power:
def _init_(self, x, n):
self.x = x
self.n = n
def calculate(self):
return self.x ** self.n
# Test the class
# Please replace 2 and 3 with your actual x and n
p = Power(2, 3)
print(p.calculate())
81. Write a NumPy program to convert the values of Centigrade degrees into Fahrenheit degrees
and vice versa. Values are stored into a NumPy array. Sample Array [0, 12, 45.21, 34, 99.91]
import numpy as np
def convert_temperatures(temps, scale_to):
if scale_to.lower() == 'fahrenheit':
return np.array(temps) * 9/5 + 32
elif scale_to.lower() == 'centigrade':
return (np.array(temps) - 32) * 5/9
else:
return "Invalid scale_to argument. It should be either 'Fahrenheit' or 'Centigrade'."
# Test the function
# Please replace [0, 12, 45.21, 34, 99.91] with your actual temperatures and 'Fahrenheit' with your
actual scale_to
print(convert_temperatures([0, 12, 45.21, 34, 99.91], 'Fahrenheit'))
82. Write a NumPy program to find the set difference of two arrays. The set difference will return
the sorted, unique values in array1 that are not in array2
import numpy as np
def set_difference(array1, array2):
return np.setdiff1d(array1, array2)
# Test the function
# Please replace [0, 10, 20, 40, 60, 80] and [10, 30, 40, 50, 70] with your actual arrays
print(set_difference([0, 10, 20, 40, 60, 80], [10, 30, 40, 50, 70]))
83. Write a Pandas program to create and display a DataFrame from a specified dictionary data
which has the index labels. Go to the editor Sample Python dictionary data and list labels:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura',
'Kevin', 'Jonas'], 'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']} labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'
import pandas as pd
import numpy as np
exam_data = {
'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin',
'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']
}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data, index=labels)
print(df)
84. Write a Pandas program to get the first 3 rows of a given DataFrame
import pandas as pd
# Create a dictionary of data
data = {
'Name': ['John', 'Anna', 'Peter', 'Linda', 'James'],
'Age': [28, 24, 35, 32, 30],
'City': ['New York', 'Paris', 'Berlin', 'London', 'Sydney']
}
85. Write a Pandas program to select the 'name' and 'score' columns from the following
DataFrame.
import pandas as pd
# Create a dictionary of data
data = {
'name': ['John', 'Anna', 'Peter', 'Linda', 'James'],
'score': [85, 90, 88, 92, 87],
'age': [28, 24, 35, 32, 30]
}
# Create a DataFrame from the dictionary
df = pd.DataFrame(data)
# Select 'name' and 'score' columns
selected_columns = df[['name', 'score']]
print(selected_columns)
86. Write a Pandas program to select the specified columns and rows from a given data frame.
import pandas as pd
# Create a dictionary of data
data = {
'name': ['John', 'Anna', 'Peter', 'Linda', 'James', 'Michael', 'Sarah', 'Jessica', 'Jacob', 'Emma'],
'score': [85, 90, 88, 92, 87, 95, 78, 88, 92, 85],
'age': [28, 24, 35, 32, 30, 27, 29, 31, 23, 25]
}
# Create a DataFrame from the dictionary
df = pd.DataFrame(data)
# Select 'name' and 'score' columns for the 2nd, 4th, and 6th rows
selected_data = df[['name', 'score']].iloc[[1, 3, 5]]
print(selected_data)
87. Write a Pandas program to select the rows where the number of attempts in the examination is
greater than 2.
import pandas as pd
# Create a dictionary of data
data = {
'name': ['John', 'Anna', 'Peter', 'Linda', 'James'],
'score': [85, 90, 88, 92, 87],
'attempts': [3, 2, 4, 3, 5]
}
# Create a DataFrame from the dictionary
df = pd.DataFrame(data)
# Select rows where the number of attempts is greater than 2
selected_rows = df[df['attempts'] > 2]
print(selected_rows)
88. Write a Pandas program to count the number of rows and columns of a DataFrame.
import pandas as pd
# Create a dictionary of data
data = {
'name': ['John', 'Anna', 'Peter', 'Linda', 'James'],
'score': [85, 90, 88, 92, 87],
'attempts': [3, 2, 4, 3, 5]
}
# Create a DataFrame from the dictionary
df = pd.DataFrame(data)
# Count the number of rows and columns
num_rows = len(df)
num_cols = len(df.columns)
print("Number of Rows: ", num_rows)
print("Number of Columns: ", num_cols)
89. Write a Pandas program to select the rows the score is between 15 and 20 (inclusive).
import pandas as pd
# Create a dictionary of data
data = {
'name': ['John', 'Anna', 'Peter', 'Linda', 'James'],
'score': [15, 20, 14, 18, 16],
'attempts': [3, 2, 1, 3, 2]
}
# Create a DataFrame from the dictionary
df = pd.DataFrame(data)
# Select rows where the score is between 15 and 20
selected_rows = df[(df['score'] >= 15) & (df['score'] <= 20)]
print(selected_rows)
90. Write a Pandas program to select the rows where number of attempts in the examination is
less than 2 and score greater than 15
import pandas as pd
# Create a dictionary of data
data = {
'name': ['John', 'Anna', 'Peter', 'Linda', 'James'],
'score': [18, 20, 14, 22, 16],
'attempts': [1, 2, 1, 3, 1]
}
# Create a DataFrame from the dictionary
df = pd.DataFrame(data)
# Select rows where the number of attempts is less than 2 and score is greater than 15
selected_rows = df[(df['attempts'] < 2) & (df['score'] > 15)]
print(selected_rows)
91. Write a Pandas program to append a new row 'k' to data frame with given values for each
column. Now delete the new row and return the original DataFrame
import pandas as pd
# Create a dictionary of data
data = {
'name': ['John', 'Anna', 'Peter', 'Linda', 'James'],
'score': [18, 20, 14, 22, 16],
'attempts': [1, 2, 1, 3, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'yes']
}
# Create a DataFrame from the dictionary
df = pd.DataFrame(data)
# Append a new row 'k' with given values
df.loc['k'] = ['Suresh', 15.5, 1, 'yes']
# Print DataFrame after appending
print("After appending a new row:\n", df)
# Delete the new row and return the original DataFrame
df = df.drop('k')
# Print DataFrame after deleting the new row
print("After deleting the new row:\n", df)
92. Write a Pandas program to sort the DataFrame first by 'name' in descending order, then by
'score' in ascending order.
import pandas as pd
# Create a dictionary of data
data = {
'name': ['John', 'Anna', 'Peter', 'Linda', 'James'],
'score': [18, 20, 14, 22, 16],
'attempts': [1, 2, 1, 3, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'yes']
}
# Create a DataFrame from the dictionary
df = pd.DataFrame(data)
# Sort the DataFrame first by 'name' in descending order, then by 'score' in ascending order
df = df.sort_values(by=['name', 'score'], ascending=[False, True])
print(df)
93. Write a Pandas program to replace the 'qualify' column contains the values 'yes' and 'no' with
True and False.
import pandas as pd
# Create a dictionary of data
data = {
'name': ['John', 'Anna', 'Peter', 'Linda', 'James'],
'score': [18, 20, 14, 22, 16],
'attempts': [1, 2, 1, 3, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'yes']
}
# Create a DataFrame from the dictionary
df = pd.DataFrame(data)
# Replace 'yes' and 'no' with True and False in 'qualify' column
df['qualify'] = df['qualify'].map({'yes': True, 'no': False})
print(df)
94. Write a Pandas program to set a given value for particular cell in DataFrame using index
value.
import pandas as pd
# Create a dictionary of data
data = {
'name': ['John', 'Anna', 'Peter', 'Linda', 'James'],
'score': [18, 20, 14, 22, 16],
'attempts': [1, 2, 1, 3, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'yes']
}
# Create a DataFrame from the dictionary
df = pd.DataFrame(data)
# Set a given value for a particular cell using the index value
df.at[1, 'score'] = 25
print(df)