mercredi 13 février 2019

An if-block does not execute even when value is True

My code simply changes a decimal number to a binary equivalent by asking the user for the decimal number and the bit size required. An if-statement on line 10 does not run code inside its block even when value is True. A sample value set is number:900 and bits:8.

I tried debugging the code and checking alignment but nothing works. When the value is False, the code works perfectly. However, when the value is True the block does not seem to execute.

However, if I pull the function out and run it separately, it seems to work perfectly.

def binStr(num, bits):
    s=''
    if num==0:
        for i in range(bits):
            s+='0'
        return s
    while(num!=0):
        s=str(num%2)+s
        num=num//2
    if(len(s)>bits):
        snew=s[-1:-(bits+1)]
    elif(len(s)<bits):
        snew=''
        for i in range(bits-len(s)):
            snew+='0'
        snew+=s
    return snew
def getInt():
    i=1
    while i==1:
        try:
            x=input("Enter a Positive Int:\n")
            if ((x=="exit") or (x=="Exit")):
                break
            else:
                a=int(x)
                bar=int(input("Number of Bits:\n"))
                t=binStr(a,bar)
                print("As Binary:", t)

        except:
            print("Not a Number.")


print("Welcome to Binary Printer\nEnter exit to quit at any time.")

getInt()

Expected: the statement in if block to get executed

Actual: When value is True, it skips the block completely. Note that when the function binStr is run separately it works perfectly.

Aucun commentaire:

Enregistrer un commentaire