Sunday, 9 November 2025

Summary of Python Collections

Python Collections

Python provides several built-in collection data types that help you store and organize data efficiently.

The four main types are:

Collection Type

Ordered

Mutable

Allows Duplicates

List

Yes

Yes

Yes

Tuple

Yes

No

Yes

Set

No

Yes

No

Dictionary

Yes (Python 3.7+)

Yes

Keys must be unique

Sunday, 10 August 2025

LCM of two numbers without built-in functions

LCM of Two Numbers

LCM (Least Common Multiple) of two given numbers without using built-in math functions or user-defined functions.

# LCM of two numbers without use of built-in functions.

# Input two numbers
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

# Store the maximum of num1 and num2
if num1 > num2:
    max_num = num1
else:
    max_num = num2

# Find LCM using loop
while True:
    if (max_num % num1 == 0) and (max_num % num2 == 0):
        lcm = max_num
        break
    max_num += 1

# Display the result
print("LCM of", num1, "and", num2, "is", lcm)

Output of program

Enter first number: 5

Enter second number: 7

LCM of 5 and 7 is 35


Saturday, 9 August 2025

Python program to find LCM of Two Numbers

LCM of Two Numbers

Following python program will find the LCM of two given numbers.

import math
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
lcm = abs(a*b) // math.gcd(a, b)
print(f"LCM of {a} and {b} is {lcm}")

Output of program 

Enter first number: 5 Enter second number: 7 LCM of 5 and 7 is 35

Explanation

LCM (Least Common Multiple) is the smallest number that is divisible by both numbers.

In other words:
  • It must be a multiple of 5
  • It must be a multiple of 7
  • And it should be the smallest such number.
List multiples of each number
  • Multiples of 5: 5, 10, 15, 20, 25, 30, 35, 40, …
  • Multiples of 7: 7, 14, 21, 28, 35, 42, …
Find the first common multiple

Looking at both lists:
  • The first number that appears in both lists is 35.
So, LCM(5, 7) = 35.


Sunday, 18 August 2024

Python Nested If Examples

Nested-If Statements in Python

When we write if statements inside another if statement, it is called Nested If Statements. These can be very useful to make complex decisions in your program. They can be several levels deep. They are also a type of decision making statement in python. 

Followings are some popular examples related to usage of the python nested-if statements.

Example 1: Python program to print student's grade.

# Python program to print student's grade

score = int(input("Enter your marks:"))

if score >= 90:
    grade = 'A'
else:
    if score >= 80:
        grade = 'B'
    else:
        if score >= 70:
            grade = 'C'
        else:
            grade = 'F'

print("Grade:", grade)


Output

Enter your marks:85 Grade: B


Example 2: Python program to check weather conditions. 

# Checking Weather Conditions
temperature = 30
raining = False

if temperature > 25:
    if raining:
        print("It's warm but raining. Bring an umbrella!")
    else:
        print("It's warm and sunny. Enjoy the weather!")
else:
    if raining:
        print("It's cold and raining. Better stay indoors!")
    else:
        print("It's cold but dry. Dress warmly!")

Output

It's warm and sunny. Enjoy the weather!


Example 3: Python program to check user authentication (username and password).
 
# User Authentication
username = "admin"
password = "12345"

if username == "admin":
    if password == "12345":
        print("Access granted")
    else:
        print("Incorrect password")
else:
    print("Username not found")

Output
Access granted


Example 4: Python program to check eligibility for a loan based on given Age and Income.

# We assume that a person is eligible for loan if age is
# above 18 years and income greater than or equal to 40000.

age = int(input("Enter your age in years:"))
income = int(input("Enter your income in Rs:"))

if age > 18:
    if income > 40000:
        print("You are eligible for the loan")
    else:
        print("You are not eligible for the loan due to low income")
else:
    print("You are not eligible for the loan due to age restriction")

Output
Enter your age in years:30 Enter your income in Rs:50000 You are eligible for the loan


Example 5:  Python program to check Positive, Negative or Zero number.

# Checking for Positive, Negative, or Zero Number
number = int(input("Enter one number:"))
if number >= 0:
    if number == 0:
        print("The number is zero")
    else:
        print("The number is positive")
else:
    print("The number is negative")

Output
Enter a number:5 The number is positive

* * *

Thursday, 11 July 2024

Python program to generate 100 random numbers between 1 to 100

Random Number Generation in Python

Following python program will generate 100 random numbers between 1 to 100.

import random

# Define a blank list to store the random numbers
random_numbers = []

# Loop 100 times to generate 100 random numbers
for _ in range(100):
  # Generate a random integer between 1 and 100 (inclusive)
  number = random.randint(1, 100)
# Append the random number to the list
  random_numbers.append(number)

# Print the list of random numbers
print("Generated 100 random numbers in range 1 to 100:")
print(random_numbers)

Output

Generated 100 random numbers in range 1 to 100:

[31, 48, 64, 37, 69, 53, 75, 24, 34, 19, 5, 2, 44, 12, 51, 96, 49, 92, 54, 99, 78, 68, 87, 74, 92, 53, 68, 41, 76, 13, 59, 89, 52, 99, 17, 41, 37, 43, 47, 32, 13, 10, 91, 87, 46, 3, 29, 46, 11, 71, 74, 26, 21, 63, 67, 80, 10, 33, 4, 4, 30, 89, 63, 93, 90, 24, 2, 46, 73, 91, 88, 94, 5, 93, 18, 5, 31, 93, 66, 54, 28, 8, 11, 39, 17, 96, 91, 60, 38, 4, 77, 98, 7, 45, 48, 64, 51, 40, 38, 34]

* * *

< Back to Home >


Sunday, 14 April 2024

Introduction to Matplotlib library

Matplotlib - Python's library for data visualization

What is Matplotlib?

Matplotlib is a fundamental Python library for data visualization. It is a powerful and versatile open-source library in Python that allows you to create various static, animated, and interactive visualizations. It excels at generating a wide range of plot types, including:

  • Line plots
  • Bar charts
  • Scatter plots
  • Histograms
  • Pie charts
  • 3D plots
  • And many more

Matplotlib is a cornerstone for data analysis and storytelling in Python. By visualizing your data, you can gain deeper insights, identify trends and patterns, and communicate findings effectively.


Getting Started with Matplotlib - Installation:

If you don't have Matplotlib installed, use pip, and import the matplotlib.pyplot submodule.
 

pip install matplotlib
import matplotlib.pyplot as plt

Example: A Line Plot using Matplotlib

This example creates a line plot showing temperature variations over time:


# Sample data (replace with your actual data)
days = [1, 2, 3, 4, 5]
temperatures = [20, 22, 25, 23, 21]

# Create the plot
plt.plot(days, temperatures)

# Add labels and title
plt.xlabel("Days")
plt.ylabel("Temperature (°C)")
plt.title("Temperature Variation Over 5 Days")

# Display the plot
plt.show()

Output of the code

Line Plot
Figure: Line Plot


Example - Bar Chart using Matplotlib: 

Following example creates a bar chart comparing sales figures for different products.

# Sample data (replace with your actual data)
products = ["Product A", "Product B", "Product C"]
sales = [100, 150, 80]

# Create the bar chart
plt.bar(products, sales)

# Add labels and title
plt.xlabel("Products")
plt.ylabel("Sales")
plt.title("Product Sales Comparison")

# Display the plot
plt.show()


Output of the code


Figure: Bar Chart using Matplotlib

Example of Scatter Plot: 

Following example creates a scatter plot to visualize the relationship between weight and height:

# Sample data (replace with your actual data)
weights = [60, 70, 80, 55, 65]
heights = [170, 180, 175, 165, 172]

# Create the scatter plot
plt.scatter(weights, heights)

# Add labels and title
plt.xlabel("Weight (kg)")
plt.ylabel("Height (cm)")
plt.title("Weight vs. Height")

# Display the plot
plt.show()

Output of the code

Figure: Scatter Plot

Remember to replace the sample data in these examples with your actual data to create meaningful visualizations.

Customization and Beyond

Matplotlib offers extensive customization capabilities. You can fine-tune plot elements like:

  • Line styles
  • Marker shapes
  • Color schemes
  • Grid lines
  • Legend placement
  • Font sizes

Explore the official Matplotlib documentation.