Author name: Vikram Chiluka

Python BMI Calculator – A Complete Step-by-Step Tutorial

In this article, we will learn how to develop a Body Mass Index (BMI) Calculator using the Python programming language. But before we begin developing one, let us first define Body Mass Index (BMI).

Body Mass Index (BMI):

BMI, or Body Mass Index, is a measure of relative weight based on an individual’s weight and height. The Body Mass Index is commonly used to classify people based on their height and weight. These classifications include underweight, healthy, overweight, and even obesity. Furthermore, it is being used by a number of countries to promote healthy eating.

Body Mass Index (BMI) can be used as a substitute for direct measures of body fat. Furthermore, BMI is a low-cost and simple means of screening for weight classes that may cause health problems.

Let Us Understand the BMI Calculator’s Operation

A BMI Calculator takes an individual’s weight and height and computes their Body Mass Index (BMI).

The data below illustrates how BMI is classified in order to determine a person’s health state.

  • If your BMI is less than 18.5, it falls within the underweight range.
  • If your BMI is 18.5 to 24.9, it falls within the normal or Healthy Weight range.
  • If your BMI is 25.0 to 29.9, it falls within the overweight range.
  • If your BMI is 30.0 or higher, it falls within the obese range.

The Formula for Calculating BMI:

BMI  = (weight)/(height)^2

where weight  in – kg

and height in – m

Python Code

Method #1: Using Built-in Functions (Static Input)

Approach:

  • Give the height as static input and store it in a variable.
  • Give the weight as static input and store it in another variable.
  • Calculate the Body Mass Index(BMI) value using the above given mathematical formula and store it in another variable.
  • Check if the above obtained BMI value is greater than 0 using the if conditional statement.
  • If it is true, then check again if the above obtained BMI value is less than or equal to 16.
  • If it is true, then print “Person is severely underweight. Please Takecare”.
  • Check if the above obtained BMI value is less than or equal to 18.5 using the elif conditional statement.
  • If it is true, then print “Person is Underweight”.
  • Check if the obtained BMI value is less than or equal to 25 using the elif conditional statement.
  • If it is true, then print “Person is Healthy”.
  • Check if the obtained BMI value is less than or equal to 30 using the elif conditional statement.
  • If it is true, then print “Person is Overweight”.
  • Else print “Person is suffering from Obesity”.
  • Else print “Invalid Input”.
  • The Exit of the Program.

Below is the implementation:

# Give the height as static input and store it in a variable.
gvn_height = 2.5
# Give the weight as static input and store it in another variable.
gvn_weight = 45
# Calculate the Body Mass Index(BMI) value using the above given mathematical
# formula and store it in another variable.
rslt_BMI = gvn_weight/(gvn_height*gvn_height)
print("The BMI value for the given height{",
      gvn_height, "}", "and weight{", gvn_weight, "}=", rslt_BMI)
# Check if the above obtained BMI value is greater than 0 using the if conditional
# statement.
if(rslt_BMI > 0):
    # If it is true, then check again if the above obtained BMI value is less than
    # or equal to 16. 
    if(rslt_BMI <= 16):
        # If it is true, then print "Person is severely underweight.Please Takecare".
        print("Person is severely underweight. Please Takecare")
    # Check if the above obtained BMI value is less than or equal to 18.5 using
    # the elif conditional statement. 
    elif(rslt_BMI <= 18.5):
        # If it is true, then print "Person is Underweight".
        print("Person is Underweight")
    # Check if the obtained BMI value is less than or equal to 25 using the elif
        # conditional statement.
    elif(rslt_BMI <= 25):
        # If it is true, then print "Person is Healthy".
        print("Person is Healthy")
    # Check if the obtained BMI value is less than or equal to 30 using the elif
        # conditional statement. 
    elif(rslt_BMI <= 30):
        # If it is true, then print "Person is Overweight".
        print("Person is Overweight")
    else:
        # Else print "Person is suffering from Obesity".
        print("Person is suffering from Obesity")
# Else print "Invalid Input".
else:
    print("Invalid Input")

Output:

The BMI value for the given height{ 2.5 } and weight{ 45 }= 7.2
Person is severely underweight. Please Takecare

Method #2: Using Built-in Functions (User Input)

Approach:

  • Give the height as user input using the float(input()) function and store it in a variable.
  • Give the weight as user input using the float(input()) function and store it in another variable.
  • Calculate the Body Mass Index(BMI) value using the above given mathematical formula and store it in another variable.
  • Check if the above obtained BMI value is greater than 0 using the if conditional statement.
  • If it is true, then check again if the above obtained BMI value is less than or equal to 16.
  • If it is true, then print “Person is severely underweight. Please Takecare”.
  • Check if the above obtained BMI value is less than or equal to 18.5 using the elif conditional statement.
  • If it is true, then print “Person is Underweight”.
  • Check if the obtained BMI value is less than or equal to 25 using the elif conditional statement.
  • If it is true, then print “Person is Healthy”.
  • Check if the obtained BMI value is less than or equal to 30 using the elif conditional statement.
  • If it is true, then print “Person is Overweight”.
  • Else print “Person is suffering from Obesity”.
  • Else print “Invalid Input”.
  • The Exit of the Program.

Below is the implementation:

# Give the height as user input using the float(input()) function and store it in a variable.
gvn_height = float(input("Enter height(m) = "))
# Give the weight as user input using the float(input()) function and store it in another variable.
gvn_weight = float(input("Enter Weight(Kg) = "))
# Calculate the Body Mass Index(BMI) value using the above given mathematical
# formula and store it in another variable.
rslt_BMI = gvn_weight/(gvn_height*gvn_height)
print("The BMI value for the given height{",
      gvn_height, "}", "and weight{", gvn_weight, "}=", rslt_BMI)
# Check if the above obtained BMI value is greater than 0 using the if conditional
# statement.
if(rslt_BMI > 0):
    # If it is true, then check again if the above obtained BMI value is less than
    # or equal to 16. 
    if(rslt_BMI <= 16):
        # If it is true, then print "Person is severely underweight.Please Takecare".
        print("Person is severely underweight. Please Takecare")
    # Check if the above obtained BMI value is less than or equal to 18.5 using
    # the elif conditional statement. 
    elif(rslt_BMI <= 18.5):
        # If it is true, then print "Person is Underweight".
        print("Person is Underweight")
    # Check if the obtained BMI value is less than or equal to 25 using the elif
        # conditional statement.
    elif(rslt_BMI <= 25):
        # If it is true, then print "Person is Healthy".
        print("Person is Healthy")
    # Check if the obtained BMI value is less than or equal to 30 using the elif
        # conditional statement. 
    elif(rslt_BMI <= 30):
        # If it is true, then print "Person is Overweight".
        print("Person is Overweight")
    else:
        # Else print "Person is suffering from Obesity".
        print("Person is suffering from Obesity")
# Else print "Invalid Input".
else:
    print("Invalid Input")

Output:

Enter height(m) = 1.5
Enter Weight(Kg) = 59
The BMI value for the given height{ 1.5 } and weight{ 59.0 }= 26.22222222222222
Person is Overweight

Python BMI Calculator – A Complete Step-by-Step Tutorial Read More »

The Differences Between Supervised and Unsupervised Learning

The two machine learning strategies are supervised and unsupervised learning. However, each technique is utilized in a different circumstance and with a distinct dataset. Below is a description of two learning methods, as well as a comparison table.

Supervised Learning:

Supervised learning is a machine learning method that trains models using labelled data. In supervised learning, models must determine the mapping function that will connect the input variable (X) to the output variable (Y).

Y = f(X)

Supervised learning requires supervision to train the model, similar to how a student learns in the presence of a teacher. Supervised learning can be applied to two sorts of problems: classification and regression.

For Example:

Assume we have an image of various sorts of fruits. Our supervised learning model’s objective is to identify the fruits and classify them appropriately. So, in supervised learning, we will provide input data as well as output data, which means we will train the model based on the form, size, colour, and flavour of each fruit. When the training is finished, we will put the model to the test by feeding it a new batch of fruits. Using a suitable algorithm, the model will recognise the fruit and forecast the outcome.

Unsupervised learning

Unsupervised learning occurs when only the input data (say, X) is present and no corresponding output variable is present.

Why is Unsupervised Learning Beneficial?
Unsupervised learning’s major goal is to model the distribution in the data in order to learn more about the data.

It is so named because there is no correct response and no such teacher (unlike supervised learning). Algorithms are left to their own devices to identify and convey fascinating data structures.

Unsupervised learning can be applied to two sorts of problems: clustering and association.

Let us see an Example

The preceding example will be used to explain unsupervised learning. So, unlike supervised learning, we will not give any supervision to the model in this case. We will simply feed the model the input dataset and let the model detect patterns in the data. The model will train itself using an appropriate algorithm and separate the fruits into distinct groups based on the most common attributes between them.

The following are the primary differences between supervised and unsupervised learning:

                      Supervised Learning                           Unsupervised Learning
1) Labeled data is used to train supervised learning algorithms.1) UnLabeled data is used to train Unsupervised learning algorithms.
2) The supervised learning model uses direct feedback to determine whether or not it is forecasting the correct output.2) The unsupervised learning model does not accept feedback.

 

3) Classification and regression challenges are two types of supervised learning tasks.

 

3) Clustering and Associations challenges are two types of unsupervised learning tasks.

 

4) The outcome is predicted by a supervised learning model.

 

4) The unsupervised learning approach discovers hidden patterns in data.

 

5) In supervised learning, the model receives input data as well as output data.5) Only input data is presented to the model in this model.

 

6) The purpose of supervised learning is to train the model such that it can identify the result when fresh data is introduced.

 

6) Unsupervised learning seeks to discover hidden patterns and helpful insights in an unknown dataset.

 

7) To train the model, supervised learning necessitates supervision.7) To train the model, unsupervised learning does not require any supervision.
8) The supervised learning model yields high accuracy.

 

8) Unsupervised learning models may produce less accurate results than supervised learning models.
9) Supervised learning can not come near to actual artificial intelligence because it requires us to train the model for each input set before it can predict the correct output.

 

9) Unsupervised learning is closer to actual Artificial Intelligence since it learns in the same way that a child learns daily routine things via his experiences.

 

10) It comprises algorithms like Linear Regression, Logistic Regression, Support Vector Machine, Multi-class Classification, Decision Tree, Bayesian Logic, and others.10) It contains algorithms like Clustering, KNN, and the Apriori algorithm.

The Differences Between Supervised and Unsupervised Learning Read More »

15 Unquestionable Advantages of Learning Python

Programming languages have been around for a long time, and each decade sees the introduction of a new language that completely captivates engineers. Python is a popular and in-demand programming language. According to a recent Stack Overflow survey, Python has surpassed languages such as Java, C, and C++ to claim the top spot. As a result, Python certification is one of the most in-demand programming credentials. I’ll go over the top ten reasons to learn Python in this blog.

The following are the top 15 explanations for this trend.

1)Python Is Among the Easiest Coding Languages

If a learner wants to learn how to code, Python is a good place to start. Experts identify three advantages of projects that necessitate this coding:

It is simple to read, write and remember.

To put it another way, this programming language is not overly complex. The reason for this is its resemblance to English syntax. Its creators designed it simple to use. Unlike some other codes, it contains spaces and is written line by line. As a result, everyone can understand what it says.

Python is used at many educational institutions as part of their STEM curricula. According to the volunteers’ experience, teaching children to use this computer language is simple. As a result, young students who do not attend colleges or universities become Python professionals. They develop into promising pupils capable of learning different codes and becoming effective IT specialists or programmers.

2) The Popularity of Python and its High paid Salaries

Python developers earn some of the best pay in the industry. In the United States, the typical Python Developer pay is around $116,028 per year.

Python has also seen a significant increase in popularity in recent years.

3) Python in Data Science

Python is the language of choice for many data scientists. For years, university scholars and private researchers used the MATLAB language for scientific study, but that began to change with the emergence of Python numerical engines such as ‘Numpy’ and ‘Pandas.’

Python also works with tabular, matrix, and statistical data, and it visualizes it using popular libraries such as ‘Matplotlib’ and ‘Seaborn.’

4) Machine Learning and Artificial Intelligence

Machine Learning has grown in popularity in recent years. Algorithms are growing increasingly complex. The Python programming language simplifies machine learning. Python contains more material than Java’s machine learning libraries, and it is a popular programming language.

AI is the next big thing in the world of technology. It is possible to create a machine that can think, evaluate, and make decisions in the same way that humans do.
Furthermore, libraries like Keras and TensorFlow add machine learning capabilities to the mix.

These libraries are provided by python. It enables learning without being explicitly programmed. We also have libraries like OpenCV that aid with computer vision or image recognition.

5) Open-Source and Free

Python is distributed under the OSI-approved open-source license. As a result, it is free to use and distribute. You can download the source code, modify it, and even distribute your own Python version. This is beneficial for organizations that want to change a specific behavior and use their version for development.

6) Libraries and Frameworks

Python provides a number of frameworks for building websites. Popular frameworks include Django, Flask, Pylons, and others. Because these frameworks are developed in Python, this is the primary reason why the code is much faster and more stable.

You can also do web scraping to obtain information from other websites. You’ll also be impressed because several websites, including Instagram, Bitbucket, and Pinterest, are built entirely on these frameworks.

7) The ideal tool for transforming data into useful information.

Data is obtained when a person collects dates and descriptions of events. Information can be obtained by systematizing the received data. Python goes hand in hand with a cutting-edge discipline like Data Science. Python is used by professionals to transform data into information that may be used to solve critical problems.

For example, specialists were able to minimize fuel costs, reduce air pollution, and shorten the idle time of Southwest Airlines planes. There were three issues, but an expert was able to handle them all with one application while saving money. Employees that know all the secrets of Python coding are in high demand. That is the truth.

8)Python has Portability

Many programming languages, such as C/C++, require you to change your code in order to run the program on different platforms. Python, on the other hand, is not the same. You only need to write it once and then run it anywhere.

You should, however, take care not to include any system-dependent features.

9)Python use in Computer Graphics

Python is widely utilized in projects of all sizes, whether little or large, online or offline. It is used to create graphical user interfaces (GUIs) and desktop applications. It makes use of the ‘Tkinter’ library to give a quick and straightforward approach to constructing apps.

It is also used in game development, where you may build the logic of a game using the ‘pygame’ module, which runs on Android devices.

10) Prospects for Career and Growth

Developers all around the world are realizing the benefits of including Python on their resumes. Learning Python can help you advance in your job. It has the potential to lead to rich global employment opportunities. Recruiters and hiring managers regard Python certification as a quantitative item.

11) Python is used in smart technology.

Artificial intelligence is used in smartphones, smart homes, smart cars, and other forms of technology. Artificial intelligence, in turn, necessitates Python coding in order to function properly. Because the language is rich in frameworks and libraries, it simplifies device construction and configuration.

12) Python in Testing.

Python is excellent for verifying ideas or products for well-established businesses. Python includes a plethora of built-in testing frameworks that cover debugging and the quickest workflows. Selenium and Splinter are two tools and modules that can help make things easier.
It supports cross-platform and cross-browser testing using frameworks such as PyTest and Robot Framework. Testing is a time-consuming activity, and Python makes it easier, thus every tester should make use of it.

13) Error Correction Is Now Easier by Python

To complete the needed duties, software must have no errors. When a person writes in Python, he or she does so line by line. It ensures dynamic typic. If an error happens, the system will notify the creator. Because of this, some people are unable to continue writing. As a result, it forces one to fix everything at once. Furthermore, even if a student or programmer makes multiple errors, the system only reports on one. As a result, one can debug the code faster and focus on a single issue at a time, avoiding a total mess.

14)Python is utilized in Big Data applications.

Python addresses a wide range of data-related issues. It allows parallel processing and can be used in combination with Hadoop. Python has a module called “Pydoop,” and you may use it to construct a MapReduce application that processes data from the HDFS cluster.

Other libraries for big data processing include ‘Dask’ and ‘Pyspark.’ As a result, Python is commonly utilized for Big Data processing because it is simple to use.

15)Python in Automation or Robotics

Using Python automation frameworks such as PYunit provides numerous benefits:
There are no additional modules to install. They come in a box.
Even if you have no prior experience with Python, you will find working with Unittest to be very easy. It is derived, and its operation is similar to that of other xUnit frameworks.

You can conduct isolated experiments in a more straightforward manner. You should simply type the names into the terminal. The output is also compact, making the structure adaptable when it comes to running test cases. The test reports are produced in milliseconds.

15 Unquestionable Advantages of Learning Python Read More »

Python Itertools.repeat() Function with Examples

Itertools Module:

Itertools is a Python module that contains a collection of functions for dealing with iterators. They make it very simple to iterate through iterables such as lists and strings.

Itertools.repeat() Function:

Itertools.repeat() belongs to the class of infinite iterators. In repeat(), we provide the data as well as the number of times the data will be repeated. If we don’t specify a number, it will loop indefinitely. The memory space is not created for each variable in repeat(). Rather, it creates only one variable and then repeats it.

Syntax:

repeat(value, number)

Parameters

value: It is the value that will be printed.

number: If the optional keyword number is specified, it prints the passed value number times; otherwise, it prints the passed value infinite times.

Examples:

Example1:

Input:

Given value = 60
Given number = 5

Output:

The list of given value { 60 } 5 times =  [60, 60, 60, 60, 60]

Example2:

Input:

Given string = "hello"
Given number = 3

Output:

The list of given string { hello } 3 times =  ['hello', 'hello', 'hello']

Itertools.repeat() Function with Examples in Python

Method #1: Using Built-in Functions (Static Input)

Approach:

  • Import itertools module using the import keyword.
  • Give the value as static input and store it in a variable.
  • Give the number as static input and store it in another variable.
  • Pass the given value and number as the arguments to the itertools.repeat() function that gets the given value, given number of times and store it in a variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools
# Give the value as static input and store it in a variable.
gvn_valu = 60
# Give the number as static input and store it in another variable.
gvn_numb = 5
# Pass the given value and number as the arguments to the itertools.repeat()
# function that gets the given value, given number of times
# and store it in a variable.
rslt = itertools.repeat(gvn_valu, gvn_numb)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Print the above result.
print("The list of given value {", gvn_valu, "}",
      gvn_numb, "times = ", rslt_lst)

Output:

The list of given value { 60 } 5 times =  [60, 60, 60, 60, 60]
For Strings

Approach:

  • Import itertools module using the import keyword.
  • Give the string as static input and store it in a variable.
  • Give the number as static input and store it in another variable.
  • Pass the given string and number as the arguments to the itertools.repeat() function that gets the given string, given number of times and store it in a variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools
# Give the string as static input and store it in a variable.
gvn_str = "hello"
# Give the number as static input and store it in another variable.
gvn_numb = 3
# Pass the given string and number as the arguments to the itertools.repeat()
# function that gets the given string, given number of times
# and store it in a variable.
rslt = itertools.repeat(gvn_str, gvn_numb)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Print the above result.
print("The list of given string {", gvn_str, "}",
      gvn_numb, "times = ", rslt_lst)

Output:

The list of given string { hello } 3 times =  ['hello', 'hello', 'hello']

Method #2: Using Built-in Functions (User Input)

Approach:

  • Import itertools module using the import keyword.
  • Give the value as user input using the int(input()) function and store it in a variable.
  • Give the number as user input using the int(input()) function and store it in another variable.
  • Pass the given value and number as the arguments to the itertools.repeat() function that gets the given value, given number of times and store it in a variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools
# Give the value as user input using the int(input()) function and store it in a variable.
gvn_valu = int(input("Enter some random number = "))
# Give the number as user input using the int(input()) function and store it in another variable.
gvn_numb = int(input("Enter some random number = "))
# Pass the given value and number as the arguments to the itertools.repeat()
# function that gets the given value, given number of times
# and store it in a variable.
rslt = itertools.repeat(gvn_valu, gvn_numb)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Print the above result.
print("The list of given value {", gvn_valu, "}",
      gvn_numb, "times = ", rslt_lst)

Output:

Enter some random number = 75
Enter some random number = 7
The list of given value { 75 } 7 times = [75, 75, 75, 75, 75, 75, 75]
For Strings

Approach:

  • Import itertools module using the import keyword.
  • Give the string as user input using the input() function and store it in a variable.
  • Give the number as user input using the int(input()) function and store it in another variable.
  • Pass the given string and number as the arguments to the itertools.repeat() function that gets the given string, given number of times and store it in a variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools
# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Give the number as user input using the int(input()) function and store it in another variable.
gvn_numb = int(input("Enter some random number = "))
# Pass the given string and number as the arguments to the itertools.repeat()
# function that gets the given string, given number of times
# and store it in a variable.
rslt = itertools.repeat(gvn_str, gvn_numb)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Print the above result.
print("The list of given string {", gvn_str, "}",
      gvn_numb, "times = ", rslt_lst)

Output:

Enter some random string = btechgeeks
Enter some random number = 2
The list of given string { btechgeeks } 2 times = ['btechgeeks', 'btechgeeks']

Python Itertools.repeat() Function with Examples Read More »

A Complete Tutorial for Python’s += Operator

In this session, we’ll look at Python’s += operator. Let us see how it works with a few simple examples.

The addition assignment operator is denoted by the operator ‘+=’. It is like a short form to it. It adds two values and stores the result in a variable (left operand).

Addition of Two numbers Using += Operator:

Example1:

gvn_num = 100
print("The given number = ", gvn_num)
gvn_num += 50
print("The given number after addition with 50 = ", gvn_num)

Output:

The given number =  100
The given number after addition with 50 =  150

Example2:

a = 10
b = 20
c = 30
rslt_sum = 0
# Adding a,b,c and storing it in a variable rslt_sum
# The below indicates rslt_sum = rslt_sum+(a+b+c)
rslt_sum += a+b+c
print("The sum of a,b,c = ", rslt_sum)

Output:

The sum of a,b,c =  60

For Strings

The ‘+=’ operator concatenates the given strings. It is used for the concatenation of two or more strings.

Example1:

gvn_fststr = "hello"
gvn_scndstr = "btechgeeks"
print("The given first string = ", gvn_fststr)
print("The given second string = ", gvn_scndstr)
print()
# It concatenates the given first string with the second string and assigns the
# result to the first string
gvn_fststr += gvn_scndstr

print("The given first string after concatenation = ", gvn_fststr)

Output:

The given first string =  hello
The given second string =  btechgeeks

The given first string after concatenation =  hellobtechgeeks

Example2:

gvn_fststr = "hello"
gvn_scndstr = " this is "
gvn_thrdstr = "btechgeeks"
concat_str = ""
# concatenating the given three strings using  '+=' Operator
concat_str += (gvn_fststr+gvn_scndstr+gvn_thrdstr)
print("The concatenation of given three strings = ", concat_str)

Output:

The concatenation of given three strings =  hello this is btechgeeks

The “+=” operator’s Associativity in Python

The ‘+=’ operator’s associativity property is from right to left.

Example1:

a = 3
b = 6
a += b >> 2
print("a =", a)
print("b =", b)

Output:

a = 4
b = 6

Explanation:

We set the starting values of two variables, a and b, to 3 and 6, respectively. In the code, we right shift the value of b by two bits, add the result to variable ‘a’, and put the final result in variable ‘a’.

Therefore the final output is :

a=4 and b=6

Example2:

a = 3
b = 6
# Left shift by 1 bit
a += b << 1
print("a =", a)
print("b =", b)

Output:

a = 15
b = 6

Conclusion

This is about the Python ‘+=’ operator and its numerous implementations.

 

A Complete Tutorial for Python’s += Operator Read More »

Python String format() Method with Examples

String format() Method in Python:

The format() method formats the specified value(s) and inserts them inside the placeholder of the string.

Curly brackets{} are used to define the placeholder. In the Placeholder section, you can learn more about the placeholders.

format() returns the formatted string.

Syntax:

string.format(value1, value2, .......)

Parameters

value1, value2, ……. :

Required. One or more values to be formatted and inserted into the string

The values are either a comma-separated list of values, a key=value list, or a combination of the two.

Any data type can be used for the values.

For Example:

Approach:

  • Apply the placeholder for the cost variable and store it in a variable.
  • Apply the format() function for the above string by passing the cost as some random number and print it.
  • The Exit of the Program.

Below is the implementation:

# Apply the placeholder for the cost variable(static string)and store it in a variable.
gvn_str = "The dress cost is {cost:.2f} Rs."
# Apply the format() function for the above string by passing the cost as some
# random number and print it.
print(gvn_str.format(cost=850))

Output:

The dress cost is 850.00 Rs.

Placeholders

The placeholders can be identified using named indexes such as {cost} numbered indexes such as 0 {0}, or even empty placeholders {}.

For Example:

Approach:

  • Apply the placeholder for the ename and id (static string) and apply the format() function for the given string by passing the ename and id with some random values and print it.
  • This is in named indexes format.
  • Similarly, do the same by numbered indexes format and empty placeholders format.
  • Print the results separately.
  • The Exit of the Program.

Below is the implementation:

# Apply the placeholder for the ename and id (static string) and apply the format()
# function for the given string by passing the ename and id with some random values
# and print it.
# (This is in named indexes format)
gvn_str1 = "The Employee name is {ename}, and his id is {id}".format(
    ename="virat", id=28)
# Similarly, do the same by numbered indexes format and empty placeholders format.
# Print the results separately.
gvn_str2 = "The Employee name is {0}, and his id is {1}".format("virat", 28)
# empty placeholders format
gvn_str3 = "The Employee name is {}, and his id is {}".format("virat", 28)
print(gvn_str1)
print(gvn_str2)
print(gvn_str3)

Output:

The Employee name is virat, and his id is 28
The Employee name is virat, and his id is 28
The Employee name is virat, and his id is 28

Types of Formatting

:<        – The result is aligned left (within the available space)

:>        – The result is aligned right (within the available space)

:^        – The result is centered (within the available space)

:=        – Positions the sign to the far left.

:+        – To indicate whether the outcome is positive or negative, use a plus sign.

:-        – Only use a minus sign for negative values.

:         – Insert an extra space before positive numbers by using a space (and a minus sign before negative numbers)

:,         – As a thousand separator, use a comma.

:_       – As a thousand separator, use an underscore.

:b       –  binary format

:c        – The value is converted into the corresponding Unicode character.

:d         – decimal format

:e         – Scientific notation in lower case e

:E        – Scientific notation in upper case E

:f         – Fix point number format

:F        – Fix point number format, all uppercase (show inf and nan as INF and NAN)

:g         – General format

:G        – Format in General (using an upper case E for scientific notations)

😮        – octal format

😡         -Hexadecimal, lower case

:X          -Hexadecimal, upper case

:n          – format for numbers

:%         – Format in percentages

 

Python String format() Method with Examples Read More »

Python String format_map() Method with Examples

String format_map() Method in Python:

The format_map() method is similar to str. format(**mapping), with the difference that str. format(**mapping) creates a new dictionary, whereas str. format map(mapping) does not.

The format map(mapping) method is similar to str.format(**mapping).

The only distinction is that str.format(**mapping) copies the dict, whereas str.format map(mapping) creates a new dictionary during the method call. If you’re working with a dict subclass, this can come in handy.

Syntax:

string. format_map(mapping)

Parameters

format map() only accepts one argument, mapping (dictionary).

Return Value:

format map() formats and returns the given string.

Examples:

Example1:

Input:

Given dictionary = {'a': 7, 'b': -3}
string format = '{a} {b}'

Output:

7 -3

Example2:

Input:

Given dictionary = {'a': 7, 'b': -3, 'c': 10}
string format = '{a} {b} {c}'

Output:

7 -3 10

String format_map() Method with Examples in Python

Method #1: Using Built-in Functions (Static Input)

Approach:

  • Give the dictionary as static input and store it in a variable.
  • Pass the given dictionary to the format_map() method to get in the specified format and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Give the dictionary as static input and store it in a variable.
gvn_dict = {'a': 7, 'b': -3}
# Pass the given dictionary to the format_map() method to get in the specified
# format and store it in another variable.
rslt = '{a} {b}'.format_map(gvn_dict)
# Print the above result.
print(rslt)

Output:

7 -3

Similarly, try for the other example

gvn_dict = {'a': 7, 'b': -3, 'c': 10}
rslt = '{a} {b} {c}'.format_map(gvn_dict)
print(rslt)

Output:

7 -3 10

format_map with dict subclass

Approach:

  • Create a class that accepts the dictionary as an argument or constructor.
  • Create a function by passing the key as a parameter to it.
  • Return the key value from the function.
  • In the main function, pass the class with the argument as ‘a’ coordinate to the format_map() method and print it.
  • Similarly, do the same by passing the ‘b’ coordinate.
  • Do the same for the a and b coordinates and print them.
  • The Exit of the Program.

Below is the implementation:

# Create a class that accepts the dictionary as an argument or constructor.
class Coordinatepoints(dict):
   # Create a function by passing the key as a parameter to it.
    def __missing__(self, key):
        # Return the key value from the function.
        return key


# In the main function, pass the class with the argument as 'a' coordinate to the
# format_map() method and print it.
print('({a}, {b})'.format_map(Coordinatepoints(a='3')))
# Similarly, do the same by passing the 'b' coordinate.
print('({a}, {b})'.format_map(Coordinatepoints(b='7')))
# Do the same for the a and b coordinates and print them.
print('({a}, {b})'.format_map(Coordinatepoints(a='3', b='7')))

Output:

(3, b)
(a, 7)
(3, 7)

Python String format_map() Method with Examples Read More »

Python String isascii() Method with Examples

String isascii() Method in Python:

If all of the characters are ASCII, the isascii() method returns True (a-z). Otherwise returns False.

Syntax: 

string.isascii()

Parameters: This method has no parameters.

Examples:

Example1:

Input:

Given string = "hello@%btechgeeks670"

Output:

True

Example2:

Input:

Given string = 'ß'

Output:

False

String isascii() Method with Examples in Python

Method #1: Using Built-in Functions (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Apply isascii() method on the given string where if all of the characters are ASCII, the isascii() method returns True (a-z). Otherwise returns False.
  • Store it in a variable.
  • Print the result after applying isascii() method on the given string.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = "btechgeeks789@"
# Apply isascii() method on the given string where if all of the characters are
# ASCII, the isascii() method returns True (a-z). Otherwise returns False.
# Store it in a variable.
rslt = gvn_str.isascii()
# Print the result after applying isascii() method on the given string.
print(rslt)

Output:

True

For any non-ASCII characters, the isascii() method returns False.

For Example:

# A letter in German
gvn_str = 'ß'
print(gvn_str.isascii())

gvn_str = 'õ'
print(gvn_str.isascii())

gvn_str = 'Ã…'
print(gvn_str.isascii())

Output:

False
False
False

The isascii() method also verifies ASCII Unicode characters.

For Example:

gvn_str = '/u0000' # Null Unicode
print(gvn_str.isascii())

gvn_str = '/u007f' # DEL Unicode
print(gvn_str.isascii())

gvn_str = '/u0041' # A's Unicode
print(gvn_str.isascii())

gvn_str = '/u0061'  # a's Unicode
print(gvn_str.isascii())

Output:

True
True
True
True

Method #2: Using Built-in Functions (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Apply isascii() method on the given string where if all of the characters are ASCII, the isascii() method returns True (a-z). Otherwise returns False.
  • Store it in a variable.
  • Print the result after applying isascii() method on the given string.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Apply isascii() method on the given string where if all of the characters are
# ASCII, the isascii() method returns True (a-z). Otherwise returns False.
# Store it in a variable.
rslt = gvn_str.isascii()
# Print the result after applying isascii() method on the given string.
print(rslt)

Output:

Enter some random string = hello@%btechgeeks670
True

Python String isascii() Method with Examples Read More »

Python Random shuffle() Method with Examples

Random shuffle() Method in Python:

The shuffle() method reorganizes the order of items in a sequence, such as a list.

Note: Please keep in mind that this method modifies the original list and does not return a new list.

Syntax:

random.shuffle(sequence, function)

Parameters

sequence: This is Required. It could be any sequence.

function: This is Optional. The name of a function that produces a value between 0.0 and 1.0.
If no function is specified, the random() function will be used.

Return Value: This method produces no output.

Examples:

Example1:

Input:

Given List = ["good", "morning", "Btechgeeks"]

Output:

Given list After shuffling : ['Btechgeeks', 'morning', 'good']

Example2:

Input:

Given List = [10, 20, 30, 40]

Output:

Given list After shuffling : [20, 40, 30, 10]

Random shuffle() Method with Examples in Python

Method #1: Using Built-in Functions (Static Input)

Approach:

  • Import random module using the import keyword.
  • Give the list as static input and store it in a variable.
  • Pass the given list to the random.shuffle() method that reorganizes the order of items in a given list.
  • Print the above-given list after shuffling.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the list as static input and store it in a variable.
gvn_lst = ["good", "morning", "Btechgeeks"]
# Pass the given list to the random.shuffle() method that reorganizes the order of
# items in a given list.
random.shuffle(gvn_lst)
# Print the above-given list after shuffling randomly.
print("Given list After shuffling :", gvn_lst)

Output:

Given list After shuffling : ['Btechgeeks', 'morning', 'good']
Using Function

To weigh or specify the result, you can define your own function.

If the function returns the same number every time, the result will be the same every time

Approach:

  • Import random module using the import keyword.
  • Create a function say demo_function.
  • Inside the function, return 0.1
  • Give the list as static input and store it in a variable.
  • Pass the given list, above function as arguments to the random.shuffle() method in which if the function returns the same number every time, the result will be the same every time.
  • Print the above-given list after shuffling.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random

# Create a function say demo_function.


def demo_function():
    # Inside the function, return 0.1
    return 0.1


# Give the list as static input and store it in a variable.
gvn_lst = ["hello", "this", "is", "btechgeeks"]
# Pass the given list, above function as arguments to the random.shuffle() method
# in which if the function returns the same number every time, the result will be
# the same every time.

random.shuffle(gvn_lst, demo_function)
# Print the above-given list after shuffling.
print(gvn_lst)

Output:

['this', 'is', 'btechgeeks', 'hello']

Method #2: Using Built-in Functions (User Input)

Approach:

  • Import random module using the import keyword.
  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Pass the given list to the random.shuffle() method that reorganizes the order of items in a given list.
  • Print the above-given list after shuffling.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))

# Pass the given list to the random.shuffle() method that reorganizes the order of
# items in a given list.
random.shuffle(gvn_lst)
# Print the above-given list after shuffling randomly.
print("Given list After shuffling :", gvn_lst)

Output:

Enter some random List Elements separated by spaces = 10 20 30 40
Given list After shuffling : [20, 40, 30, 10]

 

 

Python Random shuffle() Method with Examples Read More »

Python Random randrange() Method with Examples

Random randrange() Method in Python:

The randrange() method selects an element at random from the specified range and returns it.

Syntax:

random.randrange(start, stop, step)

Parameters

start: This is Optional. It is an integer indicating the starting position.
0 is the default.

stop: This is Required. It is an integer indicating the position at which to end.

step: Optional. The incrementation is specified by an integer.
1 is the default.

Examples:

Example1:

Input:

Given start value = 1
Given stop value = 5

Output:

The random number between 1 and 5 = 3

Example2:

Input:

Given start value = 1
Given stop value = 10
Given step size = 2

Output:

The random number between 1 and 10 = 7

Explanation:

Here it prints a random odd number between 1 and 10(includes only start value) 
since the start value is 1 and stepsize is 2

Random randrange() Method with Examples in Python

Method #1: Using Built-in Functions (Static Input)

Approach:

  • Import random module using the import keyword.
  • Give the number(start value) as static input and store it in a variable.
  • Give the other number(stop value) as static input and store it in another variable.
  • Pass the given start and stop values as the arguments to the random.randrange() method to get a random number between the given start and stop values (includes only start value).
  • Store it in another variable.
  • Print a random number between the given start and stop values.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number(start value) as static input and store it in a variable.
gvn_strtval = 1
# Give the other number(stop value) as static input and store it in another variable.
gvn_stopval = 5
# Pass the given start and stop values as the arguments to the random.randrange()
# method to get a random number between the given start and stop values.
# (includes only start value)
# Store it in another variable.
rslt = random.randrange(gvn_strtval, gvn_stopval)
# Print a random number between the given start and stop values.
print("The random number between", gvn_strtval, "and", gvn_stopval, "=", rslt)

Output:

The random number between 1 and 5 = 3
with giving step value

Approach:

  • Import random module using the import keyword.
  • Give the number(start value) as static input and store it in a variable.
  • Give the other number(stop value) as static input and store it in another variable.
  • Give the step size as static input and store it in another variable.
  • Pass the given start, stop and step values as the arguments to the random.randrange() method to get a random number between the given start and stop values(includes only start value) with a given step size.
  • Store it in another variable.
  • Print a random number between the given start and stop values.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number(start value) as static input and store it in a variable.
gvn_strtval = 1
# Give the other number(stop value) as static input and store it in another variable.
gvn_stopval = 10
# Give the step size as static input and store it in another variable.
gvn_step = 2
# Pass the given start,stop and step values as the arguments to the
# random.randrange() method to get a random number between the given start and
# stop values(includes only start value) with a given stepsize.
# Store it in another variable.
rslt = random.randrange(gvn_strtval, gvn_stopval, gvn_step)
# Print a random number between the given start and stop values.
print("The random number between", gvn_strtval, "and", gvn_stopval, "=", rslt)

Output:

The random number between 1 and 10 = 7

Method #2: Using Built-in Functions (User Input)

Approach:

  • Import random module using the import keyword.
  • Give the number(start value) as user input using the int(input()) function and store it in a variable.
  • Give the other number(stop value)  as user input using the int(input()) function and store it in another variable.
  • Pass the given start and stop values as the arguments to the random.randrange() method to get a random number between the given start and stop values (includes only start value).
  • Store it in another variable.
  • Print a random number between the given start and stop values.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number(start value) as user input using the int(input()) function and store it in a variable.
gvn_strtval = int(input("Enter some random number = "))
# Give the other number(stop value)  as user input using the int(input()) function 
# and store it in another variable.
gvn_stopval = int(input("Enter some random number = "))
# Pass the given start and stop values as the arguments to the random.randrange()
# method to get a random number between the given start and stop values.
# (includes only start value)
# Store it in another variable.
rslt = random.randrange(gvn_strtval, gvn_stopval)
# Print a random number between the given start and stop values.
print("The random number between", gvn_strtval, "and", gvn_stopval, "=", rslt)

Output:

Enter some random number = 10
Enter some random number = 17
The random number between 10 and 17 = 10
with giving step value

Approach:

  • Import random module using the import keyword.
  • Give the number(start value) as user input using the int(input()) function and store it in a variable.
  • Give the other number(stop value)  as user input using the int(input()) function and store it in another variable.
  • Give the step size as static input and store it in another variable.
  • Pass the given start, stop and step values as the arguments to the random.randrange() method to get a random number between the given start and stop values(includes only start value) with a given step size.
  • Store it in another variable.
  • Print a random number between the given start and stop values.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number(start value) as user input using the int(input()) function and store it in a variable.
gvn_strtval = int(input("Enter some random number = "))
# Give the other number(stop value) as user input using the int(input()) function 
# and store it in another variable.
gvn_stopval = int(input("Enter some random number = "))
# Give the step size as user input using the int(input()) function and store it in another variable.
gvn_step = int(input("Enter some random number = "))
# Pass the given start,stop and step values as the arguments to the
# random.randrange() method to get a random number between the given start and
# stop values(includes only start value) with a given stepsize.
# Store it in another variable.
rslt = random.randrange(gvn_strtval, gvn_stopval, gvn_step)
# Print a random number between the given start and stop values.
print("The random number between", gvn_strtval, "and", gvn_stopval, "=", rslt)

Output:

Enter some random number = 50
Enter some random number = 60
Enter some random number = 3
The random number between 50 and 60 = 53

Python Random randrange() Method with Examples Read More »