Skip to content

peace-adamu/PLP-Python-Assignments

Repository files navigation

PLP-Python-Assignment

Table of Content

Week 1 Assignment

Instructions:

  • Create a new Python file and name it "user_input.py"
  • Use the input() function to ask the user for their name and store it in a variable called "name".
  • Use the input() function to ask the user for their age and store it in a variable called "age".
  • Use the input() function to ask the user for their location and store it in a variable called "location".
  • Print out a personalized message using the user's name, age, and location. For example: "Hello [name], you are [age] years old and live in [location]."
  • Save and run the program to see the output.

Assignment solution

code

# Use the input() function to ask the user for their name and store it in a variable called "name".
name = input('Enter your name: ')

# Use the input() function to ask the user for their age and store it in a variable called "age"
age = input('What is your age: ')

# Use the input() function to ask the user for their location and store it in a variable called "location".
location = input('Give details of your location: ')

# Print out a personalized message using the user's name, age, and location. For example: "Hello [name], you are [age] years old and live in [location]."
print(f"Hello {name}, you are {age} years old and live in {location}")

Week 2 Assignment

Instructions:

  1. Create an empty list calledΒ my_list.
  2. Append the following elements toΒ my_list: 10, 20, 30, 40.
  3. Insert the valueΒ 15Β at the second position in the list.
  4. ExtendΒ my_listΒ with another list:Β [50, 60, 70].
  5. Remove the last element fromΒ my_list.
  6. SortΒ my_listΒ in ascending order.
  7. Find and print the index of the valueΒ 30Β inΒ my_list.

Assignment solution

1. # Create an empty list calledΒ my_list.
my_list = [] 

2.# Append the following elements toΒ my_list: 10, 20, 30, 40.
my_list.append(10)
my_list.append(20)
my_list.append(30)
my_list.append(40)

print(my_list)

3. # Insert the valueΒ 15Β at the second position in the list.
my_list.insert(1, 15)
print(my_list) 

4. # ExtendΒ my_listΒ with another list:Β [50, 60, 70].
my_list.extend([50, 60, 70])
print(my_list)

5. # Remove the last element fromΒ my_list
my_list.pop()
print(my_list)

6.# SortΒ my_listΒ in ascending order.
my_list.sort()
print(my_list) 

7. # Find and print the index of the valueΒ 30Β inΒ my_list.
print(my_list[3])

Week 3 Assignment

Instructions:

  • Create a function named calculate_discount(price, discount_percent) that calculates the final price after applying a discount. The function should take the original price (price) and the discount percentage (discount_percent) as parameters. If the discount is 20% or higher, apply the discount; otherwise, return the original price. Using the calculate_discount function, prompt the user to enter the original price of an item and the discount percentage. Print the final price after applying the discount, or if no discount was applied, print the original price.

Assignment Solution

origanal_price = float(input('Enter the original price of your item: '))
discount_percent = float(input('Enter the discount percentage: '))

# Create a function named calculate_discount(price, discount_percent) 
def calculate_discount(price, discount_percent):
    
    if discount_percent >= 20:
        discount_amount = (discount_percent / 100) * price
        final_price = price - discount_amount
        return final_price
    else:
        return price 
    

def main():
    origanal_price = float(input('Enter the original price of your item: '))
    discount_percent = float(input('Enter the discount percentage: '))
    final_price = calculate_discount(origanal_price, discount_percent)

# Print the final price after applying the discount, or if no discount was applied, print the original price.
    if discount_percent >= 20:
        print(f"The final price after applying the discount is: {final_price: .2f}")
    else:
        print(f"No discount applied. The original price is: {origanal_price: .2f}")



if __name__ == "__main__":
    main()   

Week 4 Assignment

Instructions:

  1. File Read & Write Challenge πŸ–‹οΈ: Create a program that reads a file and writes a modified version to a new file.
  2. Error Handling Lab πŸ§ͺ: Ask the user for a filename and handle errors if it doesn’t exist or can’t be read.

Assignment Solution

def modified_file():
    input_file = "requirements.txt"
    output_file = "modified_file"

    try:
        with open(input_file, "r") as infile:
            document = infile.read()
            modified_document = document.upper()

        with open(output_file, "w") as outfile:
            outfile.write(modified_document)
            print(f"Modified document written to {output_file}")

    except FileNotFoundError:
        print(f"Error: File {input_file} not found")
    except IOError:
        print(f"Error: Could not read the file")
    except Exception as e:
        print(f"An unexcepted error occured: {e}")



modified_file()

Week 5 Assignment 1

Instructions:

  • Design Your Own Class! πŸ—οΈ
  • Create a class representing anything you like (a Smartphone, Book, or even a Superhero!).
  • Add attributes and methods to bring the class to life!
  • Use constructors to initialize each object with unique values.
  • Add an inheritance layer to explore polymorphism or encapsulation.

Assinment 1 Solution

# Defination amd construction a class smartphone
class smartphone:
    def __init__(self, product, battery_capacity):
        self.product = product
        self.__battery_capacity = battery_capacity  # Private variable

    # Methods for displaying specification
    def display_specs(self):
        print(f"Product: {self.product}")
        print(f"Battery Capacity: {self.__battery_capacity}mAh")
    
    # Encapsulation with Getter and Setter Methods:
    # method to access private battery capacity attribute
    def get_battery_capacity(self):
        return self.__battery_capacity

    def set_battery_capacity(self, capacity):
        if capacity > 0:
            self.__battery_capacity = capacity
        else:
            print("Invalid capacity")


# Inheritance and Polymorphism
# Defining a subclass AndroidPhone
class AndroidPhone(smartphone):
    def __init__(self, product, battery_capacity, os_version):
        super().__init__(product, battery_capacity)
        self.os_version = os_version


    def display_specs(self):
        super().display_specs()
        print(f"OS Version: {self.os_version}")

# creating objects and using methods:
my_smartphone = smartphone("Generic phone", 3000)
my_smartphone.display_specs()
print(f"Battery Capacity (accessed through method): {my_smartphone.get_battery_capacity()}")     
    
my_android = AndroidPhone("Android Phone", 4000, "Android 12")
my_android.display_specs()

Assignment 2 Instructions:

Polymorphism Challenge! 🎭
  • Create a program that includes animals or vehicles with the same action (like move()). However, make each class define move() differently (for example, Car.move() prints "Driving" πŸš—, while Plane.move() prints "Flying" ✈️).

Assignment 2 Solution

# Definition
class  Vehicle:
    def move(self):
        raise NotImplementedError("Subclasses must implement this method")


# Subclass definition
class car(Vehicle):
    def move(self):
        print("Driving")

class plane(Vehicle):
    def move(self):
        print("Flying")

class bicycle(Vehicle):
    def move(self):
        print("Pedaling") 


 # polymorphism demonstration:
def demonstrate_movement(vehicle):
    vehicle.move()

Week 7 Assignment

Instructions:

  • Choose a dataset in CSV format (for example, you can use datasets like the Iris dataset, a sales dataset, or any dataset of your choice). Load the dataset using pandas. Display the first few rows of the dataset using .head() to inspect the data. Explore the structure of the dataset by checking the data types and any missing values. Clean the dataset by either filling or dropping any missing values.
  • Task 2: Basic Data Analysis Compute the basic statistics of the numerical columns (e.g., mean, median, standard deviation) using .describe(). Perform groupings on a categorical column (for example, species, region, or department) and compute the mean of a numerical column for each group. Identify any patterns or interesting findings from your analysis.
  • Task 3: Data Visualization Create at least four different types of visualizations: Line chart showing trends over time (for example, a time-series of sales data). Bar chart showing the comparison of a numerical value across categories (e.g., average petal length per species). Histogram of a numerical column to understand its distribution. Scatter plot to visualize the relationship between two numerical columns (e.g., sepal length vs. petal length). Customize your plots with titles, labels for axes, and legends where necessary.

Assignment Solution

  • Using Iris dataset
 # Importing the library pandas

import pandas as pd

# Load the dataset using pandas:

df = pd.read_csv('C:/Users/HP/Desktop/python classes/week 6/Iris.csv')

# Display the first 10 rows of the dataset using .head():

df.head(10)

# Compute basic statistics of the numerical columns:

df.describe(include='all')

# # Fill missing values (if any)
df = df.fillna(df.mode())

# Perform groupings on a categorical column and compute the mean of a numerical column for each group:

species_mean = df.groupby('Species').mean()
print(species_mean)

# DATA VISUALIZATION
# importing the needed libraries

import matplotlib.pyplot as plt
import seaborn as sns
# pair chart showing the correction of the different species and their lengths

sns.pairplot(df)

output1

  • The pair plot displays histograms for individual variables on the diagonal and scatter plots for pairwise relationships between variables off-diagonally. It reveals the distribution of each variable and shows correlations, such as the strong positive correlation between PetalLengthCm and PetalWidthCm. This visual summary aids in understanding variable distributions and relationships, identifying correlations, and spotting outliers.
Line chart showing trends over time:
# Line chart
plt.figure(figsize=(10, 6))
species_mean['SepalLengthCm'].plot(kind='line')
plt.title('Mean Sepal Length per Species')
plt.xlabel('Species')
plt.ylabel('Mean Sepal Length')
plt.show()

output2

  • A line chart titled "Mean Sepal Length per Species," showing the mean sepal length for three Iris species: Iris-setosa, Iris-versicolor, and Iris-virginica. The chart indicates a clear upward trend, with Iris-setosa having the shortest mean sepal length and Iris-virginica having the longest. This visualization highlights the differences in mean sepal length among the species, suggesting a progression in sepal length from Setosa to Virginica.
# Line chart
plt.figure(figsize=(10, 6))
species_mean['SepalWidthCm'].plot(kind='line')
plt.title('Mean Sepal Width per Species')
plt.xlabel('Species')
plt.ylabel('Mean Sepal Length')
plt.show()

output3

  • a line chart titled "Mean Sepal Length per Species," displaying the mean sepal length for the Iris species: Iris-setosa, Iris-versicolor, and Iris-virginica. In this chart, Iris-setosa has the highest mean sepal length, followed by a sharp decrease for Iris-versicolor, which has the lowest mean sepal length. Then, there is a slight increase for Iris-virginica. This visualization shows a notable drop in mean sepal length from Iris-setosa to Iris-versicolor, with Iris-virginica having an intermediate value.
# Line chart
plt.figure(figsize=(10, 6))
species_mean['PetalLengthCm'].plot(kind='line')
plt.title('Mean Petal Length per Species')
plt.xlabel('Species')
plt.ylabel('Mean Petal Length')
plt.show()

output4

  • This line plot shows the mean petal length for each Iris species: X-axis: Represents the three Iris species (Iris-setosa, Iris-versicolor, Iris-virginica). Y-axis: Displays the average petal length for each species. The plot reveals an increasing trend in mean petal length, with Iris-setosa having the smallest (around 1.5) and Iris-virginica the largest (around 5.5). Iris-versicolor lies in the middle with a mean petal length around 4. This visualization highlights a clear distinction in petal length across species.
# Line chart
plt.figure(figsize=(10, 6))
species_mean['PetalWidthCm'].plot(kind='line')
plt.title('Mean Petal width per Species')
plt.xlabel('Species')
plt.ylabel('Mean Petal Width')
plt.show()

output5

  • The line chart titled "Mean Petal Width per Species" shows the mean petal width for three Iris species: Iris-setosa, Iris-versicolor, and Iris-virginica. The chart reveals a clear upward trend in mean petal width from Iris-setosa, which has the smallest petal width, to Iris-virginica, which has the largest. This indicates a progressive increase in petal width across the species, with Iris-versicolor having an intermediate value. The pattern suggests a consistent differentiation in petal width among the three species.
Bar chart showing the comparison of a numerical value across categories:
plt.figure(figsize=(10,6))
species_mean['SepalLengthCm'].plot(kind='bar')
plt.title("Average Sepal Length per Species")
plt.xlabel('Species')
plt.ylabel('Average Sepal Length')

output6

  • This bar chart compares the average sepal length among three Iris species: Iris-setosa, Iris-versicolor, and Iris-virginica. The chart shows that Iris-virginica has the highest average sepal length, followed by Iris-versicolor, and Iris-setosa has the shortest average sepal length. This indicates a trend where the average sepal length increases from Iris-setosa to Iris-virginica.
plt.figure(figsize=(10,6))
species_mean['SepalWidthCm'].plot(kind='bar')
plt.title("Average Sepal Width per Species")
plt.xlabel('Species')
plt.ylabel('Average Sepal Width')

output7

  • This bar chart compares the average sepal width among the same three Iris species. Here, Iris-setosa has the highest average sepal width, while Iris-virginica and Iris-versicolor have relatively lower and similar sepal widths, with Iris-versicolor being slightly less than Iris-virginica. This suggests that Iris-setosa tends to have wider sepals compared to the other two species, contrasting with the trend seen in sepal length.
plt.figure(figsize=(10,6))
species_mean['PetalWidthCm'].plot(kind='bar')
plt.title("Average Petal Width per Species")
plt.xlabel('Species')
plt.ylabel('Average Petal Width')

output8

  • This bar chart represents the average petal length for each Iris species.

Iris-setosa has the smallest average petal length, around 1.5, clearly distinct from the other two species. Iris-versicolor shows a moderate average petal length of approximately 4. Iris-virginica has the largest average petal length, exceeding 5.5. The increasing trend in petal length across species indicates a potential distinguishing feature for classification. This chart effectively highlights differences in petal length, aiding in species differentiation.

plt.figure(figsize=(10,6))
species_mean['PetalLengthCm'].plot(kind='bar')
plt.title("Average Petal Length per Species")
plt.xlabel('Species')
plt.ylabel('Average Petal Length')

output9

  • This bar chart represents the average petal length for each Iris species. Iris-setosa has the smallest average petal length, around 1.5, clearly distinct from the other two species. Iris-versicolor shows a moderate average petal length of approximately 4. Iris-virginica has the largest average petal length, exceeding 5.5. The increasing trend in petal length across species indicates a potential distinguishing feature for classification. This chart effectively highlights differences in petal length, aiding in species differentiation.
Histogram of a numerical column:
plt.figure(figsize=(10,6))
sns.histplot(df['Species'], kde=True)
plt.title("Distribution of the Species")
plt.xlabel("species")
plt.ylabel("height")

output10

  • This plot shows the distribution of Iris species using a bar chart with nearly equal heights, indicating a balanced dataset. A line plot overlays the bars, but its purpose and relation to the data are unclear. The x-axis lists species, and the y-axis represents "height," though its exact meaning needs clarification. The chart could benefit from clearer labeling and context for the line plot.
Scatter plot to visualize the relationship between two numerical columns:
#  Scatter plot to visualize the relationship between two numerical columns (e.g., sepal length vs. petal length).

plt.figure(figsize=(10,6))
sns.scatterplot(x='SepalLengthCm', y='PetalLengthCm', hue='Species', data=df)
plt.xlabel("Sepal Length")
plt.ylabel("Petal Length")
plt.title("Sepal length vs Petal")

output11

  • The scatter plot visualizes the relationship between sepal length (x-axis) and petal length (y-axis) across three Iris species, serving as a basis for species classification. Data points are color-coded by species: Iris-setosa (blue), Iris-versicolor (orange), and Iris-virginica (green), enabling easy identification of patterns. Iris-setosa forms a distinct cluster with low petal lengths, suggesting clear separation from the other two species. Both Iris-versicolor and Iris-virginica exhibit a linear trend between sepal and petal lengths, with Iris-virginica showing generally higher values. This visualization highlights potential predictors (sepal and petal lengths) for species classification in a machine learning or statistical model.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages