A. K
A. K

Reputation: 15

Converting decimal numbers to binary with functions in python

I have to create a program to convert decimal numbers to binary for my class but im lost. These are the directions. 3 Files must be used

user_input.py

Obtain an integer from the user between 0-255.
No conversion or print statements allowed in the user_input.py
Obtaining the integer must be done in a function
No import statements allowed

conversion.py

Convert the number provided to a binary number (e.g., 254 provided and converted to 11111110)
No print statements, input statements, or built in functions to convert a number to binary. Conversion must be done manually.
Small hint, concatenating the 1s and 0s is going to be tough b/c python will want to add the numbers (e.g., 1+1 = 2 vs 1+1 = 11). So, how are you going to handle this issue?
The conversion must be done in a function
No import statements allowed

main.py

Print the eight bit binary representation (00000000 - 11111111) of the number provided and converted. To do so, you will have to access the necessary functions in conversion.py and user_input.py
Note - the program is only allowed to access functions. No direct access to variables allowed.
No input or conversions allowed in main.py Note - the binary print must only be the eight binary numbers. No commas, brackets etc. - ['1', '0', '0', ...] or [1,1,0,0,1..] are not allowed.

to make the function to get the inputted number I use

  def number ():
    num =int(input('Pick a number from 0 - 255'))
    return num
  number()

After that when I do not know how I would access it without importing it. This is the code I'm using to convert

def conversion(num):
cnv_bin = ''
num = ''
while num // 2 > 0:
    if num % 2 == 0:
        cnv_bin += '0'
    else:
        cnv_bin += '1'
    num = num // 2
return cnv_bin

In the last file I tried

import conversion
import user_input
print(conversion.conversion(user_input.number()))

and that gave me this error

Traceback (most recent call last):
File "C:/Users/adkir/PycharmProjects/lab_23/main.py", line 4, in <module>
print(conversion.conversion(user_input.number()))
File "C:\Users\adkir\PycharmProjects\lab_23\conversion.py", line 5, in 
conversion
while num // 2 > 0:
TypeError: unsupported operand type(s) for //: 'str' and 'int'

So basically im lost. Can anyone point me in the right direction so I can figure this out?

Upvotes: 0

Views: 557

Answers (1)

blhsing
blhsing

Reputation: 106465

Your conversion function takes num as a parameter and yet it overwrites num's value by assigning an empty string to it.

Remove the line:

num = ''

and it should work.

Upvotes: 1

Related Questions