Home > Mobile >  Running my function to convert a number to an 8 length binary number prints NameError: 'new_rul
Running my function to convert a number to an 8 length binary number prints NameError: 'new_rul

Time:04-22

rule = 90
def binary_conversion(new_rule):
    _bin = bin(rule)
    new_rule = _bin[2:]
    for char in (new_rule):
        if len(new_rule) < 8:
            new_rule = "0"   new_rule
        else:
            return(new_rule)

print(binary_conversion(new_rule))

Code returns --> NameError: name 'new_rule' is not defined. It should show the 8 char length binary conversion.

Now if I run the code without the function it prints the correct conversion but instead prints it 6 times!

rule = 90
_bin = bin(rule)
new_rule = _bin[2:]
for char in new_rule:
    if len(new_rule) < 8:
        new_rule = "0"   new_rule
    else:
        print(new_rule)

CodePudding user response:

You are trying to pass a variable new_rule to your function. That variable isn't in scope where you're trying to utilise it. Having said that, what I think you really meant was:

print(binary_conversion(rule))

You could also minimise your function to this:

def binary_conversion(new_rule):
    return f'{new_rule:08b}'

CodePudding user response:

For the first block of code, I believe you meant to use print(binary_conversion(rule)). new_ruleis defined inside the function therefore its a local variable and can only be used inside the function.

For the second block of code, you are looping through new_rule while editing it:

##Before looping:
new_rule = 1011010 # Which is a length of 7

##First loop:
len(new_rule) < 8 is True, so we add 0 at the beginning
new_rule = 01011010 # length of 8

##Second To 8th loop:
len(new_rule) < 8 is False because new_rule is 8 length long so we pring its value

Your mistake is you didn't pay attention to the length of new_rule whilst modifying its value.

CodePudding user response:

you can use zfill(8) to do it

bin(number)[2:].zfill(8)
  • Related