Python Program to Display the Multiplication Table.

Multiplication tables are fundamental in mathematics and are often required in various applications. In this article, we'll explore how to write a Python program to display the multiplication table for a given number.


Steps to Print Multiplication Table in Python.

We can print a multiplication table of any number (from 1 to 10) in Python using a loop and in our example, we are going to use for loop.


Below are the steps to follow:

  • Accept a number from the user for which you want to print the table.
  • Use a loop to iterate from 1 to the desired range (example: 1 to 10).
  • Multiply the input number by the current iteration variable in each step.
  • Display the result in the desired format of a multiplication table.  

Python Code:

# Python Program to Display the Multiplication Table

# Step 1: Accept a number from the user
number = int(input("Enter the number: "))

# Step 2: Display the multiplication table up to 10
print(f"Multiplication Table for {number}:")
for i in range(1, 11):
    result = number * i
    print(f"{number} x {i} = {result}")
Output:
Enter the number: 12
Multiplication Table for 12:
12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 96
12 x 9 = 108
12 x 10 = 120

Explanation:

In the above example, we use the input() function to get a number from the user. The for loop runs from 1 to 10 (inclusive) to generate the multiplication table. Inside the loop, we multiply the user-entered number by the current loop variable (i) to calculate the result. The print() statement displays the multiplication table in the required format.

Python Program to Convert Celsius to Fahrenheit and Visa Versa.

Temperature often needs to be converted between different scales. In this article, we'll explore how to convert Celsius to Fahrenheit and Fahrenheit to Celsius using Python.  

Convert Celsius to Fahrenheit and Visa Versa in Python

Celsius and Fahrenheit are two different measuring units to use to measure temperature. Celsius unit is widely used around the world, especially in scientific contexts where Fahrenheit is primarily used in the United States, its territories and associated states, and the Bahamas.


The formula to convert Celsius (C) to Fahrenheit (F) is given by:

  • F = C x 9/5 + 32

The formula to convert Fahrenheit (F) to Celsius (C) is given by:

  • C = 5/9 x (F - 32)

Python Program to Convert Celsius to Fahrenheit. 

In this Python program, we are going to take the value of Celsius from the user and then we will use the formula F = (C * 9/5) + 32 to calculate the value of Fahrenheit. 

Python Code:

# Temperature in celsius degree
celsius = float(input("Enter temperature in Celsius: "))
 
# Converting the celsius to
# fehrenheit using the formula
fahrenheit = (celsius * 9/5) + 32
 
# printing the result
print('%.2f Celsius is equivalent to: %.2f Fahrenheit'% (celsius, fahrenheit))
Output:
Enter temperature in Celsius: 100
100.00 Celsius is equivalent to: 212.00 Fahrenheit

Python Program to Convert Fahrenheit to Celsius.

Here in this Python program, we are going to take the value of Fahrenheit as input from the user. We will then use the formula C = 5/9 * (F - 32) to convert the temperature of Fahrenheit to Celsius.

Python Code:
# Temperature in Fahrenheit degree
fahrenheit = float(input("Enter temperature in Fahrenheit: "))
 
# Converting the Fahrenheit to
# Celsius using the formula
celsius = 5/9 * (fahrenheit - 32)
 
# printing the result
print('%.2f Fahrenheit is equivalent to: %.2f Celsius'% (fahrenheit, celsius))
Output:
Enter temperature in Fahrenheit: 212
212.00 Fahrenheit is equivalent to: 100.00 Celsius

So these are the two Python codes to convert temperature from Fahrenheit to Celsius and Celsius to Fahrenheit. 

Python Program to Convert Kilometers to Miles.

In this tutorial, will learn how to convert Kilometers to Miles using Python Programming. We'll cover the algorithm, provide a step-by-step guide, and offer Python code with explanations.

Understanding the Conversion.

The conversion from kilometers to miles involves a simple mathematical formula. The relationship between kilometers (K) and miles (M) is given by:

