Python Program to Check if a Date is Valid and Print the Incremented Date

Program to Check if a Date is Valid and Print the Incremented Date

Given a date , the task is to Check if a Date is Valid and increment the given date and print it in python

Examples:

Example1:

Input:

given date ="11/02/2001"

Output:

The incremented given date is:  12 / 2 / 2001

Example2:

Input:

 given date = "29/02/2001"

Output:

The given date 29/02/2001 is not valid

Program to Check and Print the Incremented Date in Python

Below are the ways to check and implement the increment the given date in Python:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

1)By using if..elif..else Conditional Statements  and split() function(Static Input)

Approach:

  • Give the date in the format dd/mm/yyyy as static input
  • Separate the date by storing the day, month, and year in different variables.
  • Check the validity of the day, month, and year using various if-statements.
  • If the date is valid, increment it .
  • Print the increment date.
  • Exit of Program.

Below is the implementation:

# given given_data
given_date = "11/02/2001"
# splitting the given_data by / character to separate given_data,month and year
day, month, year = given_date.split('/')
day = int(day)
month = int(month)
year = int(year)
if(month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12):
    maxdays = 31
elif(month == 4 or month == 6 or month == 9 or month == 11):
    maxdays = 30
elif(year % 4 == 0 and year % 100 != 0 or year % 400 == 0):
    maxdays = 29
else:
    maxdays = 28
if(month < 1 or month > 12):
    print("The given date", given_date, "is not valid")
elif(day < 1 or day > maxdays):
    print("The given date", given_date, "is not valid")
elif(day == maxdays and month != 12):
    day = 1
    month = month+1
    print("The incremented given date is: ", day, month, year)
elif(day == 31 and month == 12):
    day = 1
    month = 1
    year = year+1
    print("The incremented given date is: ", day, '/', month, '/', year)
else:
    day = day + 1
    print("The incremented given date is: ",  day, '/', month, '/', year)

Output:

The incremented given date is:  12 / 2 / 2001

Explanation:

  • Give the date in the format dd/mm/yyyy as static input.
  • The date is then divided, with the day, month, and year recorded in separate variables.
  • The date is invalid if it is not between 1 and 30 in the months of April, June, September, and November.
  • The date is invalid if it is not between 1 and 31 for the months of January, March, April, May, July, August, October, and December.
  • If the month is February, the day should be between 1 and 28 for non-leap years and between 1 and 29 for leap years.
  • If the date is correct, it should be increased.
  • The final incremented date is printed

2)By using if..elif..else Conditional Statements  and split() function(User Input)

Approach:

  • Scan the date, month and year as int(input()).
  • Separate the date by storing the day, month, and year in different variables.
  • Check the validity of the day, month, and year using various if-statements.
  • If the date is valid, increment it .
  • Print the increment date.
  • Exit of Program.

Below is the implementation:

# Scan the date, month and year as int(input()).
day = int(input("Enter some random day = "))
month = int(input("Enter some random month = "))
year = int(input("Enter some random year = "))
if(month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12):
    maxdays = 31
elif(month == 4 or month == 6 or month == 9 or month == 11):
    maxdays = 30
elif(year % 4 == 0 and year % 100 != 0 or year % 400 == 0):
    maxdays = 29
else:
    maxdays = 28
if(month < 1 or month > 12):
    print("The given date", given_date, "is not valid")
elif(day < 1 or day > maxdays):
    print("The given date", given_date, "is not valid")
elif(day == maxdays and month != 12):
    day = 1
    month = month+1
    print("The incremented given date is: ", day, month, year)
elif(day == 31 and month == 12):
    day = 1
    month = 1
    year = year+1
    print("The incremented given date is: ", day, '/', month, '/', year)
else:
    day = day + 1
    print("The incremented given date is: ",  day, '/', month, '/', year)

Output:

Enter some random day = 11
Enter some random month = 2
Enter some random year = 2001
The incremented given date is: 12 / 2 / 2001

Related Programs:

Python Program to Print all Numbers in a Range Divisible by a Given Number

Program to Print all Numbers in a Range Divisible by a Given Number

Given three integers, the task is to print all values in the given range that are divisible by the third number, where the first number specifies the lower limit and the second number specifies the upper limit.

Examples:

Example1:

Input:

lower limit = 1 
upper limit = 263 
given number = 5

Output:

The numbers which are divisible by 5 from 17 to 263 are:
20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 105 110 115 120 125 130 135 140 145 150 155 160 165 
170 175 180 185 190 195 200 205 210 215 220 225 230 235 240 245 250 255 260

Example2:

Input:

Enter the lower limit = 37 
Enter the upper limit = 217 
Enter the given number = 3

Output:

The numbers which are divisible by 3 from 37 to 217 are:
39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 99 102 105 108 111
114 117 120 123 126 129 132 135 138 141 144 147 150 153 156 159 162 165 168 
171 174 177 180 183 186 189 192 195 198 201 204 207 210 213 216

Example3:

Input:

Enter the lower limit = 128
Enter the upper limit = 659
Enter the given number = 7

Output:

The numbers which are divisible by 7 from 128 to 659 are:
133 140 147 154 161 168 175 182 189 196 203 210 217 224 231 238 245 252 259 266 273 280 287 294 301 308 
315 322 329 336 343 350 357 364 371 378 385 392 399 406 413 420 427 434 441 448 455 462 469 476 483 490 
497 504 511 518 525 532 539 546 553 560 567 574 581 588 595 602 609 616 623 630 637 644 651 658

Program to Print all Numbers in a Range Divisible by a Given Number in Python

There are several ways to print all the numbers in the given range which are divisible by the given number some of them are:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

Method #1:Using for loop(Static Input)

Approach:

  • Give three numbers as static input.
  • Using for loop, loop from lower limit to upper limit.
  • Using an if conditional statement, determine whether the iterator value is divisible by the given number.
  • If it is divisible then print the iterator value.
  • Exit of program

Below is the implementation:

# given lower limit
lower_limit = 17
# given upper limit
upper_limit = 263
# given number
numb = 5
print("The numbers which are divisible by", numb,
      "from", lower_limit, "to", upper_limit, "are:")
# Using for loop, loop from lower limit to upper limit
for val in range(lower_limit, upper_limit):
    # Using an if conditional statement, determine whether
    # the iterator value is divisible by the given number.
    if(val % numb == 0):
        print(val, end=" ")

Output:

The numbers which are divisible by 5 from 17 to 263 are:
20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 105 110 115 120 125 130 135 140 145 150 155 160 165 170 175 180 185 190 195 200 205 210 215 220 225 230 235 240 245 250 255 260

Method #2:Using for loop(User Input)

Approach:

  • Scan the lower limit, upper limit and the given number using int(input()).
  • Using for loop, loop from lower limit to upper limit.
  • Using an if conditional statement, determine whether the iterator value is divisible by the given number.
  • If it is divisible then print the iterator value.
  • Exit of program

Below is the implementation:

# Scanning the lower limit
lower_limit = int(input("Enter the lower limit = "))
# Scanning the upper limit
upper_limit = int(input("Enter the upper limit = "))
# Scanning the given number
numb = int(input("Enter the given number = "))
print("The numbers which are divisible by", numb,
      "from", lower_limit, "to", upper_limit, "are:")
# Using for loop, loop from lower limit to upper limit
for val in range(lower_limit, upper_limit):
    # Using an if conditional statement, determine whether
    # the iterator value is divisible by the given number.
    if(val % numb == 0):
        print(val, end=" ")

Output:

Enter the lower limit = 37
Enter the upper limit = 217
Enter the given number = 3
The numbers which are divisible by 3 from 37 to 217 are:
39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 99 102 105 108 111 114 117 120 123 126 129 132 135 138 141 144 147 150 153 156 159 162 165 168 171 174 177 180 183 186 189 192 195 198 201 204 207 210 213 216

Explanation:

  • The user must enter the upper and lower range limits.
  • The user is next required to provide the number to be divided from the user.
  • The value of i is between the lower and upper bounds.
  • Whenever the remainder of an integer divided by numb equals zero, the i is printed.

Method #3:Using While loop (User Input)

Approach:

  • Scan the lower limit, upper limit and the given number using int(input()).
  • Take a variable tempo and initialize it with lower limit.
  • Loop till tempo is less than upper limit using while loop.
  • Using an if conditional statement, determine whether the tempo value is divisible by the given number.
  • If it is divisible then print the iterator value.
  • Increment the tempo by 1
  • Exit of program

Below is the implementation:

# Scanning the lower limit
lower_limit = int(input("Enter the lower limit = "))
# Scanning the upper limit
upper_limit = int(input("Enter the upper limit = "))
# Scanning the given number
numb = int(input("Enter the given number = "))
# Take a variable tempo and initialize it with lower limit.
tempo = lower_limit
print("The numbers which are divisible by", numb,
      "from", lower_limit, "to", upper_limit, "are:")
# Loop till tempo is less than upper limit using while loop.
while(tempo < upper_limit):
    # Using an if conditional statement, determine whether
    # the tempo value is divisible by the given number.
    if(tempo % numb == 0):
        print(tempo, end=" ")
    # Increment the tempo by 1
    tempo = tempo+1

Output:

Enter the lower limit = 128
Enter the upper limit = 659
Enter the given number = 7
The numbers which are divisible by 7 from 128 to 659 are:
133 140 147 154 161 168 175 182 189 196 203 210 217 224 231 238 245 252 259 266 273 280 287 294 301 308 315 322 329 336 343 350 357 364 371 378 385 392 399 406 413 420 427 434 441 448 455 462 469 476 483 490 497 504 511 518 525 532 539 546 553 560 567 574 581 588 595 602 609 616 623 630 637 644 651 658

Related Programs:

Python Program to Convert Gray Code to Binary

Program to Convert Gray Code to Binary

Although binary numbers are the most common way to store numbers, they can be challenging to use in many situations, necessitating the usage of a binary number variant. This is where Gray codes come in handy.

Gray code has the property that two consecutive numbers differ in just one bit. Because of this quality, grey code cycles through multiple states with low effort and is used in K-maps, error correction, communication, and so on.

Gray Code is a type of minimum-change coding in which the two subsequent values differ by only one bit. More specifically, it is a binary number system in which only a single bit varies while travelling from one step to the next.

We will learn how to convert gray to binary code in Python in this tutorial. A binary number is a number written in the base-2 numeral system. As a result, a binary number is made up of only 0s and 1s. So, today, we’ll learn how to represent binary and gray code numbers, how to convert a gray number to binary code, and how to use a Python program to convert a gray number to binary code.

Examples:

Example1:

Input:

given gray code =1001000010

Output:

The Binary string of the given gray code= 1001000010 is 1110000011

Example2:

Input:

given gray code =1000111100110

Output:

The Binary string of the given gray code= 1000111100110 is 1111010111011

Program to Convert Gray Code to Binary in Python

Below are the ways to convert the given gray code to binary number in python:

Method #1:Using Right Shift Operator and  While loop( Static Input)

Approach:

  • Give the binary number as static.
  • The grayToBin has been defined.
  • It accepts as an argument the Gray codeword string.
  • It returns the binary number connected with it as a string.
  • If g(i) is the ith bit in the Gray codeword and b(i) is the ith bit in the corresponding binary number, where the 0th bit is the MSB, g(0) = b(0) and b(i) = g(i) XOR b(i – 1) for I > 0.
  • Based on the preceding, b(i) = g(i) XOR g(i – 1) XOR… XOR g (0).
  • Thus, a Gray codeword g can be translated to its corresponding binary number by doing (g XOR (g >> 1) XOR (g >> 2) XOR… XOR (g >> m)), where m is such that g >> (m + 1) equals 0.

Below is the implementation:

# function which accepts the gray code  and returns the binary code  of the gray code
def grayToBin(grayCde):
   # Converting the given gray code to integer
    graynum = int(grayCde, 2)
   # Taking a temporary variable which stores the the gray code integer number
    tempnum = graynum
    # using while loop
    while tempnum != 0:
        tempnum >>= 1
        graynum ^= tempnum

        # bin(n) returns n's binary representation with the prefix '0b' removed
        # the slice operation removes the prefix.
    return bin(graynum)[2:]


# given gray code as static
graycode = "1001000010"
# passing this graycode to grayToBin function
resultbin = grayToBin(graycode)
print('The Binary string of the given gray code=', graycode, 'is', resultbin)

Output:

The Binary string of the given gray code= 1001000010 is 1110000011

Method #2:Using Right Shift Operator and  While loop( User Input)

Approach:

  • Scan the gray code string using input() function.
  • The grayToBin has been defined.
  • It accepts as an argument the Gray codeword string.
  • It returns the binary number connected with it as a string.
  • If g(i) is the ith bit in the Gray codeword and b(i) is the ith bit in the corresponding binary number, where the 0th bit is the MSB, g(0) = b(0) and b(i) = g(i) XOR b(i – 1) for I > 0.
  • Based on the preceding, b(i) = g(i) XOR g(i – 1) XOR… XOR g (0).
  • Thus, a Gray codeword g can be translated to its corresponding binary number by doing (g XOR (g >> 1) XOR (g >> 2) XOR… XOR (g >> m)), where m is such that g >> (m + 1) equals 0.

Below is the implementation:

# function which accepts the gray code  and returns the binary code  of the gray code
def grayToBin(grayCde):
   # Converting the given gray code to integer
    graynum = int(grayCde, 2)
   # Taking a temporary variable which stores the the gray code integer number
    tempnum = graynum
    # using while loop
    while tempnum != 0:
        tempnum >>= 1
        graynum ^= tempnum

        # bin(n) returns n's binary representation with the prefix '0b' removed
        # the slice operation removes the prefix.
    return bin(graynum)[2:]


# given gray code as static
graycode = input("Enter some random gray code string = ")
# passing this graycode to grayToBin function
resultbin = grayToBin(graycode)
print('The Binary string of the given gray code=', graycode, 'is', resultbin)

Output:

Enter some random gray code string = 1000111100110
The Binary string of the given gray code= 1000111100110 is 1111010111011

Related Programs:

Python Program to Print Reverse Pyramid of Numbers

Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples

Given the number of rows of the pyramid, the task is to print a Reverse Pyramid of Numbers in C, C++, and Python.

Examples:

Example1:

Input:

Given number of rows = 10

Output:

1 
2 1 
3 2 1 
4 3 2 1 
5 4 3 2 1 
6 5 4 3 2 1 
7 6 5 4 3 2 1 
8 7 6 5 4 3 2 1 
9 8 7 6 5 4 3 2 1

Example2:

Input:

Given number of rows = 6

Output:

1 
2 1 
3 2 1 
4 3 2 1 
5 4 3 2 1

Program to Print Reverse Pyramid of Numbers in C,C++, and Python

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number of rows as static input and store it in a variable.
  • Loop from 1 to the number of rows using For loop.
  • Loop from the parent loop iterator value to 0 in decreasing order using another For loop(Nested For Loop).
  • Print the iterator value of the inner for loop.
  • Print the Newline character after the end of the inner loop.
  • The Exit of the Program.

1) Python Implementation

Below is the implementation:

# Give the number of rows as static input and store it in a variable.
numbrrows = 10
# Loop from 1 to the number of rows using For loop.
for m in range(1, numbrrows):
    # Loop from the parent loop iterator value to 0 in decreasing order
    # using another For loop(Nested For Loop).
    for n in range(m, 0, -1):
        # Print the iterator value of the inner for loop.
        print(n, end=' ')
    # Print the Newline character after the end of the inner loop.
    print()

Output:

1 
2 1 
3 2 1 
4 3 2 1 
5 4 3 2 1 
6 5 4 3 2 1 
7 6 5 4 3 2 1 
8 7 6 5 4 3 2 1 
9 8 7 6 5 4 3 2 1

2) C++ Implementation

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{

    // Give the number of rows as static input and store it
    // in a variable.
    int numbrrows = 10;
    // Loop from 1 to the number of rows using For loop.
    for (int m = 1; m < numbrrows; m++) {
        // Loop from the parent loop iterator value to 0 in
        // decreasing order using another For loop(Nested
        // For Loop).
        for (int n = m; n > 0; n--) {
            // Print the iterator value of the inner for
            // loop.
            cout << n << " ";
        }
        // Print the Newline character after the end of the
        // inner loop.
        cout << endl;
    }

    return 0;
}

Output:

1 
2 1 
3 2 1 
4 3 2 1 
5 4 3 2 1 
6 5 4 3 2 1 
7 6 5 4 3 2 1 
8 7 6 5 4 3 2 1 
9 8 7 6 5 4 3 2 1

3) C Implementation

Below is the implementation:

#include <stdio.h>

int main()
{

    // Give the number of rows as static input and store it
    // in a variable.
    int numbrrows = 10;
    // Loop from 1 to the number of rows using For loop.
    for (int m = 1; m < numbrrows; m++) {
        // Loop from the parent loop iterator value to 0 in
        // decreasing order using another For loop(Nested
        // For Loop).
        for (int n = m; n > 0; n--) {
            // Print the iterator value of the inner for
            // loop.
            printf("%d ", n);
        }
        // Print the Newline character after the end of the
        // inner loop.
        printf("\n");
    }
    return 0;
}

Output:

1 
2 1 
3 2 1 
4 3 2 1 
5 4 3 2 1 
6 5 4 3 2 1 
7 6 5 4 3 2 1 
8 7 6 5 4 3 2 1 
9 8 7 6 5 4 3 2 1

Method #2: Using For Loop (User Input)

Approach:

  • Give the number of rows as user input and store it in a variable.
  • Loop from 1 to the number of rows using For loop.
  • Loop from the parent loop iterator value to 0 in decreasing order using another For loop(Nested For Loop).
  • Print the iterator value of the inner for loop.
  • Print the Newline character after the end of the inner loop.
  • The Exit of the Program.

1) Python Implementation

Give the number of rows as user input using int(input()) and store it in a variable.

Below is the implementation:

# Give the number of rows as user input using int(input()) and store it in a variable.
numbrrows = int(input('Enter some random number of rows = '))
# Loop from 1 to the number of rows using For loop.
for m in range(1, numbrrows):
    # Loop from the parent loop iterator value to 0 in decreasing order
    # using another For loop(Nested For Loop).
    for n in range(m, 0, -1):
        # Print the iterator value of the inner for loop.
        print(n, end=' ')
    # Print the Newline character after the end of the inner loop.
    print()

Output:

Enter some random number of rows = 6
1 
2 1 
3 2 1 
4 3 2 1 
5 4 3 2 1

2) C++ Implementation

Give the number of rows as user input using cin and store it in a variable.

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{

    // Give the number of rows as user input using
    // cin and store it in a variable.
    int numbrrows;
    cin >> numbrrows;
    // Loop from 1 to the number of rows using For loop.
    for (int m = 1; m < numbrrows; m++) {
        // Loop from the parent loop iterator value to 0 in
        // decreasing order using another For loop(Nested
        // For Loop).
        for (int n = m; n > 0; n--) {
            // Print the iterator value of the inner for
            // loop.
            cout << n << " ";
        }
        // Print the Newline character after the end of the
        // inner loop.
        cout << endl;
    }

    return 0;
}

Output:

6
1 
2 1 
3 2 1 
4 3 2 1 
5 4 3 2 1

3) C Implementation

Give the number of rows as user input using scanf and store it in a variable.

Below is the implementation:

#include <stdio.h>

int main()
{

    // Give the number of rows as user input using scanf and
    // store it in a variable.
    int numbrrows;
    scanf("%d", &numbrrows);
    // Loop from 1 to the number of rows using For loop.
    for (int m = 1; m < numbrrows; m++) {
        // Loop from the parent loop iterator value to 0 in
        // decreasing order using another For loop(Nested
        // For Loop).
        for (int n = m; n > 0; n--) {
            // Print the iterator value of the inner for
            // loop.
            printf("%d ", n);
        }
        // Print the Newline character after the end of the
        // inner loop.
        printf("\n");
    }
    return 0;
}

Output:

6
1 
2 1 
3 2 1 
4 3 2 1 
5 4 3 2 1

Related Programs:

Python Program to Find the Gravitational Force Acting Between Two Objects

Program to Find the Gravitational Force Acting Between Two Objects

Gravitational Force:

The gravitational force is a force that attracts any two mass-bearing objects. The gravitational force is called attractive because it always strives to pull masses together rather than pushing them apart. In reality, every thing in the cosmos, including you, is tugging on every other item! Newton’s Universal Law of Gravitation is the name for this. You don’t have a significant mass, thus you’re not dragging on those other objects very much. Objects that are extremely far apart do not noticeably pull on each other either. However, the force exists and can be calculated.

Gravitational Force Formula :

Gravitational Force = ( G *  m1 * m2 ) / ( r ** 2 )

Given masses of two objects and the radius , the task is to calculate the Gravitational Force acting between the given two particles in Python.

Examples:

Example1:

Input:

mass1 = 1300012.67
mass2 = 303213455.953
radius = 45.4

Output:

The gravitational force of objects with masses 1300012.67 kg 303213455.953 kg  of radius= 45.4 = 12.761610184592419

Example2:

Input:

Enter the first mass of the object =2491855.892 
Enter the second mass of the object =9000872 
Enter the distance/radius between the objects =50

Output:

The gravitational force of objects with masses 24918552.892 kg 23145689000872.0 kg of radius= 50.0 = 15394799.86164859

Program to Find the Gravitational Force Acting Between Two Objects in Python

We will write the code which calculates the gravitational force acting between the particles and print it

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

1)Calculating the Gravitational Force  (Static Input)

Approach:

  • Take both the masses and the distance between the masses and store them in different variables  or give input as static
  • One of the variables should be set to the value of the gravitational constant, G.
  • The formula is used to calculate the force between the masses.
  • Print the force value, rounded up to two decimal places.
  • Exit the program.

Below is the implementation:

# given first mass
mass1 = 1300012.67
# given second mass
mass2 = 303213455.953
# enter the radius
radius = 45.4
# Given value of Gravitational Constant Gval
Gval = 6.673*(10**(-11))
# Calculating the value of the gravitational force Gforce
Gforce = (Gval*mass1*mass2)/(radius**2)
# printing the value of gravitational force
print("The gravitational force of objects with masses", str(mass1) +
      " kg "+str(mass2)+" kg ", "of radius=", radius, "=", Gforce)

Output:

The gravitational force of objects with masses 1300012.67 kg 303213455.953 kg  of radius= 45.4 = 12.761610184592419

2)Calculating the Gravitational Force  (User Input)

Approach:

  • Scan the masses and radius as a floating data type and store in different variables
  • One of the variables should be set to the value of the gravitational constant, G.
  • The formula is used to calculate the force between the masses.
  • Print the force value, rounded up to two decimal places.
  • Exit the program.

Below is the implementation:

# scanning  first mass as float
mass1 = float(input("Enter the first mass of the object ="))
# given second mass as float
mass2 = float(input("Enter the second mass of the object ="))
# enter the radius as float
radius = float(input("Enter the distance/radius between the objects ="))
# Given value of Gravitational Constant Gval
Gval = 6.673*(10**(-11))
# Calculating the value of the gravitational force Gforce
Gforce = (Gval*mass1*mass2)/(radius**2)
# printing the value of gravitational force
print("The gravitational force of objects with masses", str(mass1) +
      " kg "+str(mass2)+" kg ", "of radius=", radius, "=", Gforce)

Output:

Enter the first mass of the object =2491855.892
Enter the second mass of the object =9000872
Enter the distance/radius between the objects =50
The gravitational force of objects with masses 24918552.892 kg 23145689000872.0 kg of radius= 50.0 = 15394799.86164859

Related Programs:

Python Program to Create a Dictionary with Key as First Character and Value as Words Starting with that Character

Program to Create a Dictionary with Key as First Character and Value as Words Starting with that Character

Interested in programming and want to excel in it by choosing the short ways. Then, practicing with the available Java Program list is mandatory.

Dictionaries in Python:

Dictionary is a mutable built-in Python Data Structure. It is conceptually related to List, Set, and Tuples. It is, however, indexed by keys rather than a sequence of numbers and can be thought of as associative arrays. On a high level, it consists of a key and its associated value. The Dictionary class in Python represents a hash-table implementation.

Given a string , the task is to create a Python program for creating a dictionary with the Key as the first character and the Value as words beginning with that character.

Examples:

Example1:

Input:

given string = "hello this is btechgeeks online programming platform to read the coding articles specially python language"

Output:

h ::: ['hello']
t ::: ['this', 'to', 'the']
i ::: ['is']
b ::: ['btechgeeks']
o ::: ['online']
p ::: ['programming', 'platform', 'python']
r ::: ['read']
c ::: ['coding']
a ::: ['articles']
s ::: ['specially']
l ::: ['language']

Example2:

Input:

given string = "this is btechgeeks today is monday and tomorrow is sunday sun sets in the east "

Output:

t ::: ['this', 'today', 'tomorrow', 'the']
i ::: ['is', 'in']
b ::: ['btechgeeks']
m ::: ['monday']
a ::: ['and']
s ::: ['sunday', 'sun', 'sets']
e ::: ['east']

Program to Create a Dictionary with Key as First Character and Value as Words Starting with that Character

Below are the ways to create a Python program for creating a dictionary with the Key as the first character and the Value as words beginning with that character.

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

1)Using indexing, append ,items() function (Static Input)

Approach:

  • Give the string as static input .
  • Declare a dictionary which is empty using {} or dict()
  • Divide the string into words using split() and save them in a list.
  • Using a for loop and an if statement, determine whether the word already exists as a key in the dictionary.
  • If it is not present, use the letter of the word as the key and the word as the value to create a sublist in the list and append it to it.
  • If it is present, add the word to the associated sublist as the value.
  • The resultant dictionary will be printed.
  • Exit of Program

Below is the implementation:

# given string
given_string = "hello this is btechgeeks online programming platform to read the coding articles specially python language"
# Split the given string into words using split() function
# Convert this into list using list() function.
listString = given_string.split()
# Declare a dictionary which is empty using {} or dict()
resultdict = {}
# Traverse the list String
for stringword in listString:
  # checking if the first character of the word exists in dictionary resultdict keys or not
    if(stringword[0] not in resultdict.keys()):
        resultdict[stringword[0]] = []
        # adding this character to the resultdict
        resultdict[stringword[0]].append(stringword)
    else:
      # If it is present, add the word to the associated sublist as the value.
        if(stringword not in resultdict[stringword[0]]):
            resultdict[stringword[0]].append(stringword)
for key, value in resultdict.items():
    print(key, ":::", value)

Output:

h ::: ['hello']
t ::: ['this', 'to', 'the']
i ::: ['is']
b ::: ['btechgeeks']
o ::: ['online']
p ::: ['programming', 'platform', 'python']
r ::: ['read']
c ::: ['coding']
a ::: ['articles']
s ::: ['specially']
l ::: ['language']

Explanation:

  • A string must be entered by the user or give input as static and saved in a variable.
  • It is declared that the dictionary is empty.
  • The string is split down into words and kept in a list.
  • To iterate through the words in the list, a for loop is utilised.
  • An if statement is used to determine whether a word already exists as a key in the dictionary.
  • If it is not present, the letter of the word is used as the key and the word as the value, and they are appended to the list’s sublist.
  • If it is present, the word is added to the associated sublist as a value.
  • The final dictionary is printed

2)Using indexing, append ,items() function (User Input)

Approach:

  • Scan the given string using input() function.
  • Declare a dictionary which is empty using {} or dict()
  • Divide the string into words using split() and save them in a list.
  • Using a for loop and an if statement, determine whether the word already exists as a key in the dictionary.
  • If it is not present, use the letter of the word as the key and the word as the value to create a sublist in the list and append it to it.
  • If it is present, add the word to the associated sublist as the value.
  • The resultant dictionary will be printed.
  • Exit of Program

Below is the implementation:

# Scanning the given string
given_string = input("Enter some random string separated by spaces = ")
# Split the given string into words using split() function
# Convert this into list using list() function.
listString = given_string.split()
# Declare a dictionary which is empty using {} or dict()
resultdict = {}
# Traverse the list String
for stringword in listString:
  # checking if the first character of the word exists in dictionary resultdict keys or not
    if(stringword[0] not in resultdict.keys()):
        resultdict[stringword[0]] = []
        # adding this character to the resultdict
        resultdict[stringword[0]].append(stringword)
    else:
      # If it is present, add the word to the associated sublist as the value.
        if(stringword not in resultdict[stringword[0]]):
            resultdict[stringword[0]].append(stringword)
for key, value in resultdict.items():
    print(key, ":::", value)

Output:

Enter some random string separated by spaces = this is btechgeeks today is monday and tomorrow is sunday sun sets in the east
t ::: ['this', 'today', 'tomorrow', 'the']
i ::: ['is', 'in']
b ::: ['btechgeeks']
m ::: ['monday']
a ::: ['and']
s ::: ['sunday', 'sun', 'sets']
e ::: ['east']

Related Programs:

Python Program to Calculate BMI

Program to Calculate BMI

Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

Body Mass Index (BMI) :

The “Quetelet Index ” is another name for the BMI. It is a value calculated using a person’s weight (in kg) and height (in meters), whether male or female. The body mass index (BMI) is calculated by multiplying the body mass by the square of the body height. BMI is measured in kilograms per square meter.

The BMI is used to determine if a person is underweight, normal weight, overweight, or obese. A table with data from the four categories listed above is provided below.

BMI Weight Status
Below 18.5 Underweight
18.5 – 24.9 Normal or Healthy Weight
25.0 – 29.9 Overweight
30.0 and Above Obese

Formula to calculate BMI :

BMI = [mass/(height*height)]

where mass is the body’s mass in kilograms and

height is the body’s height in meters

Given Height, Weight and the task is to calculate BMI for given input values.

Examples:

Example1:

Input:

Given Height = 2.5
Given Weight = 50

Output:

The BMI for the above given values =  8.0
Health status of a person for the above obtained BMI = The person is Underweight

Example2:

Input:

Given Height =  1.5
Given Weight =  70

Output:

The BMI for the above given values =  31.11111111111111
Health status of a person for the above obtained BMI = The person is Suffering from Obesity

Program to Calculate BMI

Below are the ways to Calculate BMI for Given values of height, weight.

Method #1: Using Mathematical Formula (Static input)

Approach:

  • Give the first number as static input and store it in a variable.
  • Give the second number as static input and store it in another variable.
  • Calculate the BMI Value using the above given mathematical formula and store it in another variable.
  • Check If the obtained BMI value is less than 18.5 using the if conditional statement.
  • If it is True, Print “The person is Underweight”.
  • Check If the obtained BMI  is greater than or equal to 18.5 and less than 24.9 using elif conditional statement.
  • If it is True, Print “The person is Healthy”.
  • Check If the obtained BMI  is greater than or equal to 24.9 and less than 30 using elif conditional statement.
  • If it is True, Print “The person is Overweight”.
  • Check If the obtained BMI  is greater than or equal to 30 using elif conditional statement.
  • If it is True, Print “The person is Suffering from Obesity”
  • The Exit of the program.

Below is the implementation:

# Give the first number as static input and store it in a variable.
gvn_heigt = 2.5
# Give the second number as static input and store it in another variable.
gvn_weigt = 50
# Calculate the BMI Value using the above given mathematical formula and
# store it in another variable.
Bmi_vlue = gvn_weigt/(gvn_heigt**2)
print("The BMI for the above given values = ", format(Bmi_vlue))
print("Health status of a person for the above obtained BMI = ", end="")
# Check If the obtained BMI value is less than 18.5 using if conditional statement .
# If it is True, Print "The person is Underweight".
if (Bmi_vlue < 18.5):
    print("The person is Underweight")
# Check If the obtained BMI  is greater than or equal to 18.5 and less than 24.9 using 
# elif conditional statement .
# If it is True, Print "The person is Healthy".
elif (Bmi_vlue >= 18.5 and Bmi_vlue < 24.9):
    print("The person is Healthy")
# Check If the obtained BMI  is greater than or equal to 24.9 and less than 30 using 
# elif conditional statement .
# If it is True, Print "The person is Overweight".
elif (Bmi_vlue >= 24.9 and Bmi_vlue < 30):
    print("The person is Overweight")
# Check If the obtained BMI  is greater than or equal to 30 using 
# elif conditional statement .
# If it is True, Print "The person is Suffering from Obesity"
elif (Bmi_vlue >= 30):
    print("The person is Suffering from Obesity")

Output:

The BMI for the above given values =  8.0
Health status of a person for the above obtained BMI = The person is Underweight

Method #2: Using Mathematical Formula (User input)

Approach:

  • Give the first number as user input using float(input()) and store it in a variable.
  • Give the second number as user input using float(input()) and store it in another variable.
  • Calculate the BMI Value using the above given mathematical formula and store it in another variable.
  • Check If the obtained BMI value is less than 18.5 using the if conditional statement.
  • If it is True, Print “The person is Underweight”.
  • Check If the obtained BMI  is greater than or equal to 18.5 and less than 24.9 using elif conditional statement.
  • If it is True, Print “The person is Healthy”.
  • Check If the obtained BMI  is greater than or equal to 24.9 and less than 30 using elif conditional statement.
  • If it is True, Print “The person is Overweight”.
  • Check If the obtained BMI  is greater than or equal to 30 using elif conditional statement.
  • If it is True, Print “The person is Suffering from Obesity”
  • The Exit of the program.

Below is the implementation:

# Give the first number as user input using float(input()) and store it in a variable.
gvn_heigt = float(input("Enter some Random Number = "))
# Give the second number as user input float(input()) and store it in another variable.
gvn_weigt = float(input("Enter some Random Number = "))
# Calculate the BMI Value using the above given mathematical formula and
# store it in another variable.
Bmi_vlue = gvn_weigt/(gvn_heigt**2)
print("The BMI for the above given values = ", format(Bmi_vlue))
print("Health status of a person for the above obtained BMI = ", end="")
# Check If the obtained BMI value is less than 18.5 using if conditional statement .
# If it is True, Print "The person is Underweight".
if (Bmi_vlue < 18.5):
    print("The person is Underweight")
# Check If the obtained BMI  is greater than or equal to 18.5 and less than 24.9 using 
# elif conditional statement .
# If it is True, Print "The person is Healthy".
elif (Bmi_vlue >= 18.5 and Bmi_vlue < 24.9):
    print("The person is Healthy")
# Check If the obtained BMI  is greater than or equal to 24.9 and less than 30 using 
# elif conditional statement .
# If it is True, Print "The person is Overweight".
elif (Bmi_vlue >= 24.9 and Bmi_vlue < 30):
    print("The person is Overweight")
# Check If the obtained BMI  is greater than or equal to 30 using 
# elif conditional statement .
# If it is True, Print "The person is Suffering from Obesity"
elif (Bmi_vlue >= 30):
    print("The person is Suffering from Obesity")

Output:

Enter some Random Number = 1.5
Enter some Random Number = 70
The BMI for the above given values = 31.11111111111111
Health status of a person for the above obtained BMI = The person is Suffering from Obesity

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Print all the Prime Numbers within a Given Range

Program to Print all the Prime Numbers within a Given Range

Given the upper limit range, the task is to print all the prime numbers in the given range in Python.

Examples:

Example1:

Input:

given number = 95

Output:

The prime numbers from 2 to upper limit [ 95 ] :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89

Example2:

Input:

given number = 52

Output:

Enter some random upper limit range = 52
The prime numbers from 2 to upper limit [ 52 ] :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Python Program to Print all the Prime Numbers within a Given Range

There are several ways to print all the prime numbers from 2 to the upper limit range some of them are:

If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.

Method #1:Using for loop(Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Set the first for loop to have a range of 2 to the upper limit range.
  • Take a temporary variable which is the count variable and initialize it to zero.
  • Allow the second for loop to have a range of 2 to half the number (excluding 1 and the number itself).
  • Then, using the if statement, determine the number of divisors and increment the count variable each time.
  • The number is prime if the number of divisors is lower than or equal to zero.
  • Prime numbers till the given upper limit range are printed.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
givenNumbr = 95
print('The prime numbers from 2 to upper limit [', givenNumbr, '] :')
# Set the first for loop to have a range of 2 to the upper limit range.
for valu in range(2, givenNumbr+1):
  # Take a temporary variable which is the count variable and initialize it to zero.
    cntvar = 0
    # Allow the second for loop to have a range of 2 to
    # half the number (excluding 1 and the number itself).
    for divi in range(2, valu//2+1):
      # Then, using the if statement, determine the number of divisors
      # and increment the count variable each time.
        if(valu % divi == 0):
            cntvar = cntvar+1
    # The number is prime if the number of divisors is lower than or equal to zero.
    if(cntvar <= 0):
        print(valu, end=' ')

Output:

The prime numbers from 2 to upper limit [ 95 ] :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89

All the prime numbers till the upper limit range are printed.

Method #2:Using for loop(User Input)

Approach:

  • Give the number as user input with the help of the int(input()) function and store it in a variable.
  • Set the first for loop to have a range of 2 to the upper limit range.
  • Take a temporary variable which is the count variable and initialize it to zero.
  • Allow the second for loop to have a range of 2 to half the number (excluding 1 and the number itself).
  • Then, using the if statement, determine the number of divisors and increment the count variable each time.
  • The number is prime if the number of divisors is lower than or equal to zero.
  • Prime numbers till the given upper limit range are printed.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input with the help
# of the int(input()) function and store it in a variable.
givenNumbr = int(input('Enter some random upper limit range = '))
print('The prime numbers from 2 to upper limit [', givenNumbr, '] :')
# Set the first for loop to have a range of 2 to the upper limit range.
for valu in range(2, givenNumbr+1):
  # Take a temporary variable which is the count variable and initialize it to zero.
    cntvar = 0
    # Allow the second for loop to have a range of 2 to
    # half the number (excluding 1 and the number itself).
    for divi in range(2, valu//2+1):
      # Then, using the if statement, determine the number of divisors
      # and increment the count variable each time.
        if(valu % divi == 0):
            cntvar = cntvar+1
    # The number is prime if the number of divisors is lower than or equal to zero.
    if(cntvar <= 0):
        print(valu, end=' ')

Output:

Enter some random upper limit range = 52
The prime numbers from 2 to upper limit [ 52 ] :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Explanation:

  • The user must enter the range’s upper limit and save it in a separate variable.
  • The first for loop runs until the user enters an upper limit.
  • The count variable is initially set to 0.
  • Because the for loop runs from 2 to half of the number, 1 and the number itself is not considered divisors.
  • If the remainder is equal to zero, the if statement looks for the number’s divisors.
  • The count variable counts the number of divisors, and if the count is less than or equal to zero, the integer is prime.
  • If the count exceeds zero, the integer is not prime.
  • All the prime numbers till the upper limit range are printed.

Related Programs:

Python Program to Search the Number of Times a Particular Number Occurs in a List

Program to Search the Number of Times a Particular Number Occurs in a List

Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

Lists in Python:

The Python list is a straightforward ordered list of items. Python lists are extremely powerful since the objects in them do not have to be homogeneous or even of the same type. Strings, numbers, and characters, as well as other lists, can all be found in a Python list. Python lists are also mutable: once stated, they can be easily altered via a variety of list methods. Let’s look at how to use these techniques to handle Python lists.

Given a list and a element, the task is to write a  Python Program to Determine the Number of Occurrences of a Specific Number in a given List

Examples:

Examples1:

Input:

given list = ["my", "name", "is", "BTechGeeks", "coding", "platform", "for", "BTechGeeks"]

Output:

The count of the element ' BTechGeeks ' in the list ['my', 'name', 'is', 'BTechGeeks', 'coding', 'platform', 'for', 'BTechGeeks'] = 2

Examples2:

Input:

given list = [5, 9, 1, 3, 6, 9, 2, 12, 8]

Output:

The count of the element ' 9 ' in the list [5, 9, 1, 3, 6, 9, 2, 12, 8] = 2

Python Program to Search the Number of Times a Particular Number Occurs in a List

There are several ways to determine the Number of Occurrences of a Specific Number in a given List some of them are:

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Method #1: Using a Counter Variable

Approach:

  • Scan the given list or give list input as static.
  • Scan the given element or give given element as static.
  • Take a variable which stores the count of the element say countEleme and initialize it to 0.
  • Traverse the given list using for loop.
  • If the iterator element is equal to the given element.
  • Then increment the countEleme value by 1.
  • Print the countEleme.

Below is the implementation:

# given list
given_list = ["my", "name", "is", "BTechGeeks",
              "coding", "platform", "for", "BTechGeeks"]
# given element
given_element = "BTechGeeks"
# Take a variable which stores the count of the element
# say totalCount and initialize it to 0.
countEleme = 0
# Traverse the given list using for loop.
for value in given_list:
    # if the value is equal too given_element then increase the countEleme by 1
    if(value == given_element):
        countEleme = countEleme+1
# Print the countEleme
print("The count of the element '", given_element,
      "' in the list", given_list, "=", countEleme)

Output:

The count of the element ' BTechGeeks ' in the list ['my', 'name', 'is', 'BTechGeeks', 'coding', 'platform', 'for', 'BTechGeeks'] = 2

Method #2: Using Count() function

Approach:

  • Scan the given list or give list input as static.
  • Scan the given element or give given element as static.
  • Count the given element in the list using count() function.
  • Print the countEleme.

Below is the implementation:

# given list
given_list = ["my", "name", "is", "BTechGeeks",
              "coding", "platform", "for", "BTechGeeks"]
# given element
given_element = "BTechGeeks"
# Count the given element in the list using count() function.
countEleme = given_list.count(given_element)
# Print the countEleme
print("The count of the element '", given_element,
      "' in the list", given_list, "=", countEleme)

Output:

The count of the element ' BTechGeeks ' in the list ['my', 'name', 'is', 'BTechGeeks', 'coding', 'platform', 'for', 'BTechGeeks'] = 2

Method #3: Using Counter() function

Approach:

  • Scan the given list or give list input as static.
  • Scan the given element or give given element as static.
  • Use Counter function which stores the frequency as values and element as keys in its dictionary
  • Print the value of the given element

Below is the implementation:

# importing counter function from collections
from collections import Counter
# given list
given_list = ["my", "name", "is", "BTechGeeks",
              "coding", "platform", "for", "BTechGeeks"]
# given element
given_element = "BTechGeeks"
# Using counter function
freqValues = Counter(given_list)
# Count the given element in the list
countEleme = freqValues[given_element]
# Print the countEleme
print("The count of the element '", given_element,
      "' in the list", given_list, "=", countEleme)

Output:

The count of the element ' BTechGeeks ' in the list ['my', 'name', 'is', 'BTechGeeks', 'coding', 'platform', 'for', 'BTechGeeks'] = 2

Method #4:Using List Comprehension

Approach:

  • Scan the given list or give list input as static.
  • Scan the given element or give given element as static.
  • Using list Comprehension checking if given element is equal to the iterator value
  • The count of the length of this new list gives the required answer

Below is the implementation:

# given list
given_list = ["my", "name", "is", "BTechGeeks",
              "coding", "platform", "for", "BTechGeeks"]
# given element
given_element = "BTechGeeks"
# Using list comprehension
elementlist = [eleme for eleme in given_list if eleme == given_element]

# Count the given element in the list using len function
countEleme = len(elementlist)
# Print the countEleme
print("The count of the element '", given_element,
      "' in the list", given_list, "=", countEleme)

Output:

The count of the element ' BTechGeeks ' in the list ['my', 'name', 'is', 'BTechGeeks', 'coding', 'platform', 'for', 'BTechGeeks'] = 2

Pandas: Add Two Columns into a New Column in Dataframe

Methods to add two columns into a new column in Dataframe

In this article, we discuss how to add to column to an existing column in the dataframe and how to add two columns to make a new column in the dataframe using pandas. We will also discuss how to deal with NaN values.

  • Method 1-Sum two columns together to make a new series

In this method, we simply select two-column by their column name and then simply add them.Let see this with the help of an example.

import pandas as pd 
import numpy as np 
students = [('Raj', 24, 'Mumbai', 95) , 
            ('Rahul', 21, 'Delhi' , 97) , 
            ('Aadi', 22, np.NaN, 81) , 
            ('Abhay', 25,'Rajasthan' , 90) , 
            ('Ajjet', 21, 'Delhi' , 74)] 
# Create a DataFrame object 
df = pd.DataFrame( students, columns=['Name', 'Age', 'City', 'Marks']) 
print("Original Dataframe\n") 
print(df,'\n') 
total = df['Age'] + df['Marks']
print("New Series \n") 
print(total)
print(type(total))

Output

Original Dataframe

    Name  Age       City  Marks
0    Raj   24     Mumbai     95
1  Rahul   21      Delhi     97
2   Aadi   22        NaN     81
3  Abhay   25  Rajasthan     90
4  Ajjet   21      Delhi     74 

New Series 

0    119
1    118
2    103
3    115
4     95
dtype: int64
<class 'pandas.core.series.Series'>

Here we see that when we add two columns then a series will be formed.]

Note: We can’t add a string with int or float. We can only add a string with a string or a number with a number.

Let see the example of adding string with string.

import pandas as pd 
import numpy as np 
students = [('Raj', 24, 'Mumbai', 95) , 
            ('Rahul', 21, 'Delhi' , 97) , 
            ('Aadi', 22, 'Kolkata', 81) , 
            ('Abhay', 25,'Rajasthan' , 90) , 
            ('Ajjet', 21, 'Delhi' , 74)] 
# Create a DataFrame object 
df = pd.DataFrame( students, columns=['Name', 'Age', 'City', 'Marks']) 
print("Original Dataframe\n") 
print(df,'\n') 
total = df['Name'] + " "+df['City']
print("New Series \n") 
print(total)
print(type(total))

Output

Original Dataframe

    Name  Age       City  Marks
0    Raj   24     Mumbai     95
1  Rahul   21      Delhi     97
2   Aadi   22    Kolkata     81
3  Abhay   25  Rajasthan     90
4  Ajjet   21      Delhi     74 

New Series 

0         Raj Mumbai
1        Rahul Delhi
2       Aadi Kolkata
3    Abhay Rajasthan
4        Ajjet Delhi
dtype: object
<class 'pandas.core.series.Series'>
  • Method 2-Sum two columns together having NaN values to make a new series

In the previous method, there is no NaN or missing values but in this case, we also have NaN values. So when we add two columns in which one or two-column contains NaN values then we will see that we also get the result as NaN. Let see this with the help of an example.

import pandas as pd 
import numpy as np 
students = [('Raj', 24, 'Mumbai', 95) , 
            ('Rahul', 21, 'Delhi' , 97) , 
            ('Aadi', 22, 'Kolkata', np.NaN) , 
            ('Abhay', np.NaN,'Rajasthan' , 90) , 
            ('Ajjet', 21, 'Delhi' , 74)] 
# Create a DataFrame object 
df = pd.DataFrame( students, columns=['Name', 'Age', 'City', 'Marks']) 
print("Original Dataframe\n") 
print(df,'\n') 
total = df['Marks'] + df['Age']
print("New Series \n") 
print(total)
print(type(total))

Output

Original Dataframe

    Name   Age       City  Marks
0    Raj  24.0     Mumbai   95.0
1  Rahul  21.0      Delhi   97.0
2   Aadi  22.0    Kolkata    NaN
3  Abhay   NaN  Rajasthan   90.0
4  Ajjet  21.0      Delhi   74.0 

New Series 

0    119.0
1    118.0
2      NaN
3      NaN
4     95.0
dtype: float64
<class 'pandas.core.series.Series'>
  • Method 3-Add two columns to make a new column

We know that a dataframe is a group of series. We see that when we add two columns it gives us a series and we store that sum in a variable. If we make that variable a column in the dataframe then our work will be easily done. Let see this with the help of an example.

import pandas as pd 
import numpy as np 
students = [('Raj', 24, 'Mumbai', 95) , 
('Rahul', 21, 'Delhi' , 97) , 
('Aadi', 22, 'Kolkata',76) , 
('Abhay',23,'Rajasthan' , 90) , 
('Ajjet', 21, 'Delhi' , 74)] 
# Create a DataFrame object 
df = pd.DataFrame( students, columns=['Name', 'Age', 'City', 'Marks']) 
print("Original Dataframe\n") 
print(df,'\n') 
df['total'] = df['Marks'] + df['Age']
print("New Dataframe \n") 
print(df)
 
print(df)

Output

Original Dataframe

    Name  Age       City  Marks
0    Raj   24     Mumbai     95
1  Rahul   21      Delhi     97
2   Aadi   22    Kolkata     76
3  Abhay   23  Rajasthan     90
4  Ajjet   21      Delhi     74 

New Dataframe 

    Name  Age       City  Marks  total
0    Raj   24     Mumbai     95    119
1  Rahul   21      Delhi     97    118
2   Aadi   22    Kolkata     76     98
3  Abhay   23  Rajasthan     90    113
4  Ajjet   21      Delhi     74     95
  • Method 4-Add two columns with NaN values to make a new column

The same is the case with NaN values. But here NaN values will be shown.Let see this with the help of an example.

import pandas as pd 
import numpy as np 
students = [('Raj', 24, 'Mumbai', 95) , 
            ('Rahul', 21, 'Delhi' , 97) , 
            ('Aadi', 22, 'Kolkata', np.NaN) , 
            ('Abhay', np.NaN,'Rajasthan' , 90) , 
            ('Ajjet', 21, 'Delhi' , 74)] 
# Create a DataFrame object 
df = pd.DataFrame( students, columns=['Name', 'Age', 'City', 'Marks']) 
print("Original Dataframe\n") 
print(df,'\n') 
df['total'] = df['Marks'] + df['Age']
print("New Dataframe \n") 
print(df)

Output

Original Dataframe

    Name   Age       City  Marks
0    Raj  24.0     Mumbai   95.0
1  Rahul  21.0      Delhi   97.0
2   Aadi  22.0    Kolkata    NaN
3  Abhay   NaN  Rajasthan   90.0
4  Ajjet  21.0      Delhi   74.0 

New Dataframe 

    Name   Age       City  Marks  total
0    Raj  24.0     Mumbai   95.0  119.0
1  Rahul  21.0      Delhi   97.0  118.0
2   Aadi  22.0    Kolkata    NaN    NaN
3  Abhay   NaN  Rajasthan   90.0    NaN
4  Ajjet  21.0      Delhi   74.0   95.0

So these are the methods to add two columns in the dataframe.