Blogs  

How to Convert Decimal to Binary in Python

Introduction:

  1. The Python is considered as a highly versatile and sophisticated programming language which is having enriched library set with itself.

  2. It is capable to interpret any complex programming and ability to solve it. 

  3. Among the many variety of problems if we are trying to convert from decimal to binary and vice versa then python has provided that feature also.

  4. When we are trying to convert the decimal to Binary value then we can make the use of bin () function.

  5. Similarly, the vice versa is also can be done using the inbuilt function int().

Here, I am going to discuss about How to convert the decimal value to binary value and vice versa in Python. Here we are also going to discuss that how they are used to support the inbuilt functions which is being provided by the Python library.

Basic Procedure for Converting the Decimal value to Binary value:

In normal ways when we are going to convert the decimal to binary value then we used to follow the following steps as mentioned below.

  1. Keep calling conversion function with n/2 till n > 1,

  2. later perform n % 1 to get MSB of converted binary number.  

Let us consider that we are going to convert the decimal value of 7 to binary value. To do so, as I have already mentioned the steps above, we need to proceed as

  1. 7/2 = Quotient = 3(grater than 1), Remainder = 1. So, repeat the step 1 again.

  2. 3/2 = Quotient = 1(not grater than 1), Remainder = 1. So, repeat the step 1 again.

1%2 = Rem = 1. Here we need to stop, and we need to reverse count the value as (111) 2.

Implementation of program in Python:

In Python we can do the conversion form decimal to binary in three ways. I am going to discuss all the three approaches as below.

Approach-1: We can use the recursive technique here. To do so we need to proceed as follows.

DecimalToBinary(num):

        if num >= 1:

            DecimalToBinary(num // 2)

            print num % 2

To implement the code in Python we can proceed as follows.

# Function to convert decimal number to binary using recursion technique.

def DecimalToBinary(num):

 if num >= 1:

        DecimalToBinary(num // 2)

    print(num % 2, end = '')

 

# Driver Code

if __name__ == '__main__':

     

    # decimal value

    dec_val = 24

     

    # Calling function

    DecimalToBinary(dec_val)

Approach-2: Decimal to binary using in-built function.

Here we can make the use of bin() function. The implementation can be done as follows.

# use of binary function to convert Decimal number to Binary number 

def decimalToBinary(n): 

    return bin(n).replace("0b", "") 

   # Driver code 

if __name__ == '__main__': 

    print(decimalToBinary(8)) 

     output: 1000.

Approach-3: Without the use of inbuilt function also we can do the conversion. If we need to do so, then we need to proceed as follows.

def decimalToBinary(n): 

    return "{0:b}".format(int(n))

   

# Driver code 

if __name__ == '__main__': 

    print(decimalToBinary(8)) 

 

Output: 1000

Binary to Decimal in Python:

In normal ways when we are going to convert the binary to decimal value then we used to follow the following steps as mentioned below. Let us discuss here by considering an example. Let us consider that we are going to find the decimal equivalent of a binary value (1011)2. I am going to discuss the steps as below.

  1. First we need to take the modulo of given binary number (1011)2 with 10. 

(1011 % 10 = 1) it is the modulo division.

  1. After getting this now we need to multiply the reminder value with 2 and raised to the power.

It’s position from right end. 

  1. * 2^0) It should be get noted that we are starting the counting position with 0. 

  1. Add the obtained result value with the previously generated result.

 decimal = decimal + (1 * 2^0)

  1.  Update binary number by dividing it by 10.

  1. 0 = 101)

  1. Keep repeating the above steps until the given binary number value is > 0.

Final Conversion -: (1 * 2^3) + (0 * 2^2) + (1 * 2^1) + (1 * 2^0) = 11

So, from the final conversion we came to know that the decimal equivalent of (1011)2 is 11.

Implementation of program in Python:

In Python we can do the conversion form binary to decimal in following two manners. Here I am going to discuss both the approaches as below.

Program:

Approach-1: Without using the inbuilt function. Here we can use the loop concept to make the conversion.

Program:

def binaryToDecimal(binary): 

      binary1 = binary 

    decimal, i, n = 0, 0, 0

    while(binary != 0): 

        dec = binary % 10

        decimal = decimal + dec * pow(2, i) 

        binary = binary//10

        i += 1

    print(decimal)     

      # Driver code 

if __name__ == '__main__': 

    binaryToDecimal(100) 

Output: 4.

Approach-2: Using the inbuilt function int(). 

We can also able to do the program using the inbuilt function int(). To do so, we need to proceed as follows.

Program:

def binaryToDecimal(n): 

    return int(n,2) 

  

# Driver code 

if __name__ == '__main__': 

    print(binaryToDecimal('100')) 

 

Output: 4.

Scope @ NareshIT:

  1. At Naresh IT you will get a good Experienced faculty who will guide you, mentor you and nurture you to achieve your dream goal.

  2. Here you will get a good hand on practice in terms of practical industry-oriented environment which will definitely help you a lot to shape your future.

  3. During the designing process of application, we will let you know about the other aspect of the application too. 

  4. Our Expert trainer will let you know about every in’s and out’s about the problem scenario.

Achieving your dream goal is our motto. Our excellent team is working restlessly for our students to click their target. So, believe on us and our advice, and we assured you about your sure success.

 

What is Random Number Generator in Python and how to use it

Introduction:

  1. We can be able to generate the Random integer values by using the randint() function. 

  2. When we are going to use the function randint() then it is used to takes two arguments such as start and end.

  3. Here the start and the end are used to denote the range for the integer to be generated values. 

  4. When we are concern about the Random integers, then they are used to be get generated within the boundary values. Here the boundary values are the start and end of range values.

  5. More specifically they are the interval [start, end].

Here, I am going to discuss about How to generate the Random Integer in Python. Here we are also going to discuss that how they are used to support the inbuilt functions which is being provided by the Python library.

What is Random Number Generator in Python:

  1. A Random Number Generator in Python is a function which is used to generate the random number whenever it is get called.

  2. It is a built-in function in Python.

  3. It is a function which is present in the Python Random module. 

  4. So, whenever we need to generate the random number we need to call this module and invoke the Generate method.

  5. Along with this method this module also consists of other random number generator functions methods such as seed(), randrange(), randint(), choice(), shuffle(), sample() and uniform().

  6. These methods are also called as supporting methods for Random number generation.

  7. The seed() method is basically used to produce the values which are deterministic in nature.

  8. A deterministic value are used to have the same sequence of values.

  9. The randrange() method is basically used when we need to return random values between the specified limit and interval.

  10. The randint() is basically used when we are going to returns a random integer as per the given limit.

  11. The choice() method is basically get used when we need to return a random number form a given sequence of numbers.

  12. The suffle() method is basically used when we need a suffle a value within a given sequence of numbers.

  13. The sample() method is basically get used when we need to return a randomly selected values.

The uniform() method is basically get used when we need to returns the floating-point values form a given range of values.

Generating integers:

 

  1. As we have already discussed that if we are going to generate the Random integers values then it can be get generated using functions such as randrange() and randint() methods. 

  2. The randrange() method is basically used when we need to return random values between the specified limit and interval.

  3. Similarly, The randint() is basically used when we are going to returns a random integer as per the given limit.

Let us consider the example as discussed below which will let you know how to use these methods.

randrange():

  1. As we know that the randrange() function is basically used when we need to return random values between the specified limit and interval. 

  2. It is basically used to allow the user to generate values by stepping over the interval count.

Syntax:

randrange()

Let us consider the following example which shows the use of randrange().

import random

for x in range(5):

    print(random.randrange(2,60,2))

randint():

  1. When we are going to use the randint() method then it is basically used to generates integers between a given limit. 

  2. Here It will takes two parameters as an input which are used to specifies the limit values. 

  3. Here lower limit is get specified by first parameter whereas the second specifies the upper limit.

Syntax: 

randint(a,b) 

here a is the lower limit and b is the upper limit.

Example:

import random

random.randint(1,5)

 

Similarly, if we need to generate the series of sequence then we may take the approach of loop here. But it should be get noted that we need to put the function as a body of the loop.

 

For Example:

import random

for x in range(2):

    print(random.randint(2,11))

Generating floating-point numbers:

  1. Like similar to above if we are going to generate the floating point number then we can use the random() and uniform() method.

  2. When we are going to use the random() method then it produces floating-point values between 0.0 to 1.0.

  3. Like other method it never used to takes any parameters. 

  4. Here the upper limit is excluded. So, the maximum value it can range up to 9.999.

  5. When we are going to use the uniform() method then it is basically get used when we need to returns the floating-point values form a given range of values

 

Let us consider the following example which will let you know about the use of random() and uniform().

Example:

 

Use of random():

import random

for x in range(5):

    print(random.random())

Use of uniform():

for x in range(5):

    print(random.uniform(6))

Generating values from a given sequence:

  1. When we are going to generate the values form a sequence then we use the choice().

  2. The choice() method is basically get used when we need to return a random number form a given sequence of numbers.

Let us consider the following example:

for x in range(3):

    print(random.choice([1,2,3,4,5,6,7,8,9]))

Like similar to choice () some times we may also use the sample(). The use of sample() is almost similar as that of choice().

Let us consider the following example which will let you know how to use the sample().

x=random.sample([1,2,3,4,5,6,7,8,9],4)

print(x)

Other functions:

As we have already discussed above earlier that the other functions are also present which are used to generate the random number. Let us discuss one by one here.

shuffle():

  1. The suffle() method is basically used when we need a suffle a value within a given sequence of numbers

Example:

x=[1,2,3,4,5,6,7,8,9]

random.shuffle(x)

print(x)

seed():

  1. This method is also called as supporting methods for Random number generation.

  2. The seed() method is basically used to produce the values which are deterministic in nature.

  3. A deterministic value is used to have the same sequence of values.

Let us consider the following example as below:

random.seed(2)

print(random.random(),random.random(),random.random(),end='nn')

It should be get noted that This function is very useful when we need to pass the same random numbers to various test cases.

Scope @ NareshIT:

  1. At Naresh IT you will get a good Experienced faculty who will guide you, mentor you and nurture you to achieve your dream goal.

  2. Here you will get a good hand on practice in terms of practical industry-oriented environment which will definitely help you a lot to shape your future.

  3. During the designing process of application, we will let you know about the other aspect of the application too. 

  4. Our Expert trainer will let you know about every in’s and out’s about the problem scenario.

Achieving your dream goal is our motto. Our excellent team is working restlessly for our students to click their target. So, believe on us and our advice, and we assured you about your sure success. 

 

How to Install pip In Python Get Started With Python Installation

Introduction:

  1. The PIP is basically defined as it is a package manager for Python packages, or modules.

  2. When we are using the Python 3.4 Version or later then it is present by default.

  3. A Package is a collection of precompiled class which we usually need for writing a program or developing a project work.

  4. A package is also a collection of Library.

  5. In most of the cases if we need to check whether PIP is present in our Python Library or not we need to use the following command as

  6. C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip --version   

Here, I am going to discuss about the PIP in Python regarding its use and implementation. Here we are also going to discuss that how we can install the PIP if we are using the earlier version of Python.

What is PIP:

  1. As we have already discussed earlier that the PIP is a Package Manager for Python.

  2. In most of the cases if we need to check whether PIP is present in our Python Library or not we need to use the following command as

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip --version   

  1. When we are going to implement the concept in programming then we may need the PIP as a environment.

How to Install PIP In Python:

 

As we have already discussed that if we are going to have the Python 3.4 version onwards with us then it is by default present in the system. But if we are using the Python 2 then we need to install the PIP manually. To do so we need to proceed as follows.

  1. As stated earlier we first need to Check if PIP is Installed in our system or not. To do so we need to navigate our command line to the location of Python's script directory.

  2. For this we need to type the following command in the console as: C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip –version

  3. If you do not have PIP get installed in your system then you need to Install PIP by redirecting to the following link: https://pypi.org/project/pip/

  4. Downloading a PIP package is very easy just we need to Open the command line interface and download the package you want to install in your system.

     5.Navigate your command line to the location of Python's script directory,            and type the following:                    C:\Users\YourName\AppData\Local\Programs\Python\Python36-32\Scripts>pip install camelcase

     6.It is the first package that you have installed in your system and it is ready to use.

7. Now you need to Import the "camelcase" package into your project. The code for doing this is as mentioned below.

import camelcase

c = camelcase.CamelCase()

txt = "hello world"

print(c.hump(txt))

Similarly, if you need to install the PIP separately then you need to follow the following steps mentioned as below.

  1. Download the package form internet get-pip.py

  2. Open Command prompt and Run the following command such as C:\ Users\YourName\python get-pip.py

Similarly, if you need to upgrade the PIP version in your system, you need to type the following command as C:\ Users\YourName\python -m pip install –upgrade pip

Now after this you are ready with your updated PIP in your system and it is ready to use.

 

Installing A Library:

For the installation of library in PIP, If you’re using Windows, then open the Windows Command Prompt, and then typing this command:

pip install package name

For example, if we need to install the scikit-learn package, then we can type the command as 

pip install scikit-learn

It will install the package to your system. The screen shot you will receive by the system as

In the similar manner you can be able to install any package as per your wish. But it should be get noted that if you need to install a specific version of library package then you need to mention it. 

For example, if I need to install the version 0.19.2 of scikit-learn then I need to mention it as

pip install scikit-learn==0.19.2

Scope @ NareshIT:

  1. At Naresh IT you will get a good Experienced faculty who will guide you, mentor you and nurture you to achieve your dream goal.

  2. Here you will get a good hand on practice in terms of practical industry-oriented environment which will definitely help you a lot to shape your future.

  3. During the designing process of application, we will let you know about the other aspect of the application too. 

  4. Our Expert trainer will let you know about every in’s and out’s about the problem scenario.

Achieving your dream goal is our motto. Our excellent team is working restlessly for our students to click their target. So, believe on us and our advice, and we assured you about your sure success.