Vikram Chiluka

Program to Find Square Root of a Number in C++ and Python Programming

Python Program to Find the Square Root | Square Root in C++

Given a number ,the task is to find the square root of the given number.

Note :

Square root exists for even complex numbers too.

Examples:

Example1:

Input:

number = 16

Output:

The Square root of the given number 16 = 4.0

Example2:

Input:

number = 4 + 3 j

Output:

The Square root of the given number (4+3j) = (2.1213203435596424+0.7071067811865476j)

Example3:

Input:

number = 12

Output:

The Square root of the given number 12 = 3.4641016151377544

Program to Find Square Root of a Number

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:For Positive numbers in Python using math.sqrt function

The math module in Python’s standard library can be used to solve math problems in code. It has a lot of useful functions like remainder() and factorial() (). sqrt, the Python square root function, is also included ().

That’s what there is to it! You can now measure square roots with math.sqrt().

sqrt() has a simple user interface.

It only requires one parameter, x, which represents the square for which you are attempting to calculate the square root (as you might recall). This would be 16 in the previous case.

The square root of x as a floating point number is returned by sqrt(). This will be 4.0 in the case.

We store the number in number and use the sqrt function to find the square root in this program. This program can be used for any positive real number. However, it does not deal for negative or complex numbers.

Below is the implementation:

# importing math module
import math
# given number
number = 16
# finding square root
numberSqrt = math.sqrt(number)
# printing the square root of  given number
print("The Square root of the given number", number, "=", numberSqrt)

Output:

The Square root of the given number 16 = 4.0

Method #2:Using ** operator

We can calculate square root of a number easily by using ** operator.

Below is the implementation:

# importing math module
import math
# given number
number = 16
# finding square root
numberSqrt = number**0.5
# printing the square root of given number
print("The Square root of the given number", number, "=", numberSqrt)

Output:

The Square root of the given number 16 = 4.0

Method #3:Using sqrt function in C++

In C++, the sqrt() function returns the square root of a number.

The <cmath> header file defines this feature.
A single non-negative argument is passed to the sqrt() function.

A domain error occurs when a negative argument is passed to the sqrt() function.

Below is the implementation:

#include <cmath>
#include <iostream>
using namespace std;

int main()
{ // given number
    float number = 16, numberSqrt;
    // calculating the square root of the given number
    numberSqrt = sqrt(number);
    // printing the square root of the given number
    cout << "The square root of the given number " << number
         << " = " << numberSqrt;

    return 0;
}

Output:

The square root of the given number 16 = 4

Method #4:Using cmath.sqrt() function in python

The sqrt() function from the cmath (complex math) module will be used in this program.

Below is the implementation:

# importing cmath module
import cmath
# given complex number
number = 4 + 3j
# finding square root of the given complex number
numberSqrt = cmath.sqrt(number)
# printing the square root of  given number
print("The Square root of the given number", number, "=", numberSqrt)

Output:

The Square root of the given number (4+3j) = (2.1213203435596424+0.7071067811865476j)

Note:

We must use the eval() function instead of float() if we want to take a complex number as input directly, such as 4+5j

In Python, the eval() method can be used to transform complex numbers into complex objects.

 
Related Programs:

Program to Trim Whitespace From a String

Python Program to Trim Whitespace From a String

Strings:

A string in Python is an ordered collection of characters that is used to represent and store text-based data. Strings are stored in a contiguous memory area as individual characters. It can be accessed in both forward and backward directions. Characters are merely symbols. Strings are immutable Data Types in Python, which means they can’t be modified once they’ve been generated.

Trim in Python:

What does it mean to trim a string, and how do you accomplish it in Python? Trimming a string refers to the process of removing whitespace from around text strings.

Given a string, the task is to trim the white spaces in the given string.

Examples:

Example1:

Input:

given_string = "    B     T  e  c  h   G    e       e      k   s       "

Output:

Before removing white spaces given string=   B Tec  h G e         e    k s    
after removing white spaces given string= BTechGeeks

Removing trialing and leading whitespaces

Example3:

Input:

given_string = "            croyez              "

Output:

Before removing white spaces given string=         croyez             
after removing white spaces given string= croyez

Example2:

Input:

given_string = "          BtechGeeks          "

Output:

Before removing white spaces given string=           BtechGeeks               
after removing white spaces given string= BtechGeeks

Program to Trim Whitespace From a String in Python

There are several ways to trim the whitespace from the given string 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 replace() function

Replace() function:

The replace() method copies the string and replaces the previous substring with the new substring. The original string has not been altered.

If the old substring cannot be retrieved, the copy of the original string is returned.

We can use the replace() function in python to trim the white spaces in Python.

We need to replace the white space with empty string to achieve our task.

Below is the implementation:

# given string
given_string = "  B Tec  h G e        e    k s    "
# printing the original string before removing white spaces
print("Before removing white spaces given string=", given_string)
# removing white spaces from the given string
# using replace() function
# we replace white space with empty string

given_string = given_string.replace(" ", "")
# printing the original string before after white spaces
print("after removing white spaces given string=", given_string)

Output:

Before removing white spaces given string=   B Tec  h G e        e    k s    
after removing white spaces given string= BTechGeeks

Method #2:Using split() and join() functions

Below is the implementation:

# given string
given_string = "          B  t      echG   eeks               "
# printing the original string before removing white spaces
print("Before removing white spaces given string=", given_string)
# removing white spaces from the given string
given_string = "".join(given_string.split())
# printing the original string before after white spaces
print("after removing white spaces given string=", given_string)

Output:

Before removing white spaces given string=           B  t      echG   eeks               
after removing white spaces given string= BtechGeeks

Removing only leading and Trailing whitespaces:

Method #3:Using strip()

String in Python. The strip() function, as the name implies, eliminates all leading and following spaces from a string. As a result, we may use this method in Python to completely trim a string.

Syntax:

string.strip(character)

Character : It is a non-mandatory parameter. If the supplied character is supplied to the strip() function, it will be removed from both ends of the string.

Below is the implementation:

# given string
given_string = "          BtechGeeks               "
# printing the original string before removing white spaces
print("Before removing white spaces given string=", given_string)
# removing white spaces from the given string
# removing trailing and leading white spaces

given_string = given_string.strip()
# printing the original string before after white spaces
print("after removing white spaces given string=", given_string)

Output:

Before removing white spaces given string=           BtechGeeks               
after removing white spaces given string= BtechGeeks

strip() removes the leading and trailing characters from a string, as well as whitespaces.

However, if the string contains characters such as ‘\n’ and you wish to remove only the whitespaces, you must specifically mention it in the strip() method, as seen in the following code.

Explanation:

Here the regular Expression removes only the leading and trailing whitespaces from the given string

Method #4:Using Regex

We can remove leading and trailing whitespaces in regex as shown below:

Below is the implementation:

# importing regex
import re
# given string
given_string = "       BtechGeeks        "
# printing the original string before removing white spaces
print("Before removing white spaces given string=", given_string)
# using regex to remove trailing and leading white spaces from the given string
given_string = re.sub(r'^\s+|\s+$', '', given_string)
# printing the original string before after white spaces
print("after removing white spaces given string=", given_string)
Before removing white spaces given string=        BtechGeeks        
after removing white spaces given string= BtechGeeks

Explanation:

Here the regular Expression removes only the leading and trailing whitespaces from the given string
Related Programs:

Program to Remove Punctuations From a String

Python Program to Remove Punctuations From a String

Strings:

A string in Python is an ordered collection of characters that is used to represent and store text-based data. Strings are stored in a contiguous memory area as individual characters. It can be accessed in both forward and backward directions. Characters are merely symbols. Strings are immutable Data Types in Python, which means they can’t be modified once they’ve been generated.

Punctuation:

Punctuation is the practice, action, or method of putting points or other small marks into texts to help comprehension; the division of text into phrases, clauses, and so on.

Punctuation is really effective. They have the ability to completely alter the meaning of a sentence.

Given a string, the task is to remove the punctuations from the given string in python.

Examples:

Example1:

Input:

given_string="BTechGeeks, is best : for ! Python.?[]() ;"

Output:

printing the given string after removing the punctuations : 
BTechGeeks is best for Python

Example2:

Input:

given_string="pythond dsf,;]]][-*&$%@#^()!or ! Python.?[]() ;"

Output:

printing the given string after removing the punctuations : 
pythond dsfor  Python

Remove Punctuations From a String in Python

When working with Python strings, we frequently run into situations where we need to remove specific characters. This can be used for data preprocessing in the Data Science domain as well as day-to-day programming. Let’s look at a few different approaches to doing this work.

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 for loop and string concatenation

This is the most brute method of accomplishing this operation. We do this by checking for punctuations in raw strings that contain punctuations, and then constructing a string without those punctuations.

To begin, we’ll create a string of punctuations. Then, using a for loop, we iterate over the specified string.

The membership test is used in each iteration to determine if the character is a punctuation mark or not. If the character is not punctuation, we add (concatenate) it to an empty string. Finally, we show the string that has been cleaned up.

Below is the implementation:

# taking a string which stores all the punctuations and
# initialize it with some punctuations
punctuationString = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
# given string which we want  to remove the punctuation marks
given_string = "BTechGeeks, is best: for !Python.?[]() ;"

# Taking a empty which stores all the characteers of original string without punctuations
noPunctuationString = ""
# removing all punctuations from the string
# Traversing the original string
for character in given_string:
  # if character not in punctuationString which means it is not a punctuation
  # hence concate this character to noPunctuationString
    if character not in punctuationString:
        noPunctuationString = noPunctuationString + character

# printing the given string after removing the punctuations
print("printing the given string after removing the punctuations : ")
print(noPunctuationString)

Output:

printing the given string after removing the punctuations : 
BTechGeeks is best for Python

Method #2:Using for loop and replace() function

This is the most brute method of accomplishing this operation. We do this by checking for punctuations in raw strings that contain punctuations, and then constructing a string without those punctuations.

Approach:

  • Make a string out of all the punctuation characters.
  • Create a for loop and an if statement for each iteration such that if a punctuation character is detected, it is replaced by a white space.

Below is the implementation:

# taking a string which stores all the punctuations and
# initialize it with some punctuations
punctuationString = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
# given string which we want  to remove the punctuation marks
given_string = "BTechGeeks, is best: for !Python.?[]() ;"

# removing all punctuations from the string
# Traversing the original string
for character in given_string:
  # if character  in punctuationString which means it is  a punctuation
  # hence replace it with white space
    if character in punctuationString:
        given_string = given_string.replace(character, "")
# printing the given string after removing the punctuations
print("printing the given string after removing the punctuations : ")
print(given_string)

Output:

printing the given string after removing the punctuations : 
BTechGeeks is best for Python

Method #3:Using Regex

The regex module in Python allows us to work with and alter various regular expressions.

To deal with regular expressions, we’ll need to import the library listed below:

import re

To remove the punctuation marks, we’ll use re.sub(pattern, replacement, given string).
Pattern : We wish to replace the punctuation marks or the pattern of expressions with this pattern.
Replacement: The string that will be used to replace the pattern.
We’ll also utilise the re.sub() method to replace the punctuation marks with the substitute ‘ ‘, which is a white space.

Below is the implementation:

# importing regex
import re
# given string which we want  to remove the punctuation marks
given_string = "BTechGeeks, is best: for !Python.?[]() ;"
# using regex
noPunctuationString = re.sub(r'[^\w\s]', '', given_string)

# printing the given string after removing the punctuations
print("printing the given string after removing the punctuations : ")
print(noPunctuationString)

Output:

printing the given string after removing the punctuations : 
BTechGeeks is best for Python

Related Programs:

Python Program to Swap Two Variables

Python Program to Swap Two Variables

Swapping:

Swapping two variables in computer programming means that the variables values are swapped.

Given two variables x , y the task is to swap the variable values.

Examples:

Example1:(Integer Values Swapping)

Input:

p=1372 q=4129

Output:

printing the values of integer variables p and q before swapping
p = 1372
q = 4129
printing the values of integer variables p and q after swapping
p = 4129
q = 1372

Example2:(Boolean Values Swapping)

Input:

p=True q=False

Output:

printing the values of boolean variables p and q before swapping
p = True
q = False
printing the values of boolean variables p and q after swapping
p = False
q = True

Example3:(Decimal Values Swapping)

Input:

p = 2738.321  q = 83472.421

Output:

printing the values of decimal variables p and q before swapping
p = 2738.321
q = 83472.421
printing the values of decimal variables p and q after swapping
p = 83472.421
q = 2738.321

Example4:(String Values Swapping)

Input:

p="Vicky" q="Tara"

Output:

printing the values of string variables p and q before swapping
p = vicky
q = Tara
printing the values of string variables p and q after swapping
p = Tara
q = vicky

Swapping two Variables in Python

There are several ways to swap two variables in Python 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 temporary Variable

A temp variable is the easiest way to change the values of two variables. The temp variables will save the value of the fist variable (temp = a), allow the two variables to swap (a = b), and assign the them to the second variable. The temp variables will then be saved.

Below is the implementation:

# given variables of different types
# given two integer variables
p = 1372
q = 4129
# printing the values of p and q before swapping
print("printing the values of integer variables p and q before swapping")
print("p =", p)
print("q =", q)
# using temp variable to swap the two integers
# swapping two variables
tempo = p
p = q
q = tempo
# printing the values of p and q after swapping
print("printing the values of integer variables p and q after swapping")
print("p =", p)
print("q =", q)
# given two decimal variables
p = 2738.321
q = 83472.421
# printing the values of p and q before swapping
print("printing the values of decimal variables p and q before swapping")
print("p =", p)
print("q =", q)
# using temp variable to swap the two decimal variables
# swapping two variables
tempo = p
p = q
q = tempo
# printing the values of p and q after swapping
print("printing the values of decimal variables p and q after swapping")
print("p =", p)
print("q =", q)
# given two boolean variables
p = True
q = False
# printing the values of p and q before swapping
print("printing the values of boolean variables p and q before swapping")
print("p =", p)
print("q =", q)
# using temp variable to swap the two boolean values
# swapping two variables
tempo = p
p = q
q = tempo
# printing the values of p and q after swapping
print("printing the values of boolean variables p and q after swapping")
print("p =", p)
print("q =", q)
# given two string variables
p = "vicky"
q = "Tara"
# printing the values of p and q before swapping
print("printing the values of string variables p and q before swapping")
print("p =", p)
print("q =", q)
# using temp variable to swap the two string
# swapping two variables
tempo = p
p = q
q = tempo
# printing the values of p and q after swapping
print("printing the values of string variables p and q after swapping")
print("p =", p)
print("q =", q)

Output:

printing the values of integer variables p and q before swapping
p = 1372
q = 4129
printing the values of integer variables p and q after swapping
p = 4129
q = 1372
printing the values of decimal variables p and q before swapping
p = 2738.321
q = 83472.421
printing the values of decimal variables p and q after swapping
p = 83472.421
q = 2738.321
printing the values of boolean variables p and q before swapping
p = True
q = False
printing the values of boolean variables p and q after swapping
p = False
q = True
printing the values of string variables p and q before swapping
p = vicky
q = Tara
printing the values of string variables p and q after swapping
p = Tara
q = vicky

Method #2:Using comma operator in Python without temporary variable(Tuple Swap)

The tuple packaging and sequence unpackaging can also be used to change the values of two variables without a temporary variable. There are a number of methods in which tuples can be created, including by dividing tuples using commas. In addition, Python evaluates the right half of a task on its left side. Thus the variables are packed up and unpacked with the same amount of commas separating the target variables on the left hand side by selecting the comma on the right hand hand side of the sentence.

It may be used for more than two variables, provided that both sides of the state have the same amount of variables

Below is the implementation:

# given variables of different types
# given two integer variables
p = 1372
q = 4129
# printing the values of p and q before swapping
print("printing the values of integer variables p and q before swapping")
print("p =", p)
print("q =", q)
# swapping two variables
p, q = q, p
# printing the values of p and q after swapping
print("printing the values of integer variables p and q after swapping")
print("p =", p)
print("q =", q)
# given two decimal variables
p = 2738.321
q = 83472.421
# printing the values of p and q before swapping
print("printing the values of decimal variables p and q before swapping")
print("p =", p)
print("q =", q)
# swapping two variables
p, q = q, p
# printing the values of p and q after swapping
print("printing the values of decimal variables p and q after swapping")
print("p =", p)
print("q =", q)
# given two boolean variables
p = True
q = False
# printing the values of p and q before swapping
print("printing the values of boolean variables p and q before swapping")
print("p =", p)
print("q =", q)
# swapping two variables
p, q = q, p
# printing the values of p and q after swapping
print("printing the values of boolean variables p and q after swapping")
print("p =", p)
print("q =", q)
# given two string variables
p = "vicky"
q = "Tara"
# printing the values of p and q before swapping
print("printing the values of string variables p and q before swapping")
print("p =", p)
print("q =", q)
# swapping two variables
p, q = q, p
# printing the values of p and q after swapping
print("printing the values of string variables p and q after swapping")
print("p =", p)
print("q =", q)

Output:

printing the values of integer variables p and q before swapping
p = 1372
q = 4129
printing the values of integer variables p and q after swapping
p = 4129
q = 1372
printing the values of decimal variables p and q before swapping
p = 2738.321
q = 83472.421
printing the values of decimal variables p and q after swapping
p = 83472.421
q = 2738.321
printing the values of boolean variables p and q before swapping
p = True
q = False
printing the values of boolean variables p and q after swapping
p = False
q = True
printing the values of string variables p and q before swapping
p = vicky
q = Tara
printing the values of string variables p and q after swapping
p = Tara
q = vicky

Related Programs:

Program to Count the Number of Digits Present In a Number

Python Program to Count the Number of Digits Present In a Number

Count the number of numbers in a number using Python. We learn how to count the total number of digits in a number using python in this tutorial. The program receives the number and prints the total number of digits in the given number. We’ll show you three ways to calculate total numbers in a number.

Examples:

Example1:

Input:

number = 27482

Output:

The total digits present in the given number= 5

Example2:

Input:

number = 327

Output:

The total digits present in the given number= 3

Program to Count the Number of Digits Present In a Number in Python

There are several ways to count the number of digits present in a number 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 while loop

The idea behind this approach is to keep eliminating the number’s rightmost digit one by one until the number reaches zero. The following algorithm will be used for this approach:

Approach:

  • Scan the input or give static input and store it in number variable
  • Make one counter variable to keep track of the entire number count. At the start of the program, set this variable to zero.
  • Using a while loop, eliminate the number’s rightmost digit or convert the number to this new number. For instance, if the number is 782, convert it to 78, then to 7, and lastly to 0.
  • On each conversion, increment the counter variable by one. Continue until the number reaches zero. This counter variable will hold the total digit count of the number at the end of the while loop.
  • Print the counter variable.

Below is the implementation:

# given number
given_number = 27482
# initializing a variable that counts the digit of the given number.
# initlaize it with 0
digits_count = 0
# using while loop to traverse digit by digit of the given number
while (given_number > 0):
    # divide the number by 10
    given_number = given_number//10
    # increment the count
    digits_count = digits_count + 1
# printing the digits count of the given number
print("The total digits present in the given number=", digits_count)

Output:

The total digits present in the given number= 5

Explanation:

  • The while loop is iterated in this program until the test expression given_num!= 0 is evaluated to 0 (false).
  • After the first repetition, given_num will be divided by 10 and will have the value 2748. The count is then increased to 1.
  • The result of given_num after the second iteration is 274, and the count is increased to 2.
  • The value of given_num will be 27 after the third iteration, and the count will be 3.
  • The value of given_num will be 2 after the fourth iteration, and the count will be increased to 4.
  • The value of given_num will be 0 after the fourth iteration, and the count will be increased to 5.
  • The loop then ends when the condition is false.

Method #2:Using string length function

We begin by converting the number value to a string using str (). The length of the string is then determined using len ().

Below is the implementation:

# given number
given_number = 27482
# converting the given_number to string using str() function
strnum = str(given_number)
# finding the digits of the given_number using len() function
digits_count = len(strnum)
# printing the digits count of the given number
print("The total digits present in the given number=", digits_count)

Output:

The total digits present in the given number= 5

Method #3:Converting number to list and calculating length of list

Approach:

  • We first convert the given number to string using str function.
  • Then we convert this string to list of digits using list() function.
  • Then calculate the length of list using len() function in list.

Below is the implementation:

# given number
given_number = 27482
# converting the given_number to list of digits using list() function
numberslist = list(str(given_number))
# finding the digits of the given_number using len() function
digits_count = len(numberslist)
# printing the digits count of the given number
print("The total digits present in the given number=", digits_count)

Output:

The total digits present in the given number= 5

This is similar to method #2
Related Programs:

Program to Display Calendar

Program to Display Calendar in Python

To work with date-related tasks, Python has a built-in function called calendar. In this posts, you will learn how to display the calendar for a specific date.

The calendar class in Python’s Calendar module allows for calculations based on date, month, and year for a variety of tasks. Furthermore, the Text Calendar and HTML Calendar classes in Python allow you to customize the calendar and use it as needed.

Examples:

Input:

given year=2001 month =2

Output:

   February 2001
Mo Tu We Th Fr Sa Su
                   1   2   3  4
 5    6    7    8   9  10 11
12  13 14  15 16  17 18
19  20 21  22 23  24 25
26  27 28

Program to Display Calendar in Python

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)Displaying the month

To print a calendar in Python, we can use the built-in function month() from the Calendar module. To display a Calendar for a given month, the function month() requires two arguments: the first is the year in four-digit format, such as 2003, 1997, 2018, and the second is the month in two-digit format, such as 01, 04, 12, and so on.

This program prompts the user for the year and month, and then calls the month() function, which displays the Calendar for the given month for a given year, based on the input.

Below is the implementation:

# importing calendar function
import calendar

# given year
given_year = 2001

# given month
given_month = 2

# printing the calendar of given year and month
print(calendar.month(given_year, given_month))

Output:

   February 2001
Mo Tu We Th Fr Sa Su
                   1   2   3  4
 5    6    7    8   9  10 11
12  13 14  15 16  17 18
19  20 21  22 23  24 25
26  27 28

2)Displaying the year

The calendar module is imported in the program  below. The module’s built-in function calender() accepts a year and displays the calendar for that year.

Below is the implementation:

# importing calendar function
import calendar
# given year
given_year = 2001
# printing the calendar of given year
print(calendar.calendar(given_year))

Output:

                                                            2001
   
      January                   February                   March
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
        1  2  3  4  5  6  7                1  2  3  4                1  2  3  4
 8    9  10  11 12 13 14       5  6  7  8  9 10 11       5  6  7  8  9 10 11
15  16  17   18   19   20   21      12 13 14 15 16 17 18      12 13 14 15 16 17 18
22  23  24  25 26 27 28      19 20 21 22 23 24 25      19 20 21 22 23 24 25
29 30 31                  26 27 28                  26 27 28 29 30 31

       April                      May                       June
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
                   1                         1  2  3  4  5  6                   1  2  3
 2  3  4  5  6  7  8                7  8  9 10 11 12 13          4  5  6  7  8  9 10
 9 10 11 12 13 14 15      14 15 16 17 18 19 20        11 12 13 14 15 16 17
16 17 18 19 20 21 22      21 22 23 24 25 26 27        18 19 20 21 22 23 24
23 24 25 26 27 28 29      28 29 30 31                            25 26 27 28 29 30
30

        July                                August                   September
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
                   1                          1  2  3  4  5                                              1  2
 2  3  4  5  6  7  8                  6  7  8  9 10 11 12                   3  4  5  6  7  8  9
 9 10 11 12 13 14 15      13 14 15 16 17 18 19         10 11 12 13 14 15 16
16 17 18 19 20 21 22      20 21 22 23 24 25 26         17 18 19 20 21 22 23
23 24 25 26 27 28 29      27 28 29 30 31                 24 25 26 27 28 29 30
30 31

      October                   November                  December
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7                1  2  3  4                            1  2
 8  9 10 11 12 13 14                5  6  7  8  9 10 11                      3  4  5  6  7  8  9
15 16 17 18 19 20 21      12 13 14 15 16 17 18      10 11 12 13 14 15 16
22 23 24 25 26 27 28      19 20 21 22 23 24 25      17 18 19 20 21 22 23
29 30 31                             26 27 28 29 30            24 25 26 27 28 29 30
                                                    31

 
Related Programs:

Find the Largest Among Three Numbers

Python Program to Find the Largest Among Three Numbers

Given three numbers the task is to find the largest number among the three numbers.

Prerequisite:

Python IF…ELIF…ELSE Statements

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.

Examples:

Input:

number1 = 3
number2 = 5
number3 = 7

Output:

The largest number among the three numbers = 7

Input:

number1 = 9
number2 = 9
number3 = 2

Output:

The largest number among the three numbers = 9

Determine the largest of three numbers

Below are the ways to determine the largest among the three numbers:

Method #1 :Using Conditional Statements

The three numbers are stored in number 1, number 2, and number 3, in that order. We use the if…elif…else ladder to find and show the largest of the three.

Here we compare one number with other two numbers using if..elif…else ladder.

Below is the implementation:

# function which returns the largest number among the three numbers
def findLargest(number1, number2, number3):
  # comparing first number with other two numbers
    if (number1 >= number2) and (number1 >= number3):
        return(number1)
      # comparing second number with other two numbers
    elif (number2 >= number1) and (number2 >= number3):
        return(number2)
    else:
        return(number3)


number1 = 3
number2 = 5
number3 = 7
# passing the three numbers to find largest number among the three numbers
print("The largest number among the three numbers =",
      findLargest(number1, number2, number3))

Output:

The largest number among the three numbers = 7

Method #2: Using max function

We can directly use max function to know the largest number among the three numbers.

We provide the given three numbers as arguments to max function and print it.

Below is the implementation:

number1 = 3
number2 = 5
number3 = 7
# using max function to find largest numbers
maxnum = max(number1, number2, number3)
print("The largest number among the three numbers =",
      maxnum)

Output:

The largest number among the three numbers = 7

Method #3: Converting the numbers to list and using max function to print max element of list

Approach:

  • Convert the given number to list using [].
  • Print the maximum element of list using max() function

Below is the implementation:

number1 = 3
number2 = 5
number3 = 7
# converting given 3 numbers to list
listnum = [number1, number2, number3]
# using max function to find largest numbers from the list
maxnum = max(listnum)
print("The largest number among the three numbers =",
      maxnum)

Output:

The largest number among the three numbers = 7

Related Programs:

Program to Display the Multiplication Table

Python Program to Display the Multiplication Table

Given a number the task is to print the multiplication table of the given number from 1 to 10.

Prerequisite:

1)For Loop in python

2)While Loop in python

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.

Examples:

Example 1:

Input:

number=8

Output:

8 * 1 = 8
8 * 2 = 16
8 * 3 = 24
8 * 4 = 32
8 * 5 = 40
8 * 6 = 48
8 * 7 = 56
8 * 8 = 64
8 * 9 = 72
8 * 10 = 80

Example 2:

Input:

number=34

Output:

34 * 1 = 34
34 * 2 = 68
34 * 3 = 102
34 * 4 = 136
34 * 5 = 170
34 * 6 = 204
34 * 7 = 238
34 * 8 = 272
34 * 9 = 306
34 * 10 = 340

Program to Print the Multiplication Table

Below are the ways to print the multiplication table:

Method #1:Using for loop

Approach:

To iterate 10 times, we used the for loop in combination with the range() function. The range() function’s arguments are as follows: (1, 11). That is, greater than or equal to 1 and less than 11.

We’ve shown the variable num multiplication table (which is 8 in our case). To evaluate for other values, adjust the value of num in the above program.

Below is the implementation:

# given number
number = 8
# using for loop with range
for i in range(1, 11):
    print(number, "*", i, "=", number*i)

Output:

8 * 1 = 8
8 * 2 = 16
8 * 3 = 24
8 * 4 = 32
8 * 5 = 40
8 * 6 = 48
8 * 7 = 56
8 * 8 = 64
8 * 9 = 72
8 * 10 = 80

Method #2:Using While loop

Approach:

  • First we initialize a variable say multiplicationfactor to 1.
  • We increment the value of  multiplicationfactor by 1 till the multiplicationfactor is less than or equal to 10.
  • Print the multiplication table.

Below is the implementation:

# given number
number = 8
# initializing a variable say multiplication factor to 1
multiplicationfactor = 1
# loop till multiplicationfactor is less than or equal to 10
while(multiplicationfactor <= 10):
    print(number, "*", multiplicationfactor, "=", number*multiplicationfactor)
    # increment the multiplicationfactor by 1
    multiplicationfactor = multiplicationfactor+1

Output:

8 * 1 = 8
8 * 2 = 16
8 * 3 = 24
8 * 4 = 32
8 * 5 = 40
8 * 6 = 48
8 * 7 = 56
8 * 8 = 64
8 * 9 = 72
8 * 10 = 80

Related Programs:

Program to Find the Sum of Natural Numbers

Python Program to Find the Sum of Natural Numbers

Natural Number:

A natural number, as the name implies, is a number that occurs often and clearly in nature. It is a whole number with no negative digits.

Some mathematicians agree that a natural number must contain 0 while others do not. As a result, a list of natural numbers can be described as follows

N= 1 , 2 , 3 , 4 , 5 etc.

Prerequisite:

  1. For Loop in python
  2. While Loop in python

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.

Examples:

Example 1:

Input :

number = 5

Output:

Sum of natural numbers till 5 = 15

Example 2:

Input :

number = 43

Output:

Sum of natural numbers till 43 = 946

Program to Find the Sum of Natural Numbers in Python

Below are the ways to print the sum of natural numbers in python:

Method #1:Using for loop

  • Take a variable say sum and initialize to 0
  • Iterate from 1 to N using for loop and range() function.
  • For each iteration add the iterater value to sum.
  • Print the sum.

Below is the implementation:

# given number
number = 5
# Take a variable say sum and initialize to 0.
sum = 0
# Iterate from 1 to number using for loop and range function
for i in range(1, number+1):
    # add the iterater value to sum.
    sum = sum + i
# print the sum
print("Sum of natural numbers till", number, "=", sum)

Output:

Sum of natural numbers till 5 = 15

Method #2:Using while loop

  • Take a variable say sum and initialize to 0
  • The while loop was used to iterate until number became zero.
  • In each loop iteration, we have added the number to sum and decreased the value of number by 1.
  • Print the sum.

Below is the implementation:

# given number
number = 5
# Take a variable say sum and initialize to 0.
sum = 0
# iterate till the number becomes 0 using while loop
while(number != 0):
    # add the number value to sum
    sum = sum+number
    # decrement the number
    number = number-1
# print the sum
print("Sum of natural numbers", "=", sum)

Output:

Sum of natural numbers = 15

Method #3:Using mathematical formula

Instead of iterating till number the best and efficient solution is to use mathematical formula given below.

Formula:

sum = ( n * (n +1) ) / 2

Below is the implementation:

# given number
number = 5
# Using mathematical formula
sum = (number * (number+1))//2
# print the sum
print("Sum of natural numbers till", number, "=", sum)

Output:

Sum of natural numbers till 5 = 15

Related Programs:

Compute the Power of a Number

Python Program to Compute the Power of a Number

Power:

A power is an expression that describes repeated multiplication of the same factor.

Examples:

Example1:

Positive Exponent:

Input:

base = 7 power = 4

Output:

The result is 2401

Example2:

Negative Exponent:

Input:

base = 7 power = -2

Output:

The result is 0.02040816326530612

This article will teach you how to compute the power of a number.

Calculate the Power of a Number

Below are the ways to calculate the power of a number :

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 While loop

  • Scan the base and power values.
  • Create a variable resultValue and initialize it with 1.
  • Using the while loop, we continue to multiply the resultValue by the base until the exponent reaches zero.
  • Print the resultValue.

Below is the implementation:

# given base value and power value
baseValue = 7
powerValue = 4
# initialize the result value to 1
resultValue = 1
# Loop till power becomes 0
while powerValue != 0:
    resultValue = resultValue * baseValue
    powerValue = powerValue-1

print("The result is", resultValue)

Output:

The result is 2401

Method #2: Using For loop

  • Instead of a while loop, we’ve used a for loop here.
  • Scan the base and power values.
  • Create a variable resultValue and initialize it with 1.
  • The exponent is decremented by one for each iteration, and the resultValue is multiplied by the base exponent a number of times.
  • Print the resultValue.

Below is the implementation:

# given base value and power value
baseValue = 7
powerValue = 4
# initialize the result value to 1
resultValue = 1
# Loop till power becomes 0 using for loop
for i in range(powerValue):
    resultValue = resultValue*baseValue
    # decrement the powerValue
    powerValue = powerValue-1

print("The result is", resultValue)

Output:

The result is 2401

Note:

If you have a negative exponent, none of the above methods will function.
You must use the pow() function from the Python library to accomplish this.

Method #3:Using pow() function

We can calculate the power value using pow() function.

It works for negative exponent too.

1)Calculating the power of positive exponent

Below is the implementation:

# given base value and power value
baseValue = 7
powerValue = 4
# calculating the power of base
resultValue = pow(baseValue, powerValue)
# print the result
print("The result is", resultValue)

Output:

The result is 2401

2)Calculating the power of negative exponent

Below is the implementation:

# given base value and power value
baseValue = 7
powerValue = -2
# calculating the power of base
resultValue = pow(baseValue, powerValue)
# print the result
print("The result is", resultValue)

Output:

The result is 0.02040816326530612

Method #4:Using ** operator in Python

We can calculate the power value using ** .

It works for negative exponent too.

1)Calculating the power of positive exponent

Below is the implementation:

# given base value and power value
baseValue = 7
powerValue = 4
# calculating the power of base
resultValue = baseValue**powerValue
# print the result
print("The result is", resultValue)

Output:

The result is 2401

2)Calculating the power of negative exponent

Below is the implementation:

# given base value and power value
baseValue = 7
powerValue = -2
# calculating the power of base
resultValue = baseValue**powerValue
# print the result
print("The result is", resultValue)

Output:

The result is 0.02040816326530612

Related Programs: