Question: Python 3.6- Create a try exception in code when the user enters a negative number it asks to enter valid data in the following code.
Python 3.6-
Create a try exception in code when the user enters a negative number it asks to enter valid data in the following code. Provide indented source code with the exception for neg. integers. Thanks
def padWithZero(string): # returns the length of the string n = len(string) pad = 0 if n % 8 != 0: # obtain 8 characters in binary string pad = 8-(n - (n // 8) * 8) for i in range(pad): string += "0" return string def decToBin(num): binary = [] while (num > 0): a = int(float(num % 2)) # modifies the binary list binary.append(a) num = (num - a) / 2 binary.append(0) string = "" for j in binary[::-1]: string = string + str(j) string = padWithZero(string) return (string) def binToDec(binstr): binstr = padWithZero(binstr) num = int(binstr, 2) return num def binToDec(binary): decimal = 0 for digit in binary: decimal = decimal * 2 + int(digit) return (decimal) def binAdd(): a = input("What is your first binary string? ") b = input("What is your second binary string? ") c = (binToDec(a)) + (binToDec(b)) return (decToBin(c)) def binSub(): a = input("What is your first binary string? ") b = input("What is your second binary string? ") c = (binToDec(a)) - (binToDec(b)) return (decToBin(c)) print("Option 1: Convert a decimal number to binary ") print("Option 2: Add two binary strings ") print("Option 3: Subtract two binary strings ") print("Option 4: Exit ") print("Option 5: Convert a binary number to decimal ") k = int(input("What would you like to do ? ")) if k == 1: # allows user to enter an integer print(decToBin(int(input("What is your number? ")))) elif k == 2: print(binAdd()) elif k == 3: print(binSub()) elif k == 4: quit() elif k == 5: print(binToDec(input("What is your binary number? "))) Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
