so i wrote this code to take a base that is inputted by the user and a number inputted by the user and it is supposed to print the num with that base to binary. It does do what its supposed to do but it asks me for the base 3 times and then gives me the correct number here's the code
Asked
Active
Viewed 35 times
0
-
the format of the code didnt post correctly – JC102 Oct 12 '20 at 02:15
-
can you paste the code you have used and probably a sample input and expected output – Vaishak Oct 12 '20 at 07:40
1 Answers
0
So I believe this is a duplicate of This question if so then the code from their answer will work, you just need to use a base 2 to their function:
def numberToBase(number, base):
if number == 0:
return [0]
digits = []
while number:
digits.append(int(number % base))
number //= base
return digits[::-1]
So in your case:
print(numberToBase(int(input("What is your number?:")), 2))
Or if you want a string representation I would recommend this:
def number_to_base(number, base):
if number == 0:
return [0]
digits = []
while number:
digits.append(str(number % base))
number //= base
return "".join(digits[::-1])

Kieran Wood
- 1,297
- 8
- 15
-
yeah but i want to be able to input a custom base for instance number: 42 base : 10 = 42 – JC102 Oct 12 '20 at 02:26
-
@JC102 the function will allow that, the b value is for base. I will update the code with better variable naming. – Kieran Wood Oct 12 '20 at 02:27
-
if i want the base to be inputted by the user do i just add a input statement where the 2 is in the code you provided – JC102 Oct 12 '20 at 02:30
-
@JC102 yes, it would become ```numberToBase(int(input("What is your number?:")), int(input("What is your base?:")))``` – Kieran Wood Oct 12 '20 at 02:31
-
thanks that worked would there be a way i could take out the comma and the brackets and just make it the numbers – JC102 Oct 12 '20 at 02:33
-
@JC102 see the last example, also if this works please hit the checkmark so others see this answer is correct. Thanks! – Kieran Wood Oct 12 '20 at 02:36