Formula: Miles = Kilometers × 0.621371

This formula states that one kilometer is approximately equal to 0.621371 miles.

Algorithm to Convert Kilometers to Miles.

Step 1: Take the value of kilometers as input from the user.
Step 2: Use the formula M = Km x 0.621371 to calculate Miles and store the result in a variable.
Step 3: Print the value stored in the variable as output. 

Python Code:
# Python program to convert kilometers to miles
distance_in_km = float(input("Enter distance in kilometers: "))

conversion_factor = 0.621371
# Calculating miles
distance_miles = distance_in_km * conversion_factor

# Displaying the result
print(f"{distance_in_km} kilometers is equal to {distance_miles:.2f} miles.")
Output:
Enter distance in kilometers: 12
12.0 kilometers is equal to 7.46 miles.

This Python program provides a straightforward way to convert distances from kilometers to miles. Understanding such conversions is crucial in various applications, including travel, fitness tracking, and geographic calculations.

ord() and chr() Function in Python.

In Python, the ord() and chr() functions are essential tools for working with Unicode, they allow you to convert an integer to Unicode and Unicode to an integer respectively. Let's dive deeper into these functions.


What is Unicode?

Unicode is a standardized character encoding system that assigns a unique number, known as a code point, to every character in almost every script and language in the world. It is designed to be a universal character set, encompassing characters from different writing systems. For example, 'A' is assigned the code point 65, and '❤' is assigned the code point 2764.


What is ord() in Python?

The ord() function in Python is a built-in function that returns an integer representing the Unicode character. It stands for "ordinal," and its primary use is to obtain the Unicode code point of a given character.

Syntax:

ord(character)

Python Code:
# Using ord() to get the Unicode code point of a character

unicode_value = ord('A')

print(f"The Unicode code point of 'A' is {unicode_value}")
Output:
The Unicode code point of 'A' is 65

In this example, ord('A') returns 65, which is the Unicode code point for the character 'A'.

What is chr() in Python?

In Python, chr() is a built-in function that converts an integer representing a Unicode code point into the corresponding character. The name chr stands for "character." This function is the inverse of the ord() function, which converts a character to its Unicode code point.

Syntax: 
# i is an integer representing an integer point
chr(i)

Python Code:
# Using chr() to convert a Unicode code point to a character
unicode_code_point = 65  # Unicode code point for 'A'
character = chr(unicode_code_point)

# Printing the result
print(f"The character to the Unicode code point {unicode_code_point} is: {character}")

In this example, chr(65) returns the character 'A' because 65 is the Unicode code point for the uppercase letter 'A.'

In this article, we have discussed ord() and chr() functions which help us in working with Unicode. It is an important concept to learn for solving many real-life coding problems.

Python Program To Find ASCII Value of a character.

Finding the ASCII value of a character in Python programming is useful for solving many coding problems. In this tutorial, we will learn different ways to find the ASCII  value of any given character.

What is ASCII Value?

ASCII, which stands for American Standard Code for Information Interchange, is a character encoding standard used for representing text and control characters in computers and other devices that use text.

In ASCII, each character is assigned a unique numeric value. The standard ASCII set uses values ranging from 0 to 127, representing basic characters such as letters, digits, punctuation, and control characters.

Example:
  • The ASCII value for the uppercase letter 'A' is 65.
  • The ASCII value for the lowercase letter 'a' is 97.
  • The ASCII value for the digit '0' is 48.
  • The ASCII value for the exclamation mark '!' is 33.

Python Code to Find ASCII Value of a Character.

In Python, the ord() function can be used to find the ASCII value of a character.

Here's a simple Python program to get ASCII value:
character = input("Enter a character: ")

# ASCII value of character
ascii_value = ord(char)
print(f"The ASCII value of {character} is {ascii_value}")
Output:
Enter a character: D
The ASCII value of D is 68

The ord() function in Python is a built-in function that returns an integer representing the Unicode character. 

Python Program to Find Character from ASCII Value.

The chr() function is the inverse of ord(). It converts an ASCII value to its corresponding character. 

Here is a simple Python Code to get a Character from an ASCII value:
ascii_value = int(input("Enter an ASCII value: "))

character = chr(ascii_value)

print(f"The character for ASCII value {ascii_value} is {character}")
Output:
Enter an ASCII value: 65
The character for ASCII value 65 is A

These approaches showcase the simplicity and flexibility of Python when working with ASCII values. 


Related post:

Python Program to Calculate Sum of Natural Numbers.

Natural numbers are a set of positive integers starting from 1 and continuing indefinitely. They are the numbers you use for counting and ordering. The sum n natural numbers can be calculated using a formula or by using a loop. 


Example:

Input: n = 5
Output: 15

Explanation:
1+2+3+4+5 = 15

The sum of Natural Numbers Using a Loop.

You can easily find the sum of natural numbers using a for or a while loop in Python.

Algorithm:
  • Take the input value n from the user.
  • Initialize a variable S to 0 (to store the sum).
  • Use a for loop to iterate from 1 to n. In each iteration, add the current number to S.
  • Display the sum of n natural numbers as a result.

Python Code to Find Sum of Natural Numbers Using for loop.
# Python code implementation to find sum of natural numbers
def sum_of_natural_numbers_with_loop(n):
    S = 0
    for i in range(1, n + 1):
        S += i
    return S

n = int(input("Enter the value of n: "))

result = sum_of_natural_numbers_with_loop(n)

print(f"Sum of the first {n} natural numbers using a loop is: {result}")
Output:
Enter the value of n: 10
sum of the first 10 natural numbers using a loop is: 55

The Sum of Natural Numbers Using Math.

The most efficient way to find the sum of natural numbers is by using a math formula. Formula: sum = n*(n+1)/2

Example:

Input: n = 10;
Output: 55

Explanation: 
sum = n*(n+1)/2
    = 10*(10+1)/2
    = 10*(11)/2
    = 10*5.5
    = 55

Algorithm:
  • Take the value of n as an input from the user.
  • Initialize a variable sum to 0 to store the sum of natural numbers.
  • Use the mathematical formula to calculate the sum and store the result in the sum variable.
  • Display the value of the sum as a result. 

Python code to find the sum of natural numbers using a formula.
# Python sum of natural numbers
def sum_of_natural_numbers(n):
    S = (n * (n + 1)) // 2
    return S

n = int(input("Enter the value of n: "))

result = sum_of_natural_numbers(n)

print(f"Sum of the first {n} natural numbers is: {result}")
Output:
Enter the value of n: 10
sum of the first 10 natural numbers using a loop is: 55

These are the two Python program that calculates the sum of the first n natural numbers.

Hash Table Chaining in C++.

One of the key challenges in hash table implementation is handling collisions, where two keys hash to the same index. Chaining and Open Addressing are two techniques that help us to manage these collisions gracefully. In this tutorial, you will learn how to handle collisions using the Chaining method in detail. 


What is Hash Table Chaining?

In chaining collision, each bucket or index of the hash table contains a linked list or another data structure. When a collision occurs, the colliding elements are appended to the linked list at the corresponding index. Chaining allows multiple elements with the same hash value to coexist at the same index.

Chaining in Hash Table

Advantages of Chaining in Hash Table.

  • Chaining handles collisions effectively, ensuring that no data is lost.
  • Chaining facilitates dynamic resizing, accommodating varying numbers of elements.
  • Implementing chaining is straightforward, making it an attractive option for hash table design.


Disadvantages of Chaining in Hash Table.

  • Each element requires additional memory for the linked list pointers, contributing to increased memory overhead.
  • In scenarios with high collision rates, the performance of the linked lists might degrade, impacting overall hash table performance.

Implementation of Chaining.

Instead of storing multiple elements at the same index, chaining involves maintaining a linked list (or another data structure) at each index to store all colliding elements.

Hash Function: The hash function calculates the hash value for each key. The hash value determines the index at which the key's corresponding value will be stored.

Index Calculation: Calculate the hash value using the hash function: index = hash(key) % table_size.

Collision Occurs: If two keys hash to the same index, a collision occurs. In chaining, this is not a problem.

Linked List Handling: Each index in the hash table contains a linked list. If the linked list is empty, insert the key-value pair at the corresponding index and if the linked list is not empty, append the key-value pair to the end of the list.

Searching: When searching for a key, calculate its hash and navigate the linked list at the corresponding index. If the key is found in the linked list, return its associated value and if the linked list is empty or the key is not found, the key is not in the hash table.

Deleting: To delete a key, calculate its hash and search for it in the linked list. If found, remove the node from the linked list. If the linked list becomes empty after deletion, update the index in the hash table.


C++ code to implement Chaining in Hash Table:

// C++ code of chaining in hash table
#include <iostream>
#include <list>
using namespace std;

// HashTable class with Chaining
class HashTable {
private:
    int table_size;  // Size of the hash table
    // Array of linked lists
    list<pair<int, int>>* table;  

    // Hash function to determine the index
    int hash(int key) {
        return key % table_size;
    }

public:
    // Constructor to initialize the hash table
    HashTable(int size) {
        table_size = size;
        table = new list<pair<int, int>>[table_size];
    }

    // Function to insert a key-value pair into the hash table
    void insert(int key, int value) {
        int index = hash(key);
        table[index].push_back(make_pair(key, value));
    }

    // Function to search for a key and return its value
    int search(int key) {
        int index = hash(key);
        for (auto& it : table[index]) {
            if (it.first == key) {
                return it.second;  // Key found, return its value
            }
        }
        return -1;  // Key not found
    }

    // Function to delete a key from the hash table
    void remove(int key) {
        int index = hash(key);
        for (auto it = table[index].begin(); it != table[index].end(); ++it) {
            if (it->first == key) {
                table[index].erase(it);  // Remove the key-value pair
                break;
            }
        }
    }

    // Function to display the hash table
    void display() {
        for (int i = 0; i < table_size; ++i) {
            cout << "[" << i << "] -> ";
            for (const auto& it : table[i]) {
                cout << "(" << it.first << ", " << it.second << ") -> ";
            }
            cout << "nullptr\n";
        }
    }
};

// Main function for testing
int main() {
    // Create a hash table with a size of 5
    HashTable hashTable(5);

    // Insert key-value pairs
    hashTable.insert(25, 250);
    hashTable.insert(14, 140);
    hashTable.insert(7, 70);

    // Display the hash table
    cout << "Hash Table after Insertion:\n";
    hashTable.display();

    // Search for a key
    int searchResult = hashTable.search(14);
    if (searchResult != -1) {
        cout << "Value for key 14: " << searchResult << "\n";
    } else {
        cout << "Key 14 not found.\n";
    }

    // Remove a key
    hashTable.remove(14);
    cout << "\nHash Table after Removal:\n";
    hashTable.display();

    return 0;
}
Output:
Hash Table after Insertion:
[0] -> (25, 250) -> nullptr
[1] -> nullptr
[2] -> (7, 70) -> nullptr
[3] -> nullptr
[4] -> (14, 140) -> nullptr
Value for key 14: 140

Hash Table after Removal:
[0] -> (25, 250) -> nullptr
[1] -> nullptr
[2] -> (7, 70) -> nullptr
[3] -> nullptr
[4] -> nullptr

This C++ code defines a HashTable class with chaining. It includes functions for inserting, searching, removing keys, and displaying the hash table. The main function demonstrates the usage of the hash table with a few key-value pairs.

How To Find Mac Address on Windows, macOS and Linux.

MAC (Media Access Control) address is a unique identifier assigned to a network interface card (NIC) in a device, providing it with a distinct digital identity on a network. Comprising twelve alphanumeric characters, the MAC address is often expressed as six pairs of two characters separated by colons or hyphens (e.g., 00:1A:2B:3C:4D:5E).


Here we show you the different ways to find the MAC Address of your laptop on various operating systems like Windows macOS and Linux. 


Find the MAC Address on Windows using CMD.

It is easy to find the MAC Address on a Windows laptop using the Command Prompt (CMD). Below are steps you can follow:


1. Press the Windows key + R to open the Run dialog. Type cmd and press Enter to open the Command Prompt.

CMD in Windows

2. In the Command Prompt window, type the following command and press Enter.

ipconfig /all

CMD Command to Find MAC Address

3. Look for the network adapter you're interested in; it might be labeled as a "Wireless LAN adapter" for Wi-Fi or an "Ethernet adapter" for wired connections.


4. In the information displayed, find the "Physical Address." This is your MAC address. It usually appears as six pairs of alphanumeric characters separated by hyphens or colons (e.g., 00-1A-2B-3C-4D-5E).

Mac Address which are visible on CMD

Now you've successfully retrieved the MAC address of your Windows computer using the Command Prompt.


Find MAC Address on macOS.

You can find the MAC Address on a macOS device in the network settings. Below are the steps to follow:

1. Click on the Apple logo in the top-left corner of your screen. Select "System Preferences" from the drop-down menu.


2. In the System Preferences window, locate and click on "Network."


3. Choose the network connection for which you want to find the MAC address (Wi-Fi or Ethernet) from the left sidebar.


4. Once you've selected the network connection, click on the "Advanced" button in the lower-right corner.

Network Setting in macOS

5. In the advanced settings, go to the "Hardware" or "Ethernet" tab. Here, you will find the "MAC Address" or "Hardware Address.

MAC Address in MackBook


Find the MAC Address on Linux.

To discover the MAC (Media Access Control) address on a Linux system, you can use the command line. Here's a step-by-step guide:


1. Launch the terminal on your Linux system. You can usually find it in your applications menu or use a keyboard shortcut like Ctrl + Alt + T.


2. In the terminal window, type the following command and press Enter.

ip link show


3. Look for the network interface for which you want to find the MAC address. Common interfaces include eth0 for Ethernet and wlan0 for Wi-Fi.


4. In the output, find the line labeled "link/ether" followed by the MAC address. 


Alternatively, you can use the following command specifically for the MAC address.

cat /sys/class/net/<interface>/address

Replace <interface> with the name of your network interface (e.g., eth0 or wlan0).

Frequently Ask Questions.


Q: What is the Use of MAC Address?

Answer: The primary use of a MAC address is in network communication. It serves as a hardware address for devices to interact within a local network, facilitating the delivery of data to the intended recipient. This address is crucial for device recognition, enabling routers and switches to forward data accurately to the designated device. 


Q: What is the difference between a MAC Address and an IP Address?

Answer: A MAC Address is a hardware-level identifier assigned to a device's network interface, while an IP Address is a logical identifier assigned to a device on a network. MAC Addresses operate at the data link layer, and IP Addresses operate at the network layer of the OSI model. While IP addresses handle global communication, MAC addresses manage local network communication, making them essential for the seamless functioning of networked devices. 


Q: Is the MAC Address visible to others on the internet?

Answer: No, the MAC Address is typically not visible beyond the local network. When data leaves the local network and travels through routers, the source MAC Address is replaced with the router's MAC Address.


Q: Why might I need to know my device's MAC Address?

Answer: Knowing your device's MAC Address is useful for network troubleshooting, configuring network settings, implementing security measures such as MAC filtering, and ensuring proper device recognition on a network.


Q: Can two devices have the same MAC Address?

Answer: No, each MAC Address is unique. The probability of two devices having the same MAC Address is extremely low due to the large address space available.


Q: Does the MAC Address change when switching networks?

Answer: No, the MAC Address remains constant for a specific network interface. It only changes if the user manually modifies it or if the device undergoes hardware changes, such as a network card replacement.

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson