King Uuuuuuu
King Uuuuuuu
print("Addition:", addition)
print("Subtraction:", subtraction)
print("Multiplication:", multiplication)
print("Division:", division)
largest = num1
largest = num2
else:
largest = num3
if number % 2 == 0:
else:
print(f"{number} is an Odd number.")
else:
sum_of_digits = 0
original_num = num
reversed_num = 0
if original_num == reversed_num:
else:
is_prime = True
if num % i == 0:
is_prime = False
break
if is_prime:
else:
else:
print(f"{num} is not a Prime number.") # Numbers less than 2 are not prime
a, b = 0, 1
count = 0
if n <= 0:
elif n == 1:
else:
next_term = a + b
a=b
b = next_term
count = count + 1
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
# Recursive approach
def fibonacci_recursive(n):
if n <= 1:
return n
else:
import math
import datetime
# Using the math module to calculate the square root and factorial
sqrt_value = math.sqrt(number)
factorial_value = math.factorial(number)
# Using the datetime module to display the current date and time
current_datetime = datetime.datetime.now()
print(f"Current date and time: {current_datetime}")
# Creating a list
numbers = [1, 2, 3, 4, 5]
numbers.append(6)
numbers.remove(3)
numbers.sort()
# Creating a list
elements = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
frequency = {}
if item in frequency:
frequency[item] = frequency[item] + 1
else:
frequency[item] = 1
# Creating a tuple
my_tuple = (1, 2, 3, 4, 5)
new_element = 6
print(item)
Week 5:Dictionaries and Sets
# Creating a dictionary
my_dict["occupation"] = "Engineer"
my_dict["age"] = 31
removed_value = my_dict.pop("city")
print(f"{key}: {value}")
print("Dictionary of squares:")
print(squares)
# Creating a set
my_set = {1, 2, 3, 4, 5}
my_set.add(6)
my_set.remove(3) # Using remove() will raise an error if the element is not found
another_set = {4, 5, 6, 7, 8}
union_set = my_set.union(another_set)
intersection_set = my_set.intersection(another_set)
difference_set = my_set.difference(another_set)
words = file.read().split()
lines = source_file.readlines()
destination_file.write(line)
Lab Exercise 7.1: Program using try, except, else, and finally blocks
try:
except TypeError:
else:
finally:
divide_numbers(num1, num2)
Example inputs
divide_numbers(10, 2)
divide_numbers(10, 0)
divide_numbers(10, "a")
try:
except ZeroDivisionError:
except TypeError:
except Exception as e:
else:
finally:
def get_number_input(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
# Handle the case where conversion to float fails
# Main program
divide_numbers(num1, num2)
class Shape:
self.name = name
def area(self):
pass
def perimeter(self):
pass
class Circle(Shape):
super().__init__("Circle")
self.radius = radius
def area(self):
def perimeter(self):
class Rectangle(Shape):
self.length = length
self.width = width
def area(self):
def perimeter(self):
circle = Circle(5)
rectangle = Rectangle(4, 7)
# Base class
class Vehicle:
self.make = make
self.model = model
self.year = year
def display_info(self):
# Derived class
class Car(Vehicle):
self.doors = doors
def display_info(self):
# Main program
def main():
if __name__ == "__main__":
main()
Week 9:Libraries and packages
import numpy as np
import pandas as pd
print("NumPy Array:")
print(data)
df = pd.DataFrame(data, columns=columns)
print("\nPandas DataFrame:")
print(df)
mean_values = df.mean()
print("\nMean Values:")
print(mean_values)
print(filtered_df)
output:
NumPy Array:
[[45 48 65]
[68 68 68]
[10 84 77]
[87 70 88]
[83 64 80]
[19 54 82]
[55 65 53]
[69 68 62]
[87 60 74]
[84 53 23]]
Pandas DataFrame:
A B C
0 45 48 65
1 68 68 68
2 10 84 77
3 87 70 88
4 83 64 80
5 19 54 82
6 55 65 53
7 69 68 62
8 87 60 74
9 84 53 23
Mean Values:
A 57.6
B 61.8
C 69.6
dtype: float64
A B C Sum
3 87 70 88 245
4 83 64 80 227
5 19 54 82 155
8 87 60 74 221
A B C Sum
3 87 70 88 245
4 83 64 80 227
5 19 54 82 155
8 87 60 74 221
math_operations/
├── math_ops/
│ ├── __init__.py
│ ├── addition.py
│ ├── subtraction.py
│ ├── multiplication.py
│ └── division.py
└── setup.py
1. math_ops/addition.py
2. math_ops/subtraction.py
def subtract(a, b):
"""Return the difference of two numbers."""
return a - b
3. math_ops/multiplication.py
def multiply(a, b):
"""Return the product of two numbers."""
return a * b
4. math_ops/division.py
def divide(a, b):
"""Return the quotient of two numbers. Raise ValueError if dividing by zero."""
if b == 0:
raise ValueError("Cannot divide by zero.")
return a / b
5.math_ops/__init__.py
from .addition import add
from .subtraction import subtract
from .multiplication import multiply
from .division import divide
setup(
name='math_operations',
version='0.1',
packages=find_packages(),
description='A simple package for basic mathematical operations',
author='Your Name',
author_email='your.email@example.com',
)
pip install .
test_math_operations.py
try:
except ValueError as e:
print(e)
python test_math_operations.py
Example Output
Addition: 5 + 3 = 8
Subtraction: 5 - 3 = 2
Multiplication: 5 * 3 = 15
Division: 5 / 2 = 2.5
Write a Program Demonstrating Data Loading, Manipulation, and Visualization using Pandas,
Matplotlib, and Seaborn.
import pandas as pd
# Step 1: Load the dataset (for this example, we'll create a simple dataset)
data = {
# Create a DataFrame
df = pd.DataFrame(data)
average_salary = df['Salary'].mean()
print(older_employees)
plt.figure(figsize=(8, 5))
plt.title('Employee Salaries')
plt.xlabel('Employee Name')
plt.ylabel('Salary')
plt.show()
Example Output:
2 Peter 35 102000
3 Linda 32 56000
5 James 30 75000