PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 7, 2022

[FIXED] how to convert decimal to binary by using repeated division in python

 August 07, 2022     decimal, python-3.x     No comments   

Issue

how to convert decimal to binary by using repeated division in python?

i know i have to use a while loop, and use modulus sign and others {%} and {//} to do this...but i need some kind of example for me to understand how its done so i can understand completely. CORRECT ME, if I'm wrong:

number = int(input("Enter a numberto convert into binary: "))

result = "" 
while number != 0:
    remainder = number % 2 # gives the exact remainder
    times = number // 2
    result = str(remainder) + result
    print("The binary representation is", result)
    break

Thank You


Solution

Making a "break" without any condition, makes the loop useless, so the code only executes once no matter what.

-

If you don't need to keep the original number, you can change "number" as you go.

If you do need to keep the original number, you can make a different variable like "times".

You seem to have mixed these two scenarios together.

-

If you want to print all the steps, the print will be inside the loop so it prints multiple times.

If you only want to print the final result, then the print goes outside the loop.

while number != 0:
    remainder = number % 2  # gives the exact remainder
    number = number // 2
    result = str(remainder) + result
print("The binary representation is", result)

-

The concatenation line:

Putting the print inside the loop might help you see how it works.

we can make an example:

the value in result might be "11010" (a string, with quotes)

the value in remainder might be 0 (an integer, no quotes)

str(remainder) turns the remainder into a string = "0" instead of 0

So when we look at the assignment statement:

result = str(remainder) + result

The right side of the assignment operator = is evaulated first.

The right side of the = is

str(remainder) + result

which, as we went over above has the values:

"0" + "11010"

This is string concatenation. It just puts one string on the end of the other one. The result is:

"0     11010"

"011010"

That is the value evaluated on the right side of the assignment statement.

result = "011010"

Now that is the value of result.



Answered By - beauxq
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing