Page 34 - Programming With Python 3
P. 34

An Introduction to STEM Programming with Python — 2019-09-03a                               Page 21
            Chapter 2 — Numbering Systems

                    25 0
                    12 1
             Free
                    6 0
                    3 0
                    1 1
                    0 1

            There is an easier way to do it in Python using something called a while loop. We will learn exactly
             eBook
            how they work in a future chapter, but now would be a good time to show a preview. The while
            statement repeats the suite, of three lines of code, while n is not zero. We will see the while statement
            in future chapters, but it makes the program much smaller. The example below will work for virtually
            any positive integer, just change the first line.

               1|  n = 101
             Edition
               2|  while(n):
               3|    r = n % 2
               4|    n = n //2
               5|    print(n,r)

                    50 1
            Please support this work at
                    25 0
                    12 1
                    6 0
                    3 0
                    1 1           http://syw2l.org
                    0 1


            Another Example:

            Convert 364 to binary.                                             Free
                                             364 / 2 = 182 r 0                0

                                             182 / 2 = 91 r 0                00
                                             91 / 2 = 45 r 1                100

                                                                           1100
                                             45 / 2 = 22 r 1       eBook
                                             22 / 2 = 11 r 0             01100
                                             11 / 2 = 5 r 1             101100

                                             5 / 2 = 2 r 1             1101100
                                             2 / 2 = 1 r 0      Edition
                                                                      01101100
                                             1 / 2 = 0 r 1           101101100



            Copyright 2019 — James M. Reneau Ph.D. — http://www.syw2l.org — This work is licensed
            under a Creative Commons Attribution-ShareAlike 4.0 International License.
   29   30   31   32   33   34   35   36   37   38   39