Results 1 to 5 of 5

Thread: Python/programming, need help

  1. #1
    cpt_azad's Avatar Colonel
    Join Date
    Aug 2003
    Location
    Surrey, BC
    Posts
    6,646

    Question Mark

    The question asks for a program that converts decimal to binary using the division method (divide by 2, get rid of remainder, divide by 2, etc etc).

    I'm having trouble comprehending how to go about doing this in Python, like how do I save the fact that if theres a remainder then its a 1 (in binary/base2) and if there is no remainder that it's a 0 (in binary/base2).

    This is what I have so far:



    Code:
    num = int(raw_input("Please input a number in the range [0, 127]: "))
    if not(num > 0 and num <= 127):
        print "You entered an invalid number, please restart the program."
    num1 = num/2
    num2 = num1/2
    num3 = num2/2
    num4 = num3/2
    num5 = num4/2
    num6 = num5/2
    num7 = num6/2
    num8 = num7/2

    Jeff Loomis: He's so good, he doesn't need to be dead to have a tribute.

  2. Lounge   -   #2
    The idiosyncratic syntax of riddles interests me

  3. Lounge   -   #3
    cpt_azad's Avatar Colonel
    Join Date
    Aug 2003
    Location
    Surrey, BC
    Posts
    6,646
    Quote Originally Posted by Buffalo View Post
    Thanks

    Jeff Loomis: He's so good, he doesn't need to be dead to have a tribute.

  4. Lounge   -   #4
    cpt_azad's Avatar Colonel
    Join Date
    Aug 2003
    Location
    Surrey, BC
    Posts
    6,646
    Hmm, i posted there but I don't know how long it'll take for someone to reply, if anyone on here knows how to help me pls let me know

    Jeff Loomis: He's so good, he doesn't need to be dead to have a tribute.

  5. Lounge   -   #5
    Barbarossa's Avatar mostly harmless
    Join Date
    Jun 2002
    Location
    Over here!
    Posts
    15,180
    It's the remainders that give you the binary.

    In pseudocode: (I don't know python)

    Code:
    set worknum = num
    set answer = '' (the answer is built up from a string of 0s and 1s)
    while worknum > 0 do
       remainder = worknum MOD 2
       answer = str(remainder) + answer
       worknum = worknum DIV 2
    endwhile
    MOD and DIV are integer operatiors, usually standard functions of a language. The syntax may vary. Basically, DIV gives you the result of one number divided by the other, and MOD gives you the remainder of the same operation.

    Apparently in Python '/' is DIV and '%' is MOD, so I'm told.

    Well, possibly this may give you some idea.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •