PDA

View Full Version : Python/programming, need help



cpt_azad
01-30-2007, 02:43 AM
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:





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

Buffalo
01-30-2007, 02:48 AM
You should look @ http://forums.devshed.com/python-programming-11/

cpt_azad
01-30-2007, 02:51 AM
You should look @ http://forums.devshed.com/python-programming-11/

Thanks :)

cpt_azad
01-30-2007, 03:04 AM
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 :)

Barbarossa
01-30-2007, 09:58 AM
It's the remainders that give you the binary.

In pseudocode: (I don't know python)


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. :idunno: